Creating double boxplots- i.e two boxes for each x-value

Question:

I want to create a boxplot diagram where each x-value has two boxplots right next to each other, kinda like this:

enter image description here

Is this possible? If so, how can I do it?

Asked By: The Unfun Cat

||

Answers:

I don’t know if there is a name for this kind of plot but you can create this simply by using the pyplot.boxplot function and passing in the positions keyword to shift the boxes slightly. Here is an example

x = np.array([1000,2000])
data1 = np.array([np.random.normal(loc=0.5,size=100),np.random.normal(loc=1.5,size=100)]).T
data2 = np.array([np.random.normal(loc=2.5,size=100),np.random.normal(loc=0.75,size=100)]).T
plt.figure()
plt.boxplot(data1,0,'',positions=x-100,widths=150)
plt.boxplot(data2,0,'',positions=x+100,widths=150)
plt.xlim(500,2500)
plt.xticks(x)
plt.show()

First we create the two sets of data for the left and right boxes and the corresponding x locations. Next we plot each set of data specifying the position to be x but shifted left and right slightly respectively. Note: Because our x positions are far apart we also have to adjust the widths using the widths keyword. Now we set the correct x-axis limits and then finally replace the x-tick locations with the ones we want.

It produces this output:

enter image description here

Answered By: Dan

thank you for the code, this is exactly what i am looking for. however I have 3 x-values (with 2 boxplots intended for each) and I am reading the y-data from an excel file (1 column per box); i can figure out which part of the code i need to tweak to change it from 2 to 3 x points, and i beleive the biggest issue is the positions that i cannot figure out what to specify. can you please advise?

Answered By: Alireza Rahnama
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.