Is there a way to group boxplots in matplotlib?
Assume we have three groups “A”, “B”, and “C” and for each we want to create a boxplot for both “apples” and “oranges”. If a grouping is not possible directly, we can create all six combinations and place them linearly side by side. What would be to simplest way to visualize the groupings? I’m trying to avoid setting the tick labels to something like “A + apples” since my scenario involves much longer names than “A”.
Advertisement
Answer
How about using colors to differentiate between “apples” and “oranges” and spacing to separate “A”, “B” and “C”?
Something like this:
JavaScript
x
60
60
1
from pylab import plot, show, savefig, xlim, figure,
2
hold, ylim, legend, boxplot, setp, axes
3
4
# function for setting the colors of the box plots pairs
5
def setBoxColors(bp):
6
setp(bp['boxes'][0], color='blue')
7
setp(bp['caps'][0], color='blue')
8
setp(bp['caps'][1], color='blue')
9
setp(bp['whiskers'][0], color='blue')
10
setp(bp['whiskers'][1], color='blue')
11
setp(bp['fliers'][0], color='blue')
12
setp(bp['fliers'][1], color='blue')
13
setp(bp['medians'][0], color='blue')
14
15
setp(bp['boxes'][1], color='red')
16
setp(bp['caps'][2], color='red')
17
setp(bp['caps'][3], color='red')
18
setp(bp['whiskers'][2], color='red')
19
setp(bp['whiskers'][3], color='red')
20
setp(bp['fliers'][2], color='red')
21
setp(bp['fliers'][3], color='red')
22
setp(bp['medians'][1], color='red')
23
24
# Some fake data to plot
25
A= [[1, 2, 5,], [7, 2]]
26
B = [[5, 7, 2, 2, 5], [7, 2, 5]]
27
C = [[3,2,5,7], [6, 7, 3]]
28
29
fig = figure()
30
ax = axes()
31
hold(True)
32
33
# first boxplot pair
34
bp = boxplot(A, positions = [1, 2], widths = 0.6)
35
setBoxColors(bp)
36
37
# second boxplot pair
38
bp = boxplot(B, positions = [4, 5], widths = 0.6)
39
setBoxColors(bp)
40
41
# thrid boxplot pair
42
bp = boxplot(C, positions = [7, 8], widths = 0.6)
43
setBoxColors(bp)
44
45
# set axes limits and labels
46
xlim(0,9)
47
ylim(0,9)
48
ax.set_xticklabels(['A', 'B', 'C'])
49
ax.set_xticks([1.5, 4.5, 7.5])
50
51
# draw temporary red and blue lines and use them to create a legend
52
hB, = plot([1,1],'b-')
53
hR, = plot([1,1],'r-')
54
legend((hB, hR),('Apples', 'Oranges'))
55
hB.set_visible(False)
56
hR.set_visible(False)
57
58
savefig('boxcompare.png')
59
show()
60