【问题标题】:subplots in matplotlib using histogrammatplotlib 中的子图使用直方图
【发布时间】:2013-12-04 14:09:36
【问题描述】:
diff  = [[10,20,30],[40,50,60],[70,80,90]]
comp = ["foo","bar","baz"]
fig,ax = plt.subplots()
for foo in range(0, len(diff)):
        x = [diff[foo]]
        name = comp
        color = ['0.1', '0.2', '0.3']
        label = ['1000000','1200000', '1400000']
        y = zip(*x)
        pos = np.arange(len(x))
        width = 1. / (1 + len(x))

        fig = plt.subplot(3,1,foo)
        for idx, (serie, color,label) in enumerate(zip(y, color,label)):
                ax.bar(pos + idx * width, serie, width, color=color,label=label)
        fig = plt.gcf()
        fig.set_size_inches(28.5,10.5)

        ax.set_xticks(pos + 1.5*width)
        plt.ylabel(name[foo])
        ax.set_xticklabels(comp)
        ax.legend()
        plt.gray()
plt.savefig("file" + '.jpg', bbox_inches='tight', pad_inches=0.5,dpi=100)
plt.clf()

我想对foo bar and baz 进行子图。但是当我尝试使用上面的代码来做到这一点时。数据未显示在图表上。知道为什么吗?

【问题讨论】:

  • 我发现了一个非常讨厌的快捷方式,我不喜欢它。使用Montage 加入图像。 :) 像这样montage -geometry 500 image1 image2 [...] output
  • 你已经调用了两次subplots:一次在没有参数的循环之前,它创建了一个只有一个轴的图形,但是在循环中你再次调用它(3,1, ...) 你想要将第二个调用移到顶部,然后在三个轴中的每一个中绘制一次。

标签: python matplotlib histogram subplot


【解决方案1】:

当您在循环内调用subplot 时,您将替换第一个fig,这是一个固定版本。看到subplots返回的ax是一个np.ndarray,所以你必须给一个索引ax[foo]来获取AxesSubplot对象。

diff  = [[10, 20, 30], [40, 50, 60], [70, 80, 90]]
comp = ["foo", "bar", "baz"]
fig, ax = plt.subplots(3, 1)
for foo in range(0, len(diff)):
        x = [diff[foo]]
        name = comp
        color = ['0.1', '0.2', '0.3']
        label = ['1000000', '1200000', '1400000']
        y = zip(*x)
        pos = np.arange(len(x))
        width = 1. / (1 + len(x))
        for idx, (serie, color,label) in enumerate(zip(y, color,label)):
                ax[foo].bar(pos + idx * width, serie, width, color=color,label=label)
        fig.set_size_inches(28.5, 10.5)
        ax[foo].set_xticks(pos + 1.5*width)
        plt.ylabel(name[foo])
        ax[foo].set_xticklabels(comp)
        ax[foo].legend()
        plt.gray()
fig.savefig("file" + '.jpg', bbox_inches='tight', pad_inches=0.5, dpi=100)
plt.clf()

【讨论】:

  • 为什么每次循环都调用gcf()并调整图形大小?你应该使用fig.savefig(...) 而不是plt.savefig
  • @tcaswell 谢谢!我刚刚从 OP 复制了代码并修复了问题,但没有引起足够的重视...
猜你喜欢
  • 2012-07-12
  • 2011-07-16
  • 2016-06-09
  • 2016-01-14
  • 2015-10-25
  • 2018-11-03
  • 2013-04-27
相关资源
最近更新 更多