Search code examples
pythonmatplotlibaxis-labelspolar-coordinates

Bring radial axes labels in front of lines of polar plot matplotlib


I am trying to get the radial (or y-axis) labels on a polar plot to go on top of the lines that are plotted on the graph. Right now they are underneath the lines and are covered up.

enter image description here

Here is a simplified version of the code for just one city and one line:

fig, ax = plt.subplots(figsize=(10,6) , nrows=1, ncols=1,subplot_kw=dict(projection='polar'))
rmax = 15
rticks = np.arange(9,rmax,1.5)
rticklabel = np.arange(18,rmax*2,3).astype(int)

theta = np.arange(0,6.3, 0.17) #plots a circle
r = np.ones(len(theta))*(21/2)
ax.plot(theta, r,c='r', linestyle='-',linewidth = 4,zorder=1)

ax.set_rmax(rmax)
ax.set_rticks(rticks)  # less radial ticks

ax.set_xticklabels([])  
ax.set_rlabel_position(285)  # get radial labels away from plotted line
ax.grid(True)

ax.set_facecolor('white') 
ax.yaxis.grid(color='silver', linestyle=':',linewidth = 1.5,zorder=10)
ax.set_yticklabels(rticklabel,fontsize=12,zorder=10) #this zorder does nothing

I have already tried this:

plt.rcParams["axes.axisbelow"] = False

This brings the text to the front as I wish, however, it also brings the grid lines. I would like those to stay behind the colored lines.

I have also tried changing the zorder of the yaxis grid, but that does not work.

Most solutions for this are not for the polar axis. Any suggestions?


Solution

  • Unfortunately it seems that the zorder of the grid and labes is tied to that of the axes: https://matplotlib.org/api/_as_gen/matplotlib.axes.Axes.grid.html

    One possible solution even if not elegant is to draw the gridlines yourself

    fig, ax = plt.subplots(figsize=(10,6) , nrows=1, ncols=1,subplot_kw=dict(projection='polar'))
    rmax = 15
    rticks = np.arange(9,rmax,1.5)
    rticklabel = np.arange(18,rmax*2,3).astype(int)
    
    theta = np.arange(0,6.3, 0.17) #plots a circle
    r = np.ones(len(theta))*(21/2)
    ax.plot(theta, r,c='r', linestyle='-',linewidth = 4,zorder=2)
    
    ax.set_rticks(rticks)  # less radial ticks
    
    ax.set_xticklabels([])  
    ax.set_rlabel_position(285)  # get radial labels away from plotted line
    ax.xaxis.grid(True)
    ax.yaxis.grid(False)
    
    ax.set_facecolor('white') 
    ax.set_yticklabels(rticklabel,fontsize=12,zorder=10) #this zorder does nothing
    ax.yaxis.set_zorder(10)
    #ax.yaxis.grid(color='silver', linestyle=':',linewidth = 1.5,zorder=10)
    
    x = np.arange(0,2*np.pi,0.05)
    y = np.outer( np.ones(x.shape), rticks)
    ax.plot( x,y, zorder=1, color='silver', linestyle=':')
    ax.set_ylim(0,rmax)
    

    enter image description here