【问题标题】:Pandas Bar Graph: Side By Side (No X or Y axises shared)Pandas 条形图:并排(不共享 X 或 Y 轴)
【发布时间】:2025-12-01 01:35:03
【问题描述】:

Two Bar Plots- Non side by side

嗨, 我对 Pandas 和 Python 比较陌生。我一直试图让我的两个条形图并排显示,而不是像上图那样一个接一个地显示。它们不共享 y 或 x 轴,因为它们是单独的自变量。我想介绍它,以便我可以强调它们之间的密切关系以及它们是重复变量。

到目前为止,我看过http://worksofscience.net/matplotlib/gridspec 其中 GridSpec 用于创建不同的网格进行绘图。 在创建两个大小相等的网格 ax1 和 ax2 之后,我尝试添加附加到它们各自变量的两个图,如下面的代码所示

fig1 = plt.figure(figsize=[15,8])
gs = GridSpec(100,100)
ax1 = fig1.add_subplot(gs[:,0:50])
ax2 = fig1.add_subplot(gs[:,51:100])

#saving the plots in variables
waterpointtype=waterindep.waterpoint_type.value_counts().plot(kind='bar',title ='Waterpoint_Type')
#plt.show()
waterpointtypegroup = waterindep.waterpoint_type_group.value_counts().plot(kind='bar',title='Waterpoint_Type_Group')
#plt.show()
#plotting on those axes
ax1.plot(waterpointtype)
ax2.plot(waterpointtypegroup)

fig1.savefig('waterpointcomparison.png', format ='png', dpi =600)
plt.show()

但是,我最终得到 Index Error: index 51 is out of bounds for axis 0 with size 3 我无法理解。如果您有解决此错误的方法或我可以并排绘制条形图的其他方式,我将不胜感激。 非常感谢!

【问题讨论】:

    标签: python pandas matplotlib


    【解决方案1】:

    将坐标轴传递给绘图调用:

    waterindep['waterpoint_type'].value_counts().plot(
        kind='bar',title='Waterpoint_Type', ax=ax1)
    waterindep['waterpoint_type_group'].value_counts().plot(
        kind='bar',title='Waterpoint_Type_Group', ax=ax2)
    

    import numpy as np
    import pandas as pd
    import matplotlib.pyplot as plt
    import matplotlib.gridspec as gridspec
    np.random.seed(2015)
    
    fig1 = plt.figure(figsize=[15,8])
    gs = gridspec.GridSpec(100,100)
    ax1 = fig1.add_subplot(gs[:,0:50])
    ax2 = fig1.add_subplot(gs[:,51:100])
    waterindep = pd.DataFrame(np.random.randint(10, size=(100,2)), 
                              columns=['waterpoint_type', 'waterpoint_type_group'])
    waterindep['waterpoint_type'].value_counts().plot(kind='bar',title='Waterpoint_Type', ax=ax1)
    waterindep['waterpoint_type_group'].value_counts().plot(kind='bar',title='Waterpoint_Type_Group', ax=ax2)
    plt.show()
    

    请注意,您也可以使用

    fig, axs = plt.subplots(figsize=[15,8], ncols=2)
    ax1, ax2 = axs
    

    而不是gridspec.GridSpec 来创建轴。它将有 “开箱即用”的轴之间的间距更好看。

    【讨论】: