user1968963
user1968963

Reputation: 2501

ipython pylab: print histogram from 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 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

Answers (2)

unutbu
unutbu

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)

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

Upvotes: 3

EdChum
EdChum

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>

enter image description here

Upvotes: 1

Related Questions