如何在Python中使用Matplotlib绘制带有数据列表的直方图? [英] How to plot a histogram using Matplotlib in Python with a list of data?
问题描述
我正在尝试使用matplotlib.hist()
函数绘制直方图,但是我不确定该怎么做.
I am trying to plot a histogram using the matplotlib.hist()
function but I am not sure how to do it.
我有一个列表
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).
我如何使概率作为每个小节的y值,而将其命名为x值?
How do I make the probability as my y-value of each bar and names as x-values?
推荐答案
如果您想要直方图,则无需在x值上附加任何名称",因为在x轴上您将具有数据仓:
If you want a histogram, you don't need to attach any 'names' to x-values, as on x-axis you would have data bins:
import matplotlib.pyplot as plt
import numpy as np
%matplotlib inline
np.random.seed(42)
x = np.random.normal(size=1000)
plt.hist(x, density=True, bins=30) # `density=False` would make counts
plt.ylabel('Probability')
plt.xlabel('Data');
您可以使用PDF
线,标题和图例使直方图更加有趣:
You can make your histogram a bit fancier with PDF
line, titles, and legend:
import scipy.stats as st
plt.hist(x, density=True, bins=30, label="Data")
mn, mx = plt.xlim()
plt.xlim(mn, mx)
kde_xs = np.linspace(mn, mx, 301)
kde = st.gaussian_kde(x)
plt.plot(kde_xs, kde.pdf(kde_xs), label="PDF")
plt.legend(loc="upper left")
plt.ylabel('Probability')
plt.xlabel('Data')
plt.title("Histogram");
但是,如果您的数据点数量有限(例如在OP中),则条形图可以更好地表示您的数据(然后您可以在x轴上附加标签):
However, if you have limited number of data points, like in OP, a bar plot would make more sense to represent your data (then you may attach labels to x-axis):
x = np.arange(3)
plt.bar(x, height=[1,2,3])
plt.xticks(x, ['a','b','c'])
这篇关于如何在Python中使用Matplotlib绘制带有数据列表的直方图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!