How to draw polar hist2d/hexbin in matplotlib?
<p>I have a random vector (random length and random angle) and would like to plot its approximate PDF (probability density function) via <code>hist2d</code> or <code>hexbin</code>. Unfortunately they seems not to work with polar plots, the following code yields nothing:</p>

<pre><code>import numpy as np
import matplotlib.pyplot as plt

# Generate random data:
N = 1024
r = .5 + np.random.normal(size=N, scale=.1)
theta = np.pi / 2 + np.random.normal(size=N, scale=.1)

# Plot:
ax = plt.subplot(111, polar=True)
ax.hist2d(theta, r)
plt.savefig('foo.png')
plt.close()
</code></pre>

<p>I would like it to look like this: <a href="http://matplotlib.org/examples/pylab_examples/hist2d_demo.html" rel="nofollow noreferrer">pylab_examples example code: hist2d_demo.py</a> only in polar coordinates. The closest result so far is with colored scatter plot as <a href="https://stackoverflow.com/questions/20105364/how-can-i-make-a-scatter-plot-colored-by-density-in-matplotlib">adviced here</a>:</p>

<pre><code>import numpy as np
import matplotlib.pyplot as plt
from scipy.stats import gaussian_kde

# Generate random data:
N = 1024
r = .5 + np.random.normal(size=N, scale=.1)
theta = np.pi / 2 + np.random.normal(size=N, scale=.1)

# Plot:
ax = plt.subplot(111, polar=True)

# Using approach from:
# https://stackoverflow.com/questions/20105364/how-can-i-make-a-scatter-plot-colored-by-density-in-matplotlib
theta_r = np.vstack([theta,r])
z = gaussian_kde(theta_r)(theta_r)

ax.scatter(theta, r, c=z, s=10, edgecolor='')

plt.savefig('foo.png')
plt.close()
</code></pre>

<p><a href="https://i.stack.imgur.com/hBROt.png" rel="nofollow noreferrer">Image from the second version of the code</a></p>

<p>Is there a better way to make it more like real PDF generated with hist2d? <a href="https://stackoverflow.com/questions/19248787/build-up-and-plot-matplotlib-2d-histogram-in-polar-coordinates-using-the-legendr">This question</a> seems to be relevant (the resulting image is as expected), but it looks messy.</p>