Shade 'cells' in polar plot with matplotlib

matplotlib, plot, python

Solution

Sure! Just use `pcolormesh` on a polar axes.

E.g.

import matplotlib.pyplot as plt
import numpy as np

# Generate some data...
# Note that all of these are _2D_ arrays, so that we can use meshgrid
# You'll need to "grid" your data to use pcolormesh if it's un-ordered points
theta, r = np.mgrid[0:2*np.pi:20j, 0:1:10j]
z = np.random.random(theta.size).reshape(theta.shape)


fig, (ax1, ax2) = plt.subplots(ncols=2, subplot_kw=dict(projection='polar'))


ax1.scatter(theta.flatten(), r.flatten(), c=z.flatten())
ax1.set_title('Scattered Points')

ax2.pcolormesh(theta, r, z)
ax2.set_title('Cells')

for ax in [ax1, ax2]:
    ax.set_ylim([0, 1])
    ax.set_yticklabels([])

plt.show()

If your data isn't already on a regular grid, then you'll need to grid it to use pcolormesh.

It looks like it's on a regular grid from your plot, though. In that case, gridding it is quite simple. If it's already ordered, it may be as simple as calling `reshape`. Otherwise, a simple loop or exploiting `numpy.histogram2d` with your `z` values as weights will do what you need.

Problem

I've got a bunch of regularly distributed points (θ = n*π/6, r=1...8), each having a value in [0, 1]. I can plot them with their values in matplotlib using ``` polar(thetas, rs, c=values) ``` But rather then having just a meagre little dot I'd like to shade the corresponding 'cell' (ie. everything until halfway to the adjacent points) with the colour corresponding to the point's value: (Note that here my values are just [0, .5, 1], in really they will be everything between 0 and 1. Is there any straight-forward way of realising this (or something close enough) with matplotlib? Maybe it's easier to think about it as a 2D-histogram?

Original source