【问题标题】:Error when creating a bar chart in Matplotlib在 Matplotlib 中创建条形图时出错
【发布时间】:2020-09-26 18:41:51
【问题描述】:

我想在 matplotlib 中创建一个条形图,每 12 周有 3 个条形图。我采用了带有两个条形图的条形图代码,但不幸的是我收到以下错误消息: “ValueError:形状不匹配:无法将对象广播到单个形状 "

这是我的代码:

import matplotlib
import matplotlib.pyplot as plt
import numpy as np


labels = ['Woche \n 1', 'Woche \n 5', 'Woche \n 6', 'Woche \n 8', 'Woche \n 8' , 'Woche \n 11', 'Woche \n 12',
         'Woche \n 41', 'Woche \n 43', 'Woche \n 46', 'Woche \n 48', 'Woche \n 49', 'Woche \n 50']
conventional = [1063, 520, 655, 47, 1516, 3200, 1618, 1378, 577, 504, 76, 1154]
IC = [345, 217, 229, 0, 800, 2700 ,1253, 896, 151, 382, 4, 797     ]
CO = [100, 130,  80, 0, 580, 2450, 1020, 650, 0, 300, 0, 600    ]

x = np.arange(len(labels))  # the label locations
width = 0.30  # the width of the bars

fig, ax = plt.subplots(figsize=(13,8), dpi=100)
rects1 = ax.bar(x - width/2, conventional, width, label='conventional')
rects2 = ax.bar(x + width/2, IC, width, label='IC')
rects3 = ax.bar(x + width/2, CO, width, label='CO')

# Add some text for labels, title and custom x-axis tick labels, etc.
ax.set_ylabel('Surplus', fontsize = 17)
ax.set_xticks(x)
ax.set_xticklabels(labels)
ax.tick_params(axis='both', which='major', labelsize=16)
ax.legend(loc='center left', bbox_to_anchor=(0.07, 1.04), fontsize = 16, ncol=3)



fig.tight_layout()

plt.savefig('PaperA_Results_7kWp.png', edgecolor='black', dpi=400, bbox_inches='tight')

plt.show()

谁能告诉我,是什么导致了错误?我会很感激每一条评论。

【问题讨论】:

  • 你需要显示完整的回溯

标签: python matplotlib


【解决方案1】:

问题是您有 13 个 labels,但您剩余的数组 conventionalICCO 只有 12 个值。这就是为什么当您执行 np.arange(len(labels)) 时,您有 13 个 x 值,但 conventionalICCO 只有 12 个值,这会导致形状不匹配错误。也许您只想绘制前 12 个标签。

另外,我认为您想为条形使用正确的 x 位置来并排显示它们。因此,请使用以下代码

x = np.arange(len(labels)-1)  # the label locations


width = 0.25
fig, ax = plt.subplots(figsize=(8, 6), dpi=100)
rects1 = ax.bar(x - width, conventional, width, label='conventional')
rects2 = ax.bar(x , IC, width, label='IC')
rects3 = ax.bar(x + width, CO, width, label='CO')

【讨论】:

  • 感谢Sheldore 的回答和帮助。
猜你喜欢
  • 2022-09-30
  • 2016-11-19
  • 1970-01-01
  • 2012-03-26
  • 1970-01-01
  • 2014-06-02
  • 2011-08-13
  • 1970-01-01
  • 2021-04-21
相关资源
最近更新 更多