Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python plot simple histogram given binned data

I have count data (a 100 of them), each correspond to a bin (0 to 99). I need to plot these data as histogram. However, histogram count those data and does not plot correctly because my data is already binned.

import random import matplotlib.pyplot as plt x = random.sample(range(1000), 100) xbins = [0, len(x)] #plt.hist(x, bins=xbins, color = 'blue')  #Does not make the histogram correct. It counts the occurances of the individual counts.   plt.plot(x) #plot works but I need this in histogram format plt.show() 
like image 710
Curious Avatar asked Sep 06 '12 15:09

Curious


2 Answers

If I'm understanding what you want to achieve correctly then the following should give you what you want:

import matplotlib.pyplot as plt plt.bar(range(0,100), x) plt.show() 

It doesn't use hist(), but it looks like you've already put your data into bins so there's no need.

like image 160
redrah Avatar answered Sep 23 '22 08:09

redrah


The problem is with your xbins. You currently have

xbins = [0, len(x)] 

which will give you the list [0, 100]. This means you will only see 1 bin (not 2) bounded below by 0 and above by 100. I am not totally sure what you want from your histogram. If you want to have 2 unevenly spaced bins, you can use

xbins = [0, 100, 1000] 

to show everything below 100 in one bin, and everything else in the other bin. Another option would be to use an integer value to get a certain number of evenly spaced bins. In other words do

plt.hist(x, bins=50, color='blue') 

where bins is the number of desired bins.

On a side note, whenever I can't remember how to do something with matplotlib, I will usually just go to the thumbnail gallery and find an example that looks more or less what I am trying to accomplish. These examples all have accompanying source code so they are quite helpful. The documentation for matplotlib can also be very handy.

like image 33
jlund3 Avatar answered Sep 20 '22 08:09

jlund3