Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Plot line graph from histogram data in matplotlib

I have a numpy array of ints representing time periods, which I'm currently plotting in a histogram to get a nice distribution graph, using the following code:

ax.hist(data,bins=100,range=(minimum,maximum),facecolor="r") 

However I'm trying to modify this graph to represent the exact same data using a line instead of bars, so I can overlay more samples to the same plot and have them be clear (otherwise the bars overlap each other). What I've tried so far is to collate the data array into an array of tuples containing (time, count), and then plot it using

ax.plot(data[:,0],data[:,1],color="red",lw=2) 

However that's not giving me anything close, as I can't accurately simulate the bins option of the histogram in my plot. Is there a better way to do this?

like image 784
CNeo Avatar asked Jan 11 '12 15:01

CNeo


People also ask

How do you plot a histogram in 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 show a line plot in Matplotlib?

To plot a line plot in Matplotlib, you use the generic plot() function from the PyPlot instance. There's no specific lineplot() function - the generic one automatically plots using lines or markers.


2 Answers

I am very late to the party - but maybe this will be useful to someone else. I think what you need to do is set the histtype parameter to 'step', i.e.

ax.hist(data,bins=100,range=(minimum,maximum),facecolor="r", histtype = 'step') 

See also http://matplotlib.sourceforge.net/examples/pylab_examples/histogram_demo_extended.html

like image 51
Ger Avatar answered Sep 20 '22 01:09

Ger


You can save the output of hist and then plot it.

import numpy as np import pylab as p  data=np.array(np.random.rand(1000)) y,binEdges=np.histogram(data,bins=100) bincenters = 0.5*(binEdges[1:]+binEdges[:-1]) p.plot(bincenters,y,'-') p.show() 
like image 28
imsc Avatar answered Sep 20 '22 01:09

imsc