pythonmatplotlibpolar-plot

ax.set_facecolor between angles in a polar plot


Say I have a standard matplotlib polar plot:

import matplotlib.pyplot as plt
import numpy as np

r = np.arange(0, 2, 0.01)
theta = 2 * np.pi * r

fig, ax = plt.subplots(subplot_kw={'projection': 'polar'})
ax. Plot(theta, r)
ax.set_rmax(2)
ax.set_rticks([0.5, 1, 1.5, 2])  # Less radial ticks
ax.set_rlabel_position(-22.5)  # Move radial labels away from plotted line
ax. Grid(True)

ax.set_title("A line plot on a polar axis", va='bottom')
plt.show()

Which yields (source):

polar demo

In my case, the results are not trustful between certain angles (e.g. between 0º and 45º in the above figure), so I would like to change the plot background color, but only between those angles; i.e. apply ax.set_facecolor only between certain angles. Is it possible? I could not find online an example for that.


Solution

  • You can use axvspan(...) to color between two angles (in radians).

    import matplotlib.pyplot as plt
    import numpy as np
    
    r = np.arange(0, 2, 0.01)
    theta = 2 * np.pi * r
    
    fig, ax = plt.subplots(subplot_kw={'projection': 'polar'})
    ax.plot(theta, r)
    ax.set_rmax(2)
    ax.set_rticks([0.5, 1, 1.5, 2])  # Less radial ticks
    ax.set_rlabel_position(-22.5)  # Move radial labels away from plotted line
    ax.grid(True)
    startangle = 0
    endangle = 45
    ax.axvspan(np.deg2rad(startangle), np.deg2rad(endangle), facecolor='red', alpha=0.3)
    
    plt.show()
    

    matplotlib: coloring the background of a polar plot between two angles