我想在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()
谁能告诉我,是什么原因导致的错误?我会很感激每条评论。
问题是,你有13个labels
,但你的剩余阵列conventional
,IC
并且CO
只有12个值。这就是为什么当您执行时np.arange(len(labels))
,您有13个x值,但是仅有12个值conventional
,IC
并CO
导致形状不匹配错误。也许您只想绘制前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')
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句