如何在Python中使用Matplotlib绘制直方图和数据列表?

2024-04-23 23:42:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图使用matplotlib.hist()函数绘制直方图,但我不确定如何绘制。

我有一张单子

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]

以及一个名字(字符串)列表。

如何将概率设为每个条的y值,将名称设为x值?


Tags: 函数字符串名称列表matplotlib绘制直方图概率
3条回答

这是一种非常全面的方法,但是如果您想制作一个直方图,其中您已经知道bin值,但没有源数据,您可以使用np.random.randint函数在每个bin的范围内生成正确数量的值,以便hist函数绘制图表,例如:

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..])

对于标签,您可以将x记号与箱子对齐,得到如下结果:

#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.. ])

如果尚未安装matplotlib,请尝试该命令。

> pip install matplotlib

库导入

import matplotlib.pyplot as plot

直方图数据:

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

显示直方图

plot.show()

输出如下:

enter image description here

如果你想要一个直方图,你不需要在x值上附加任何“名称”,因为在x轴上你会有一个箱子:

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

enter image description here

但是,如果数据点的数量有限,并且需要条形图,则可以将标签附着到x轴:

x = np.arange(3)
plt.bar(x, height= [1,2,3])
plt.xticks(x+.5, ['a','b','c'])

enter image description here

如果这能解决你的问题,请告诉我。

编辑2018年11月26日

根据下面的注释,从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

编辑2019年5月23日

就直方图而言,不推荐使用normed参数:

MatplotlibDeprecationWarning: The 'normed' kwarg was deprecated in Matplotlib 2.1 and will be removed in 3.1. Use 'density' instead.

因此,从Matplolib 3.1开始而不是:

plt.hist(x, normed=True, bins=30) 

必须写:

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

enter image description here

相关问题 更多 >