Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I create a histogram from a hashmap in python?

I have data in a hashmap, and I want to create a histogram over this data using the keys as bins and the values as data.

My data:

N = {1: 12, 2: 15, 3: 8, 4: 4, 5: 1}

What I want plotted:

  |
15|    X
  |    X 
  |    X
  | X  X
  | X  X
10| X  X
  | X  X
  | X  X  X
  | X  X  X
  | X  X  X
 5| X  X  X
  | X  X  X  X
  | X  X  X  X
  | X  X  X  X
  | X  X  X  X  X
  |_________________________
    1  2  3  4  5

I've tried to figure out how to do this with pyplot.hist(), but all overloads I can find take a list of values, not a hashmap. Do I really have to generate this list, just to let matplotlib count all the values again?

like image 303
Tomas Aschan Avatar asked Mar 13 '12 17:03

Tomas Aschan


People also ask

How do you create histograms in Python?

To create a histogram the first step is to create bin of the ranges, then distribute the whole range of the values into a series of intervals, and count the values which fall into each of the intervals. Bins are clearly identified as consecutive, non-overlapping intervals of variables. The matplotlib. pyplot.

How do I create a histogram in Python MatPlotLib?

In Matplotlib, we use the hist() function to create histograms. The hist() function will use an array of numbers to create a histogram, the array is sent into the function as an argument.

How do I make a multiple histogram in Python?

To make multiple overlapping histograms, we need to use Matplotlib pyplot's hist function multiple times. For example, to make a plot with two histograms, we need to use pyplot's hist() function two times. Here we adjust the transparency with alpha parameter and specify a label for each variable.


1 Answers

Just plot a bar graph. That's all hist does.

E.g.:

import matplotlib.pyplot as plt

N = {1: 12, 2: 15, 3: 8, 4: 4, 5: 1}
plt.bar(N.keys(), N.values(), align='center')
plt.show()

enter image description here

like image 168
Joe Kington Avatar answered Nov 15 '22 00:11

Joe Kington