Baobab1988
Baobab1988

Reputation: 715

How to display two mismatching dictionaries in a bar graph using matplotlib?

I'm trying to plot a graph which will display data from dictionaries. My problem is that sometimes number of values in dictionaries (ME_Requests and non_ME_Requests) are mismatching and this generates the following error:

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

Could someone help me flatten values so if there is a mismatch then only one bar will show instead of two? Thanks in advance!

my code:

import numpy as np
import matplotlib.pyplot as plt

#sample data
ME_Requests = {'John Doe': 47, 'Amanda Doe': 27, 'Maria Doe': 26}
non_ME_Requests = {'John Doe': 105, 'Amanda Doe': 64, 'Maria Doe': 48, 'Dimitri Doe': 58}
month="Apr-2020"
X = np.arange(len(ME_Requests))
ax = plt.subplot(111)
ax.bar(X, ME_Requests.values(), width=0.2, align='center')
ax.bar(X-0.2, non_ME_Requests.values(), width=0.2, align='center')
ax.legend(('ME_Requests','non_ME_Requests'))
plt.xticks(X, ME_Requests.keys())
plt.title("Emails Closed per team member in {}".format(month) , fontsize=17)
plt.show()

Upvotes: 0

Views: 37

Answers (2)

Shmn
Shmn

Reputation: 703

I calculated length of ME_Requests and non_ME_Requests dictionaries separately. Plotted using length of bigger dictionary.

import matplotlib.pyplot as plt
#sample data
ME_Requests = {'John Doe': 47, 'Amanda Doe': 27, 'Maria Doe': 26}
non_ME_Requests = {'John Doe': 105, 'Amanda Doe': 64, 'Maria Doe': 48, 'Dimitri Doe': 58}
month="Apr-2020"
X = np.arange(len(ME_Requests))
X_non_ME = np.arange(len(non_ME_Requests))
ax = plt.subplot(111)
ax.bar(X, ME_Requests.values(), width=0.2, align='center')
ax.bar(X_non_ME-0.2, non_ME_Requests.values(), width=0.2, align='center')
ax.legend(('ME_Requests','non_ME_Requests'))

# plt.xticks(X, ME_Requests.keys())
plt.xticks(X_non_ME, non_ME_Requests.keys())
plt.title("Emails Closed per team member in {}".format(month), fontsize=17)
plt.show()

Upvotes: 1

Diziet Asahi
Diziet Asahi

Reputation: 40687

If you don't mind using pandas, I would create a dataframe that ensures consistent number of elements:

df1 = pd.DataFrame(ME_Requests.values(), index=ME_Requests.keys(), columns=['ME_Requests'])
df2 = pd.DataFrame(non_ME_Requests.values(), index=non_ME_Requests.keys(), columns=['non_ME_Requests'])
df = pd.concat([df1,df2], axis=1)

df.plot.bar()

enter image description here

Upvotes: 2

Related Questions