【问题标题】:barh plot fails with "ValueError: incompatible sizes: argument 'width' must be length 2 or scalar"barh 图因“ValueError:不兼容的尺寸:参数‘宽度’必须是长度 2 或标量”而失败
【发布时间】:2017-05-03 01:57:41
【问题描述】:

我想连续绘制 4 个图,因此我尝试将 ax 插入 list 并循环遍历列表。每个子图应类似于以下图:

df.plot(kind="barh")

但是,下面的代码不起作用:

df = pd.DataFrame({'a': [1, 2],'b': [3, 4]})
df.index = ["Row1", "Row2"]

ax1 = fig.add_subplot(1, 4, 1)
ax2 = fig.add_subplot(1, 4, 2)
ax3 = fig.add_subplot(1, 4, 3)
ax4 = fig.add_subplot(1, 4, 4)

axis_list = [ax1, ax2, ax3, ax4]

for ax in axis_list:
    ax.barh(df, kind='barh', width=0.8, colormap='Set1')

此异常失败:

ValueError:不兼容的大小:参数“宽度”必须是长度 2 或标量

【问题讨论】:

    标签: python matplotlib bar-chart


    【解决方案1】:

    您可以使用 plt.subplots 命令创建一个轴数组,这将整理您的代码。另请注意,您可以使用 df.plot 并指定要绘制的轴。

    import pandas as pd
    import matplotlib.pyplot as plt
    
    df = pd.DataFrame({'a': [1, 2],'b': [3, 4]})
    df.index = ["Row1", "Row2"]
    
    fig, axis_list = plt.subplots(1,4)
    for ax in axis_list:
        df.plot(kind='barh',ax=ax,width=0.8, colormap='Set1')
    fig.show()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-08-21
      • 2016-08-26
      • 2022-01-21
      • 2018-01-28
      • 2021-12-05
      • 1970-01-01
      • 2017-07-18
      相关资源
      最近更新 更多