在 matplotlib 中调整大小不一致 [英] Inconsistent figsize resizing in matplotlib

查看:38
本文介绍了在 matplotlib 中调整大小不一致的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have several different barplot figures to generate with a varying amount of bars. The total width and height of the figure thus varies, but I would like the bars to be consistently sized the same for all barplots.

到目前为止,我尝试的是将figsize的大小与条形的数量成比例地调整.这似乎并不一致.

What I tried so far is to resize the figsize proportionally to the number of bars. This does not seem to work consistently.

这是一个示例代码:

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')

这将导致:

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

If we overlap both using GIMP, we can clearly notice the difference in bar widths:

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

How can I ensure the same width for the bars, whatever the number of bars?

我正在使用matplotlib 2.

I am using matplotlib 2.

推荐答案

要设置图形尺寸,以使图形中不同数量的条形始终具有相同的宽度,则需要考虑图形边距.还需要在所有情况下均等地设置绘图的 xlimits.

To set the figure size such that different numbers of bars in a figure always have the same width would require to take the figure margins into account. Also one would need to set the xlimits of the plot equally in all cases.

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()

这篇关于在 matplotlib 中调整大小不一致的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆