有没有办法在matplotlib中生成多个水平方框图?

2024-06-11 06:10:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试制作一个matplotlib图形,该图形将有多个水平方框图堆叠在一起。文档显示了如何制作单个水平方框图和如何制作多个垂直方向的图in this section.

我尝试在下面的代码中使用子块:

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调用行。现在子块版本可以工作了,但是仍然希望框线图都是一个图形。。。


Tags: in文档import图形matplotlibasnp水平
2条回答

如果我理解正确,您只需要传递一个包含要绘制的每个数组的列表(或2d数组)。

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

尝试:

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

从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

如果你想把它们都放在一起,就方便地把它们转移。以恒定位移为例:

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

相关问题 更多 >