Friday, March 26, 2010

Matplotib - adding patterns to bars

Matplotlib is an excellent library for building graphs in python. I've used it before to create graphs for school and my post on jacks or better. Today, I needed to create a bar chart for black and white printing, so the standard color scheme wouldn't work! I tried to find documentation online for how to do this, and found nothing. Finally, I figured it out. You can use the hatch property in the optional kwargs arguments to create the patterns. For example, the code looks something like this
1:  kwargs = {'hatch':'.'}
2: rects = ax.bar(left, height, width, color='w', **kwargs)
This creates a bar with dots in the center. Here's an example:


Here's all of the code:
1:  import numpy as np  
2: import matplotlib.pyplot as plt
3:
4: N = 2
5: ind = np.arange(N) # the x locations for the groups
6: offset = 0.05
7: width = 0.24 # the width of the bars
8:
9: fig = plt.figure()
10: ax = fig.add_subplot(111)
11:
12: baseline = [7.64, 3.89]
13: baselineStd = [0.59, 0.06]
14: kwargs = {"hatch":'x'}
15: rects1 = ax.bar(offset+ind, baseline, width, color='w', ecolor='k', yerr=baselineStd, **kwargs)
16:
17: leaf = [7.06, 3.69]
18: leafStd = [0.67, 0.12]
19: kwargs = {"hatch":'.'}
20: rects2 = ax.bar(offset+ind+width, leaf, width, color='w', ecolor='k', yerr=leafStd, **kwargs)
21:
22: ultrapeer = [5.76, 3.25]
23: ultrapeerStd = [0.32, 0.19]
24: kwargs = {"hatch":'/'}
25: rects3 = ax.bar(offset+ind+width+width, ultrapeer, width, color='w', ecolor='k', yerr=ultrapeerStd, **kwargs)
26:
27: # add labels
28: ax.set_ylabel('Estimated Lifetime (hours)')
29: ax.set_xticks(offset+ind+width+width/2)
30: ax.set_xticklabels( ('Inactive Mac2', 'Active Mac2') )
31:
32: ax.legend( (rects1[0], rects2[0], rects3[0]), ('Baseline', 'Leaf', 'Ultrapeer') )
33:
34: plt.show()

No comments:

Post a Comment