不一致的figsize在matplotlib中调整大小

gab*_*ous 4 python matplotlib python-2.7

我有几个不同的条形图数字,用不同数量的条形成.因此,图形的总宽度和高度会有所不同,但我希望所有条形图的条形尺寸始终相同.

到目前为止我尝试的是按比例调整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')
Run Code Online (Sandbox Code Playgroud)

结果如下: 2条 10条

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

这两个酒吧

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

我正在使用matplotlib 2.

Imp*_*est 6

要设置图形大小,使图形中不同数量的条形总是具有相同的宽度,则需要考虑图形边距.还需要在所有情况下均等地设置图的xlimits.

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()
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

  • 那是正确的。整个解决方案基于设置子图参数。如果调用`tight_layout`,它将只计算自己最适合的子图参数并覆盖之前设置的任何内容。 (2认同)