【问题标题】:Unable to execute subplot command for multiple graphs in matplotlib pyplot无法在 matplotlib pyplot 中为多个图形执行 subplot 命令
【发布时间】:2020-11-05 06:58:23
【问题描述】:

这是我的数据框(命名为人口普查):

    Ethnicity   USA All CA All  USA Children    CA Children
0   Black       0.12    0.05            0.14    0.05
1   Hispanic    0.18    0.38            0.24    0.50
2   White       0.62    0.39            0.52    0.29
3   Other       0.08    0.18            0.10    0.16

我试图显示平行图,但似乎无法找到我哪里出错了 这是我的代码:

error im facing:
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-32-c9aa8709606a> in <module>
----> 1 fig, (ax1,ax2,ax3,ax4) = plt.subplots(nrows = 2, ncols = 2)
      2 plt.tight_layout()
      3 ax1 = census[['USA All','CA All','Ethnicity']]
      4 ax1.plot.barh()
      5 

ValueError: not enough values to unpack (expected 4, got 2)
fig, (ax1,ax2,ax3,ax4) = plt.subplots(nrows = 2, ncols = 2)
plt.tight_layout()
ax1 = census[['USA All','CA All','Ethnicity']]
ax1.plot.barh()

ax2 = census[['USA All','CA Children','Ethnicity']]
ax2.plot.barh()

ax3 = census[['USA Children','CA Children','Ethnicity']]
ax3.plot.barh()

ax4 = census[['USA All','USA Children','Ethnicity']]
ax4.plot.barh()

plt.tight_layout()

【问题讨论】:

    标签: matplotlib subplot


    【解决方案1】:

    如果误差因子绘制了多个子图,则需要将其矩阵结构与斧头的规格相匹配。将每个图形与斧头相关联。您创建的图表是基于我的估计,可能不是您想要的。

    import matplotlib.pyplot as plt
    
    fig, [[ax1,ax2],[ax3,ax4]] = plt.subplots(nrows=2, ncols=2, figsize=(12,9))
    
    df1 = census[['Ethnicity','USA All','CA All']]
    df1.plot(kind='barh', x='Ethnicity', y=['USA All','CA All'],ax=ax1)
    
    df2 = census[['Ethnicity','USA All','CA Children']]
    ax2 = df2.plot(kind='barh', x='Ethnicity', y=['USA All','CA Children'], ax=ax2)
    
    df3 = census[['Ethnicity','USA Children','CA Children']]
    ax3 = df3.plot(kind='barh', x='Ethnicity', y=['USA Children','CA Children'], ax=ax3)
    
    df4 = census[['Ethnicity','USA All','USA Children']]
    ax4 = df4.plot(kind='barh', x='Ethnicity', y=['USA All','USA Children'], ax=ax4)
    
    plt.tight_layout()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-06-24
      • 2014-01-14
      • 1970-01-01
      • 2022-10-16
      • 1970-01-01
      • 2012-05-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多