Getting a shape mismatch error message when trying to plot a stacked barchart

Viewed 15736

I am trying to create a stacked barchart from my data and keep getting an error message

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

This is what the relevant code I have written:

num = list(yearly_posts.index)
barWidth = 0.50
plt.bar(num,yearly_status.values, color='#b5ffb9',edgecolor='white',width=barWidth)
plt.bar(num,yearly_posts.values, color='#f9bc86',edgecolor='white',width=barWidth)

and this is a sample of my data

#yearly_status table
year
2009     85
2010     86
2011    188
2012    274
2013    240
2014    171
2015    132
2016     22
2017     18
2018     13
dtype: int64

#yearly_posts table
year
2009     8
2010    19
2013    19
2014    40
2015    13
2016    20
2017    27
2018    17
dtype: int64
2 Answers

The problem was that both your dataframes has unequal no. of entries which is why the num was different for both. The solution is to use different indexes for both as num1 and num2. Additionally, you will have to flatten your values 2d array into a 1-d array as yearly_status.values.flatten()

num1 = list(yearly_status.index)
num2 = list(yearly_posts.index)
barWidth = 0.50
plt.bar(num1, yearly_status.values.flatten(), color='#b5ffb9',edgecolor='white',width=barWidth)
plt.bar(num2, yearly_posts.values.flatten(), color='#f9bc86',edgecolor='white',width=barWidth)

enter image description here

if you are sure that the length of both list objects are equal and still getting a shape mismatch error. You can convert the list object to a numpy array before plotting.

import numpy as np
numpyObject = np.array(listObject)
Related