Pandas将具有相同x轴的多个子图组合成1个条形图

时间:2017-03-01 12:23:08

标签: python pandas matplotlib

我循环遍历包含6个col_names的列表。我通过一次取3个循环循环,所以我可以在每次迭代后打印3个子图。 我有2个具有相同列名的数据帧,因此它们看起来完全相同,除了每个列名的直方图。

我想在同一个子图上绘制两个数据帧的类似列名。现在,我将他们的直方图绘制在两个独立的子图上。

目前,对于col' A' B'' C'在df_plot中:

enter image description here

和col' A',' B'' C'在df_plot2中: enter image description here

我只想要3个图表,我可以将相似的列名组合到同一个图表中,因此在同一个图表中有蓝色和黄色条。

在下方添加df_plot2无效。我想我没有正确定义我的第二个axs,但我不知道如何做到这一点。

col_name_list = ['A','B','C','D','E','F']
chunk_list = [col_name_list[i:i + 3] for i in xrange(0, len(col_name_list), 3)]
    for k,g in enumerate(chunk_list):
        df_plot = df[g]
        df_plot2 = df[g][df[g] != 0]

        fig, axs = plt.subplots(1,len(g),figsize = (50,20))
        axs = axs.ravel()

        for j,x in enumerate(g):
            df_plot[x].value_counts(normalize=True).head().plot(kind='bar',ax=axs[j], position=0, title = x, fontsize = 30)
            # adding this doesnt work.
            df_plot2[x].value_counts(normalize=True).head().plot(kind='bar',ax=axs[j], position=1, fontsize = 30)
                axs[j].title.set_size(40)
        fig.tight_layout()   

1 个答案:

答案 0 :(得分:0)

解决方案是在同一ax上绘图:

更改axs[j] to axs

for k,g in enumerate(chunk_list):
    df_plot = df[g]
    df_plot2 = df[g][df[g] != 0]

    fig, axs = plt.subplots(1,len(g),figsize = (50,20))
    axs = axs.ravel()

    for j,x in enumerate(g):
        df_plot[x].value_counts(normalize=True).head().plot(kind='bar',ax=axs, position=0, title = x, fontsize = 30)
        # adding this doesnt work.
        df_plot2[x].value_counts(normalize=True).head().plot(kind='bar',ax=axs, position=1, fontsize = 30)
            axs[j].title.set_size(40)
    fig.tight_layout() 

然后只需致电plt.plot()

  

示例这将在同一个子图上绘制x和y:

import matplotlib.pyplot as plt
x = np.arange(0, 10, 1)
y = np.arange(0, 20, 2)

ax = plt.subplot(1,1)
fig = plt.figure()
ax = fig.gca()
ax.plot(x)
ax.plot(y)

plt.show()

编辑:

现在有一个关键字参数。这样可以确保结果始终是2D numpy数组。

fig, ax2d = subplots(2, 2, squeeze=False)

如果需要将其转换为一维数组很容易:

axli = ax1d.flatten()