如何在matplotlib中绘制多个水平箱线图?
我正在尝试制作一个 matplotlib 图形,里面有多个水平的箱线图,一个叠一个。文档里有介绍怎么制作一个单独的水平箱线图,以及怎么制作多个竖着的箱线图,具体可以在这一部分找到。
我尝试使用子图,代码如下:
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()
但是我的输出结果只显示了一个水平的箱线图。
有没有人有什么建议呢?
编辑:感谢 @joaquin,我修正了 plt.subplot
的调用,现在子图版本可以正常工作了,但我还是希望所有的箱线图能在一个图形里显示...
2 个回答
1
尝试:
plt.subplot('{0}{1}{2}'.format(totfigs, 1, i+1) # n rows, 1 column
或者
plt.subplot('{0}{1}{2}'.format(1, totfigs, i+1)) # 1 row, n columns
根据文档说明:
subplot(*args, **kwargs)
这个命令用来创建子图,也就是生成坐标轴,格式是:
subplot(numRows, numCols, plotNum)
其中 plotNum = 1 表示第一个图,后面的 plotNums 会先填满每一行。最大值 plotNum 必须等于 numRows 乘以 numCols。
如果你想把它们放在一起,可以方便地进行偏移。举个例子,使用一个固定的偏移量:
for i in np.arange(totfigs):
x = np.random.random(50)
plt.boxplot(x+(i*2),vert=0)
7
如果我理解得没错,你只需要给箱线图传递一个列表(或者一个二维数组),里面包含你想要绘制的每个数组。
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()