matplotlib 中 FigSize 大小调整不一致

2023-12-07

我有几个不同的条形图,可以用不同数量的条形图生成。因此,图形的总宽度和高度会有所不同,但我希望所有条形图的条形尺寸一致。

到目前为止,我尝试的是根据条数按比例调整Figsize的大小。这似乎并不一致。

这是示例代码:

nb_bars_list = [2, 10]

for i, nb_bars in enumerate(nb_bars_list):
    # Resize proportionally to the number of bars
    figsize = [1+nb_bars, 5]
    # Prepare the ticks
    ticks = np.arange(1, 1+nb_bars, 1)
    # Generate random points
    points = [np.random.randn(10) for x in xrange(nb_bars)]
    # Make the plot
    fig, ax = plt.subplots()
    if figsize:
        fig.set_size_inches(figsize[0], figsize[1], forward=True)
    for b in xrange(nb_bars):
        ax.bar(ticks[b], points[b].mean())
    fig.savefig('test%i' % i, bbox_inches='tight')

Which results in: 2-bars 10-bars

如果我们使用 GIMP 将两者重叠,我们可以清楚地注意到条形宽度的差异:

both-bars

无论条数有多少,如何确保条的宽度相同?

我正在使用 matplotlib 2。


要设置图形大小以使图形中不同数量的条形始终具有相同的宽度,需要考虑图形边距。此外,还需要在所有情况下均等地设置绘图的 xlimit。

import matplotlib.pyplot as plt
import numpy as np

nb_bars_list = [2, 10]
margleft = 0.8 # inch
margright= 0.64 # inch
barwidth = 0.5 # inch


for i, nb_bars in enumerate(nb_bars_list):
    # Resize proportionally to the number of bars
    axwidth = nb_bars*barwidth # inch
    figsize = [margleft+axwidth+margright, 5]
    # Prepare the ticks
    ticks = np.arange(1, 1+nb_bars, 1)
    # Generate random points
    points = [np.random.randn(10) for x in xrange(nb_bars)]
    # Make the plot
    fig, ax = plt.subplots(figsize=figsize)
    fig.subplots_adjust(left=margleft/figsize[0], right=1-margright/figsize[0])

    for b in xrange(nb_bars):
        ax.bar(ticks[b], points[b].mean())
    ax.set_xlim(ticks[0]-0.5,ticks[-1]+0.5)
    #fig.savefig('test%i' % i, bbox_inches='tight')
plt.show()

enter image description here

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

matplotlib 中 FigSize 大小调整不一致 的相关文章

随机推荐