Ipython pylab: print a histogram from a dictionary

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'm looking for is a graphic analogy with the following:

X
X
X
X  X  X
X  X  X  X  X
-------------
A  O  B  L  C
+4
source share
2 answers

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)

enter image description here

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)

enter image description here

+3
source

You can simply call plotand 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>

enter image description here

+1
source

All Articles