3

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
EdChum
  • 376,765
  • 198
  • 813
  • 562
user1968963
  • 2,371
  • 3
  • 21
  • 22

2 Answers2

3

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

unutbu
  • 842,883
  • 184
  • 1,785
  • 1,677
  • actually, your example does not work when I draw plot inline `ipython qtconsole --pylab=inline`. It only works when the plots are displayed in an external window. – user1968963 Aug 06 '14 at 14:02
  • I've modified the code so that the plot will be displayed inline with the ipython qtconsole. – unutbu Aug 06 '14 at 17:33
  • thanks, but it still does not work properly: `plt.bar` draws the histogram (the bars) but with numbers instead of labels. The second command `plt.xticks` draws a second empty graph with labels (without bars) – user1968963 Aug 07 '14 at 07:28
  • You have to paste all the commands into one cell before evaluating. – unutbu Aug 07 '14 at 10:23
  • what do you mean "paste into one cell". What is a cell? – user1968963 Aug 07 '14 at 10:35
  • By "cell" I mean one input line -- the thing that begins with `In [...]:`. The term may be is a hangover from Mathematica. They look more like cells when you run `ipython notebook`. – unutbu Aug 07 '14 at 10:44
1

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

EdChum
  • 376,765
  • 198
  • 813
  • 562