I am trying to plot a histogram using the matplotlib.hist() function but I am not sure how to do it.
I have a list
probability = [0.3602150537634409, 0.42028985507246375,
0.373117033603708, 0.36813186813186816, 0.32517482517482516,
0.4175257731958763, 0.41025641025641024, 0.39408866995073893,
0.4143222506393862, 0.34, 0.391025641025641, 0.3130841121495327,
0.35398230088495575]
and a list of names(strings).
How do I make the probability as my y-value of each bar and names as x-values?
If you want a histogram, you don't need to attach any 'names' to x-values, as on x-axis you would have bins:
import matplotlib.pyplot as plt
import numpy as np
%matplotlib inline
x = np.random.normal(size = 1000)
plt.hist(x, normed=True, bins=30)
plt.ylabel('Probability');
However, if you have limited number of data points, and you want a bar plot, then you may attach labels to x-axis:
x = np.arange(3)
plt.bar(x, height= [1,2,3])
plt.xticks(x+.5, ['a','b','c'])
Let me know if this solves your problem.
EDIT 26 November 2018
As per comment below, the following code will suffice as of Matplotlib 3.0.2:
x = np.arange(3)
plt.bar(x, height= [1,2,3])
plt.xticks(x, ['a','b','c']) # no need to add .5 anymore
EDIT 23 May 2019
As far as histogram is concerned, the normed param is deprecated:
MatplotlibDeprecationWarning: The 'normed' kwarg was deprecated in Matplotlib 2.1 and will be removed in 3.1. Use 'density' instead.
So, as from Matplolib 3.1 instead of:
plt.hist(x, normed=True, bins=30)
one has to write:
import matplotlib.pyplot as plt
import numpy as np
%matplotlib inline
x = np.random.normal(size = 1000)
plt.hist(x, density=True, bins=30) # density
plt.ylabel('Probability');
If you haven't installed matplotlib yet just try the command.
> pip install matplotlib
Library import
import matplotlib.pyplot as plot
The histogram data:
plot.hist(weightList,density=1, bins=20)
plot.axis([50, 110, 0, 0.06])
#axis([xmin,xmax,ymin,ymax])
plot.xlabel('Weight')
plot.ylabel('Probability')
Display histogram
plot.show()
And the output is like :
This is a very round-about way of doing it but if you want to make a histogram where you already know the bin values but dont have the source data, you can use the np.random.randint function to generate the correct number of values within the range of each bin for the hist function to graph, for example:
import numpy as np
import matplotlib.pyplot as plt
data = [np.random.randint(0, 9, *desired y value*), np.random.randint(10, 19, *desired y value*), etc..]
plt.hist(data, histtype='stepfilled', bins=[0, 10, etc..])
as for labels you can align x ticks with bins to get something like this:
#The following will align labels to the center of each bar with bin intervals of 10
plt.xticks([5, 15, etc.. ], ['Label 1', 'Label 2', etc.. ])
来源:https://stackoverflow.com/questions/33203645/how-to-plot-a-histogram-using-matplotlib-in-python-with-a-list-of-data



