How to plot a histogram using Matplotlib in Python with a list of data?

偶尔善良 提交于 2019-11-28 16:56:45

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');

Niraj

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 :

Connor Wilmers

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.. ])
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!