Is there a way to create a bar chart diagram in Python?

I need to create a histogram that displays a row, not a step or a histogram. I am using python 2.7. The plt.hist function below displays a stepped line, and the boxes do not 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 a line to correlate with each number of bins in the bin centers as if the histtype = u'line flag had the align = u'mid flag

+8
source share
3 answers

Using scipy, you can use stats.gaussian_kde to evaluate 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

+11
source

The Matplotlib thumbnail gallery is usually quite useful in situations like yours. The combination of this and this is one of the gallery with some settings, probably very close to what you mean:

 import numpy as np import matplotlib.mlab as mlab import matplotlib.pyplot as plt mu = 0 sigma = 1 noise = np.random.normal(mu, sigma, size=1000) num_bins = 7 n, bins, _ = plt.hist(noise, num_bins, normed=1, histtype='step') y = mlab.normpdf(bins, mu, sigma) plt.plot(bins, y, 'r--') plt.show() 

enter image description here

In addition, increasing the number of boxes helps ...

enter image description here

+2
source

The line of the line that you produce does not line up, since the x values ​​used are the edges of the bin. You can calculate the centers of the bins as follows: bin_centers = 0.5*(x[1:]+x[:-1]) Then the full code:

 noise = np.random.normal(0,1,(1000,1)) n,x,_ = plt.hist(noise, bins = np.linspace(-3,3,7), histtype=u'step' ) bin_centers = 0.5*(x[1:]+x[:-1]) plt.plot(bin_centers,n) ## using bin_centers rather than edges plt.show() 

If you want the chart to be filled to y = 0, use plt.fill_between(bin_centers,n) Linear histogram in basket centers

+2
source

Source: https://habr.com/ru/post/1210782/


All Articles