Polar bar plot in Python

Here’s how to create a polar bar plot in matplotlib.


The trick is just to specify that you want polar coordinates when you create the axis. Then create a bar plot as normal.


from matplotlib.pyplot import figure, show
from math import pi

fig = figure()
ax = fig.add_subplot(111, polar=True)
x = [30,60,90,120,150,180]
x = [i*pi/180 for i in x]  # convert to radians

ax.bar(x,[1,2,3,4,5,6], width=0.4)
show()

Note that in the above example the “right” or “clockwise-most” edge is lined up with each specified x value. You can change this by subtracting width / 2 to each of the x values to center the bars on the x-values, like this:


from matplotlib.pyplot import figure, show
from math import pi

width = 0.4  # width of the bars (in radians)

fig = figure()
ax = fig.add_subplot(111, polar=True)
x = [30,60,90,120,150,180]

# Convert to radians and subtract half the width
# of a bar to center it.
x = [i*pi/180 - width/2 for i in x]
ax.bar(x,[1,2,3,4,5,6], width=width)
show()

Get funky . . .

The following is slightly modifed from the matplotlib examples:


import numpy as npy
import matplotlib.cm as cm
from matplotlib.pyplot import figure, show, rc

# force square figure and square axes (looks better for polar, IMHO)
fig = figure(figsize=(8,8))
ax = fig.add_axes([0.1, 0.1, 0.8, 0.8], polar=True)

N = 20
theta = npy.arange(0.0, 2*npy.pi, 2*npy.pi/N)  # random angles
radii = 10*npy.random.rand(N)  # random bar heights
width = npy.pi/4*npy.random.rand(N) # random widths

# Create the bar plot
bars = ax.bar(theta, radii, width=width, bottom=0.0)

# Step through bars (a list of Rectangle objects) and
# change color based on its height and set its alpha transparency
# to 0.5

for r,bar in zip(radii, bars):
    bar.set_facecolor( cm.jet(r/10.))
    bar.set_alpha(0.5)

show()

One Response to “Polar bar plot in Python”

  1. Justin Says:

    Thanks for the article. I have been playing with this for a couple days and everything seems to work except for a couple issues. You can actually simply center the label by adding ‘align=center’ as such

    ax.bar(x,[1,2,3,4,5,6], width=width, align=’center’)

    The first problem I am having is to have each pie have a fixed angle and prevent overlapping. I have 16 coordinates and I need each pie to be 22.5 degrees. There doesn’t seem to be anything in the documentation about this.

    The next problem is to have the angles start with 0 at the top and go clockwise like a regular compass. I am trying to make a wind rose with speed/direction. Let me know if you come across anything.

    Thanks,

    Justin

Leave a Reply