Python 使用给定的 x 和 y 值绘制直方图
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/32541659/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Plotting Histogram with given x and y values
提问by krazzy
I am trying to plot a histogram that lines up every x value with the y value on the plot. I have tried to use multiple resources, but unfortunately I wasn't able to find anything. This is the best way I could code to make a histogram.
我试图绘制一个直方图,将每个 x 值与图中的 y 值对齐。我尝试使用多种资源,但不幸的是我找不到任何东西。这是我编写直方图的最佳方式。
x = (1,2,3,4,5)
y = (1,2,3,4,5)
h=plt.hist(x,y)
plt.axis([0, 6, 0, 6])
plt.show()
I want a graph that looks like the image below without those a's on x-axis:
我想要一个看起来像下图的图表,x 轴上没有那些 a:
回答by Sahil M
From your plot and initial code, I could gather that you already have the bin and the frequency values in 2 vectors x and y. In this case, you will just plot a bar chart of these values, as opposed to the histogram using the plt.hist command. You can do the following:
从您的绘图和初始代码中,我可以推断出您已经拥有 2 个向量 x 和 y 中的 bin 和频率值。在这种情况下,您将只绘制这些值的条形图,而不是使用 plt.hist 命令绘制直方图。您可以执行以下操作:
import matplotlib.pyplot as plt
x = (1,2,3,4,5)
y = (1,2,3,4,5)
plt.bar(x,y,align='center') # A bar chart
plt.xlabel('Bins')
plt.ylabel('Frequency')
for i in range(len(y)):
plt.hlines(y[i],0,x[i]) # Here you are drawing the horizontal lines
plt.show()