mishaF
mishaF

Reputation: 8314

Is there a way to make multiple horizontal boxplots in matplotlib?

I am trying to make a matplotlib figure that will have multiple horizontal boxplots stacked on one another. The documentation shows both how to make a single horizontal boxplot and how to make multiple vertically oriented plots in this section.

I tried using subplots as in the following code:

import numpy as np
import pylab as plt

totfigs = 5

plt.figure()
plt.hold = True

for i in np.arange(totfigs):    
    x = np.random.random(50)
    plt.subplot('{0}{1}{2}'.format(totfigs,1,i+1))
    plt.boxplot(x,vert=0)
plt.show()

My output results in just a single horizontal boxplot though.

Any suggestions anyone?

Edit: Thanks to @joaquin, I fixed the plt.subplot call line. Now the subplot version works, but still would like the boxplots all in one figure...

Upvotes: 5

Views: 10882

Answers (2)

joaquin
joaquin

Reputation: 85603

try:

plt.subplot('{0}{1}{2}'.format(totfigs, 1, i+1)    # n rows, 1 column

or

plt.subplot('{0}{1}{2}'.format(1, totfigs, i+1))    # 1 row, n columns

from the docstring:

subplot(*args, **kwargs)

Create a subplot command, creating axes with::

subplot(numRows, numCols, plotNum)

where plotNum = 1 is the first plot number and increasing plotNums fill rows first. max(plotNum) == numRows * numCols

if you want them all together, shift them conveniently. As an example with a constant shift:

for i in np.arange(totfigs):    
    x = np.random.random(50)
    plt.boxplot(x+(i*2),vert=0)

Upvotes: 1

Stephen Terry
Stephen Terry

Reputation: 6279

If I'm understanding you correctly, you just need to pass boxplot a list (or a 2d array) containing each array you want to plot.

import numpy as np
import pylab as plt

totfigs = 5

plt.figure()
plt.hold = True
boxes=[]
for i in np.arange(totfigs):    
    x = np.random.random(50)
    boxes.append(x)

plt.boxplot(boxes,vert=0)
plt.show()

enter image description here

Upvotes: 7

Related Questions