Search code examples
pythonmatplotlibpolar-coordinates

Gradient color background on matplotlib polar plot


I'm plotting a spider chart in matplotlib, and want the background to be a colour gradient, but I can only see how to set the background to a solid colour. I want the gradient going radially (e.g. this). Is there a way to just write set_facecolor('name_of_colormap')?

MWE:

import numpy as np
import matplotlib.pyplot as ply

fig, ax = plt.subplots(subplot_kw={'projection': 'polar'})
r = [2, 1.5, 4, 3, 0.5, 2.5]
theta = [(2*np.pi)/6*i for i in range(6)]
ax.set_theta_zero_location("N") # Put 0 at the top
ax.set_rticks([])
ax.set_thetagrids([i*180/np.pi for i in theta[:-1]])
ax.set_theta_direction(-1)      # Make angles go clockwise
ax.set_xticklabels(['one', 'two', 'three', 'four', 'five', 'six'])
ax.set_facecolor("green")
ax.plot(theta, r, 'k')

Solution

  • You can use ax.pcolormesh to achieve that. Note that in the following example I have applied a cyclic color map and colors defines the the way color is going to be mapped to the colormap.

    import numpy as np
    import matplotlib.pyplot as ply
    import matplotlib.cm as cm
    
    fig, ax = plt.subplots(subplot_kw={'projection': 'polar'})
    r = [2, 1.5, 4, 3, 0.5, 2.5]
    theta = [(2*np.pi)/6*i for i in range(6)]
    ax.set_theta_zero_location("N") # Put 0 at the top
    ax.set_rticks([])
    ax.set_thetagrids([i*180/np.pi for i in theta[:-1]])
    ax.set_theta_direction(-1)      # Make angles go clockwise
    # ax.set_xticklabels(['one', 'two', 'three', 'four', 'five', 'six'])
    N = 500j
    rr, tt = np.mgrid[0:4:N, 0:2*np.pi:N]
    colors = rr / rr.max()
    ax.pcolormesh(tt, rr, colors, cmap=cm.hsv, shading="nearest")
    ax.plot(theta, r, 'k')
    

    enter image description here