Reputation: 2501
I have a dictionary d
:
d = {'apples': 5, 'oranges': 2, 'bananas': 2, 'lemons': 1, 'coconuts': 1}
how can I display it graphically, as a histogram using (pylab/matplotlib/
pandas/what-ever-is-best-suitable-for-simple-histograms
)
What I am looking for is a graphical analogy to the following:
X
X
X
X X X
X X X X X
-------------
A O B L C
Upvotes: 3
Views: 4560
Reputation: 879471
Using matplotlib:
import matplotlib.pyplot as plt
d = {'apples': 5, 'oranges': 2, 'bananas': 2, 'lemons': 1, 'coconuts': 1}
plt.bar(range(len(d)), d.values(), align='center')
plt.xticks(range(len(d)), d.keys(), rotation=25)
Or, to make it colorful:
import numpy as np
import matplotlib.pyplot as plt
d = {'apples': 5, 'oranges': 2, 'bananas': 2, 'lemons': 1, 'coconuts': 1}
jet = plt.get_cmap('jet')
N = len(d)
plt.bar(range(N), d.values(), align='center', color=jet(np.linspace(0, 1.0, N)))
plt.xticks(range(N), d.keys(), rotation=25)
Upvotes: 3
Reputation: 394031
You can just call plot
and set `kind='bar':
In [252]:
d = {'apples': [5], 'oranges':[2], 'bananas': [2], 'lemons': [1], 'coconuts': [1]}
df = pd.DataFrame(d)
df.plot(kind='bar')
Out[252]:
<matplotlib.axes.AxesSubplot at 0xb54b0f0>
Upvotes: 1