pythonmatplotlib

Cannot remove frame/axes from a matplotlib plot


I got the following code from a colleague. It draws a polar plot showing the percentage of three things on three rings. I am not very sure how the polar plot is drawn in the code but it seems it is some conversion from a bar plot. The matplotlib version I am using is 3.9.2. I couldn't make the square frame around the rings disappear. As you can see the sample code, I tried various ways by searching online. Running the same code on Matplotlib 3.7.0 doesn't have the square frame showing. I feel this might be a simple one-line fix but couldn't figure it out. Hope someone can help me here. Thanks.

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from math import pi

data = [15, 20, 12]
fig, ax = plt.subplots(figsize=(6, 6), facecolor='white')
ax = plt.subplot(projection='polar', frameon=False)

startangle = 90
colors = ['#005a85', '#4c4c4d', '#048543']
colors_bg = ['#818589', '#818589', '#818589']

xs = [(i * pi *2)/ 100 for i in data]
xs_bg = [(i * pi *2)/ 100 for i in [100,100,100]]
ys = [-0.2, 1, 2.2]
left = (startangle * pi * 6)/ 360            #this is to control where the bar starts

# plot bars and points at the end to make them round
for i, x in enumerate(xs_bg):#draw the background grey circles
    ax.barh(ys[i], x, left=left, height=0.4, color=colors_bg[i])

for i, x in enumerate(xs):   
    ax.barh(ys[i], x, left=left, height=0.4, color=colors[i])
    ax.scatter(x+left, ys[i], s=60, color=colors[i], zorder=2)
    ax.scatter(left, ys[i]-0.01, s=60, color=colors[i], zorder=2)

plt.ylim(-4, 4)

# clear ticks, grids, spines
plt.xticks([])
plt.yticks([])
ax.spines.clear()

# Other attempts to remove the frame, none worked
ax.axis("off")
ax.set_axis_off()
ax.grid(False)
ax.get_xaxis().set_visible(False)
ax.get_yaxis().set_visible(False)
plt.gca().get_xaxis().set_visible(False)
plt.gca().get_yaxis().set_visible(False)

plt.tight_layout()
plt.show()

enter image description here


Solution

  • You created two subplots on top of each other. One with plt.subplots and the other with plt.subplot. At version 3.7 the original subplot was automatically deleted when the second was added on top. But that changed at v3.8. You should have seen a deprecation warning when running with v3.7. You successfully hide the second but not the first subplot. To fix, just don't make the first subplot. E.g. replace this line

    fig, ax = plt.subplots(figsize=(6, 6), facecolor='white')
    

    with one that only creates a figure

    fig = plt.figure(figsize=(6, 6), facecolor='white')
    

    enter image description here