Circular / polar histogram in python

Cupitor picture Cupitor · Mar 21, 2014 · Viewed 23.7k times · Source

I have periodic data and the distribution for it is best visualised around a circle. Now the question is how can I do this visualisation using matplotlib? If not, can it be done easily in Python?

Here I generate some sample data which I would like to visualise with a circular histogram:

import matplotlib.pyplot as plt
import numpy as np

# Generating random data
a = np.random.uniform(low=0, high=2*np.pi, size=50)

There are a few examples in a question on SX for Mathematica.

I would like to generate a plot which looks something like one of the following: enter image description hereenter image description here

Answer

tom10 picture tom10 · Mar 21, 2014

Building off of this example from the gallery, you can do

enter image description here

import numpy as np
import matplotlib.pyplot as plt

N = 80
bottom = 8
max_height = 4

theta = np.linspace(0.0, 2 * np.pi, N, endpoint=False)
radii = max_height*np.random.rand(N)
width = (2*np.pi) / N

ax = plt.subplot(111, polar=True)
bars = ax.bar(theta, radii, width=width, bottom=bottom)

# Use custom colors and opacity
for r, bar in zip(radii, bars):
    bar.set_facecolor(plt.cm.jet(r / 10.))
    bar.set_alpha(0.8)

plt.show()

Of course, there are many variations and tweeks, but this should get you started.

In general, a browse through the matplotlib gallery is usually a good place to start.

Here, I used the bottom keyword to leave the center empty, because I think I saw an earlier question by you with a graph more like what I have, so I assume that's what you want. To get the full wedges that you show above, just use bottom=0 (or leave it out since 0 is the default).