I would like to make a boxplot using two data sets. Each set is a list of floats. A and B are examples of the two data sets
A = []
B = []
for i in xrange(10):
l = [random.random() for i in xrange(100)]
m = [random.random() for i in xrange(100)]
A.append(l)
B.append(m)
I would like the boxplots for A and B to appear next to each other, not on each other. Also, I would like more gap between the different x-values and perhaps thinner boxes. My code is below and so is the plot it produces (the present code puts A on top of B). Thanks for helping.
def draw_plot(data, edge_color, fill_color):
bp = ax.boxplot(data, patch_artist=True)
for element in ['boxes', 'whiskers', 'fliers', 'medians', 'caps']:
plt.setp(bp[element], color=edge_color)
plt.xticks(xrange(11))
for patch in bp['boxes']:
patch.set(facecolor=fill_color)
fig, ax = plt.subplots()
draw_plot(A, "tomato", "white")
draw_plot(B, "skyblue", "white")
plt.savefig('sample_box.png', bbox_inches='tight')
plt.close()
Looking at the documentation of boxplot we find that it has a positions
argument, which can be used to set the positions of the boxplots. You would need to supply a list or array with as many elements as you want to draw boxplots.
import numpy as np; np.random.seed(1)
import matplotlib.pyplot as plt
A = np.random.rand(100,10)
B = np.random.rand(100,10)
def draw_plot(data, offset,edge_color, fill_color):
pos = np.arange(data.shape[1])+offset
bp = ax.boxplot(data, positions= pos, widths=0.3, patch_artist=True, manage_xticks=False)
for element in ['boxes', 'whiskers', 'fliers', 'medians', 'caps']:
plt.setp(bp[element], color=edge_color)
for patch in bp['boxes']:
patch.set(facecolor=fill_color)
fig, ax = plt.subplots()
draw_plot(A, -0.2, "tomato", "white")
draw_plot(B, +0.2,"skyblue", "white")
plt.xticks(xrange(10))
plt.savefig(__file__+'.png', bbox_inches='tight')
plt.show()
plt.close()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With