ValueError: shape mismatch: objects cannot be broadcast to a single shape

I want to draw a grouped bar charts which compares the most watched Star Wars series by female and male. (I reference to the code from matplotlib’s website; it’s basically identical but somehow does not working. I wanna know why and how to correct it)

https://app.dataquest.io/c/25/m/201/guided-project%3A-star-wars-survey/8/exploring-the-data-by-binary-segments

Basics-Copy1.ipynb (46.4 KB)

original codes

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

labels = [‘S1’, ‘S2’, ‘S3’, ‘S4’, ‘S5’]
ranking_mean_male = [4.037825,4.224586,4.274882,2.997636,2.458629,3.002364]
ranking_mean_female = [3.429293,3.954660,4.418136,3.544081,2.569270,3.078086]

x = np.arange(len(labels))
width = 0.35

fig, ax = plt.subplots()
rects1 = ax.bar(x - width/2, ranking_mean_male, width,label=‘Male’)
rects2 = ax.bar(x + width/2, ranking_mean_female, width, label=‘Female’)

ax.set_ylabel(‘Total views’)
ax.set_title(‘Comparison of favorite star wars series’)
ax.set_xticks(x, labels)
ax.legend()

plt.show()

Returned error


ValueError Traceback (most recent call last)
in
11
12 fig, ax = plt.subplots()
—> 13 rects1 = ax.bar(x - width/2, ranking_mean_male, width,label=‘Male’)
14 rects2 = ax.bar(x + width/2, ranking_mean_female, width, label=‘Female’)
15

/dataquest/system/env/python3/lib/python3.8/site-packages/matplotlib/init.py in inner(ax, data, *args, **kwargs)
1563 def inner(ax, *args, data=None, **kwargs):
1564 if data is None:
→ 1565 return func(ax, *map(sanitize_sequence, args), **kwargs)
1566
1567 bound = new_sig.bind(ax, *args, **kwargs)

/dataquest/system/env/python3/lib/python3.8/site-packages/matplotlib/axes/_axes.py in bar(self, x, height, width, bottom, align, **kwargs)
2338 yerr = self._convert_dx(yerr, y0, y, self.convert_yunits)
2339
→ 2340 x, height, width, y, linewidth = np.broadcast_arrays(
2341 # Make args iterable too.
2342 np.atleast_1d(x), height, width, y, linewidth)

<array_function internals> in broadcast_arrays(*args, **kwargs)

/dataquest/system/env/python3/lib/python3.8/site-packages/numpy/lib/stride_tricks.py in broadcast_arrays(*args, **kwargs)
262 args = [np.array(_m, copy=False, subok=subok) for _m in args]
263
→ 264 shape = _broadcast_shape(*args)
265
266 if all(array.shape == shape for array in args):

/dataquest/system/env/python3/lib/python3.8/site-packages/numpy/lib/stride_tricks.py in _broadcast_shape(*args)
189 # use the old-iterator because np.nditer does not handle size 0 arrays
190 # consistently
→ 191 b = np.broadcast(*args[:32])
192 # unfortunately, it cannot handle 32 or more arguments directly
193 for pos in range(32, len(args), 31):

ValueError: shape mismatch: objects cannot be broadcast to a single shape

Click here to view the jupyter notebook file in a new tab

Hi @zhouhuilingsybil,

The issue is that you have 5 labels but 6 values for men and women. To fix it, add one more label in the list labels.

2 Likes