在Matplotlib中创建条形图时出错

2024-05-18 18:22:31 发布

您现在位置:Python中文网/ 问答频道 /正文

我想在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()

谁能告诉我,是什么导致了这个错误?我很感激你的每一句话


Tags: theimportlabelsmatplotlibbarpltaxwidth
1条回答
网友
1楼 · 发布于 2024-05-18 18:22:31

问题是您有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')

enter image description here

相关问题 更多 >

    热门问题