如何在包含多个matplotlib直方图的图中设置x轴范围并创建单列图表?

11 投票
1 回答
38585 浏览
提问于 2025-04-18 08:13

我在设置每个直方图的x轴范围(xlim)时遇到了一些困难,并且想要把图放成一列,这样x轴的刻度就能对齐。因为我刚开始接触pandas,所以不太确定如何应用这个答案:使用pandas叠加多个直方图

>import from pandas import DataFrame, read_csv
>import matplotlib.pyplot as plt
>import pandas as pd

>df=DataFrame({'score0':[0.047771,0.044174,0.044169,0.042892,0.036862,0.036684,0.036451,0.035530,0.034657,0.033666],
              'score1':[0.061010,0.054999,0.048395,0.048327,0.047784,0.047387,0.045950,0.045707,0.043294,0.042243]})

>print df
     score0    score1
0  0.047771  0.061010
1  0.044174  0.054999
2  0.044169  0.048395
3  0.042892  0.048327
4  0.036862  0.047784
5  0.036684  0.047387
6  0.036451  0.045950
7  0.035530  0.045707
8  0.034657  0.043294
9  0.033666  0.042243

>df.hist()
>plt.xlim(-1.0,1.0)

结果只把x轴的一个边界设置成了[-1,1]。

我对R语言中的ggplot很熟悉,现在在尝试用python的pandas和matplotlib。我很乐意接受更好的绘图建议。任何帮助都非常感谢。

enter image description here

更新 #1 (@ct-zhu):

我尝试了以下方法,但在子图上编辑xlim似乎没有把新的x轴值的箱宽(bin widths)转换过来。结果是,图表现在有奇怪的箱宽,而且仍然有多于一列的图

for array in df.hist(bins=10):
    for subplot in array:
        subplot.set_xlim((-1,1))

enter image description here

更新 #2:

通过使用layout,我离目标更近了,但箱的宽度并不等于区间长度除以箱的数量。在下面的例子中,我设置了bins=10。因此,从[-1,1]这个区间来看,每个箱的宽度应该是2/10=0.20;然而,图表中并没有任何箱的宽度是0.20。

for array in df.hist(layout=(2,1),bins=10):
    for subplot in array:
        subplot.set_xlim((-1,1))

enter image description here

1 个回答

15

这里有两个子图,你可以分别访问和修改它们:

ax_list=df.hist()
ax_list[0][0].set_xlim((0,1))
ax_list[0][1].set_xlim((0.01, 0.07))

这里插入图片描述

你通过 plt.xlim 所做的更改,只会影响当前正在操作的坐标轴。在这个例子中,影响的是第二个图,因为它是最近生成的。


补充说明:

如果想把图表排成2行1列,可以使用 layout 参数。如果想让柱子的边缘对齐,可以使用 bins 参数。把x轴的范围设置为 (-1, 1) 可能不是个好主意,因为你的数据值都比较小。

ax_list=df.hist(layout=(2,1),bins=np.histogram(df.values.ravel())[1])
ax_list[0][0].set_xlim((0.01, 0.07))
ax_list[1][0].set_xlim((0.01, 0.07))

这里插入图片描述

或者可以在范围 (-1, 1) 之间精确指定10个柱子:

ax_list=df.hist(layout=(2,1),bins=np.linspace(-1,1,10))
ax_list[0][0].set_xlim((-1,1))
ax_list[1][0].set_xlim((-1,1))

这里插入图片描述

撰写回答