barh plot失败,其中" ValueError:不兼容的大小:参数' width'必须是长度2或标量"

时间:2017-05-03 01:57:42

标签: python matplotlib bar-chart

我希望连续有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或标量

1 个答案:

答案 0 :(得分: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()

enter image description here

相关问题