python - matplotlib 中的子图使用直方图

标签 python matplotlib histogram subplot

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 .但是当我尝试使用上面的代码来做到这一点时。数据未显示在图表上。知道为什么吗?

最佳答案

当您在循环内调用 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()

关于python - matplotlib 中的子图使用直方图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20098386/

相关文章:

c - 为什么这段 C 代码输出的数据会形成有趣的波浪状直方图?

python - 在多个文件中进行测试

python - 标准环境下的GAE第三方库(例如MySQLdb)

python - 无法删除 matplotlib polycollection 中的原点

python - Matplotlib pandas plot_date 颜色类别

python - 如何在 Jupyter Notebook 中的绘图旁边显示数据框

javascript - 创建客户端日期时间直方图

matlab - 在 MATLAB 中测试单峰(Unimodality)或双峰(Bimodality)分布

python - 如何在Python中打开pdb文件?

python django 在服务器中运行 bash 脚本