2

I would like to create a barchart in matplotlib with 3 bars for each of 12 weeks. I adopted a code for barcharts with two bars but unfortunately I get the following error message: "ValueError: shape mismatch: objects cannot be broadcast to a single shape "

Here is my code:

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()

Can anyone tell me, what causes the error? I'd appreciate every comment.

1
  • You need to show the full traceback Commented Jun 7, 2020 at 20:32

1 Answer 1

2

The problem is that you have 13 labels but your remaining arrays, conventional, IC and CO have only 12 values. That's why, when you do np.arange(len(labels)), you have 13 x-values but only 12 values for conventional, IC and CO which results in shape mismatch error. Perhaps you want to plot only the first 12 labels.

Also, I think you want to use the correct x-positions for your bars to show them side by side. Therefore, use the following code

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

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks Sheldore for your answer and help.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.