Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a clean way to generate a line histogram chart in Python?

Tags:

I need to create a histogram that plots a line and not a step or bar chart. I am using python 2.7 The plt.hist function below plots a stepped line and the bins don't line up in the plt.plot function.

import matplotlib.pyplot as plt import numpy as np noise = np.random.normal(0,1,(1000,1)) (n,x,_) = plt.hist(noise, bins = np.linspace(-3,3,7), histtype=u'step' )   plt.plot(x[:-1],n) 

I need the line to correlate with each bin's count at the bin centers as if there was a histtype=u'line' flag to go with the align=u'mid' flag

like image 971
DanGoodrick Avatar asked Jan 10 '15 03:01

DanGoodrick


People also ask

How do I make my Matplotlib histogram look better?

Tweaking Matplotlib Preferably, one that has tick mark and other features closer to the aesthetic you want to achieve. Turn the frame and grid lines off. Tweak the x-axis so that there is a gap with the y-axis, which seems more appropriate for histograms. Have color options allowing for separation between bins.

Which method is used to create a histogram in Python?

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.


1 Answers

Using scipy, you could use stats.gaussian_kde to estimate the probability density function:

import matplotlib.pyplot as plt import numpy as np import scipy.stats as stats  noise = np.random.normal(0, 1, (1000, )) density = stats.gaussian_kde(noise) n, x, _ = plt.hist(noise, bins=np.linspace(-3, 3, 50),                     histtype=u'step', density=True)   plt.plot(x, density(x)) plt.show() 

enter image description here

like image 92
unutbu Avatar answered Oct 21 '22 06:10

unutbu