pratik_m
pratik_m

Reputation: 67

Creating a simple python bar chart / histogram using data in dictionary

freq = {1: 1000, 2: 980, 4: 560, ... 40: 3, 41: 1, 43: 1}

(Between 1 to 43, not all numbers are keys)

I want to make a histogram and plot it, such that I can see each key on the X axis, and the values on Y axis using matplotlib. How do I do this? I do not wish to create bins (need all values covered individually) and no tutorial is really helpful to make me understand the terms. I am also short on time, so couldn't get into all the terminology. What is the best way to do this?

Upvotes: 1

Views: 1506

Answers (2)

Carsten
Carsten

Reputation: 18446

To extend @Tzach's comment, here's a minimal example to create a bar chart from your data:

import matplotlib.pyplot as plt
freq = {1: 1000, 2: 980, 4: 560, 40: 3, 41: 1, 43: 1}
fig, ax = plt.subplots()
ax.bar(freq.keys(), freq.values())
fig.savefig("bar.png")

enter image description here

Upvotes: 3

Sede
Sede

Reputation: 61225

If you use matplotlib you can create 2D histograms

>>> import matplotlib.pyplot as plt
>>> freq = {1: 1000, 2: 980, 4: 560,40: 3, 41: 1, 43: 1}
>>> x = list(freq.keys())
>>> y = list(freq.values())
>>> plt.hist2d(x,y)
(array([[ 0.,  0.,  0.,  0.,  0.,  1.,  0.,  0.,  0.,  2.],
       [ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.],
       [ 3.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.]]), array([  1. ,   5.2,   9.4,  13.6,  17.8,  22. ,  26.2,  30.4,  34.6,
        38.8,  43. ]), array([    1. ,   100.9,   200.8,   300.7,   400.6,   500.5,   600.4,
         700.3,   800.2,   900.1,  1000. ]), <matplotlib.image.AxesImage object at 0xb475012c>)
>>> plt.show()

histogram 2d

Upvotes: 2

Related Questions