Python 在直方图中绘制平均线(matplotlib)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16180946/
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
Drawing average line in histogram (matplotlib)
提问by user308827
I am drawing a histogram using matplotlib in python, and would like to draw a line representing the average of the dataset, overlaid on the histogram as a dotted line (or maybe some other color would do too). Any ideas on how to draw a line overlaid on the histogram?
我正在使用 python 中的 matplotlib 绘制直方图,并想绘制一条代表数据集平均值的线,作为虚线覆盖在直方图上(或者其他颜色也可以)。关于如何在直方图上绘制一条线的任何想法?
I am using the plot() command, but not sure how to draw a vertical line (i.e. what value should I give for the y-axis?
我正在使用 plot() 命令,但不确定如何绘制一条垂直线(即我应该为 y 轴指定什么值?
thanks!
谢谢!
采纳答案by Warren Weckesser
You can use plotor vlinesto draw a vertical line, but to draw a vertical line from the bottom to the top of the y axis, axvlineis the probably the simplest function to use. Here's an example:
您可以使用plot或vlines来绘制一条垂直线,但是从 y 轴的底部到顶部绘制一条垂直线,axvline这可能是最简单的功能。下面是一个例子:
In [80]: import numpy as np
In [81]: import matplotlib.pyplot as plt
In [82]: np.random.seed(6789)
In [83]: x = np.random.gamma(4, 0.5, 1000)
In [84]: result = plt.hist(x, bins=20, color='c', edgecolor='k', alpha=0.65)
In [85]: plt.axvline(x.mean(), color='k', linestyle='dashed', linewidth=1)
Out[85]: <matplotlib.lines.Line2D at 0x119758828>
回答by smitec
I would look at the largest value in your data set (i.e. the histogram bin values) multiply that value by a number greater than 1 (say 1.5) and use that to define the y axis value. This way it will appear above your histogram regardless of the values within the histogram.
我会查看数据集中的最大值(即直方图 bin 值)将该值乘以一个大于 1 的数字(比如 1.5),然后使用它来定义 y 轴值。这样,无论直方图中的值如何,它都会出现在您的直方图上方。
回答by P?rripeikko
This is old topic and minor addition, but one thing I have often liked is to also plot mean value beside the line:
这是一个老话题和小补充,但我经常喜欢的一件事是也在线条旁边绘制平均值:
import numpy as np
import matplotlib.pyplot as plt
np.random.seed(6789)
x = np.random.gamma(4, 0.5, 1000)
result = plt.hist(x, bins=20, color='c', edgecolor='k', alpha=0.65)
plt.axvline(x.mean(), color='k', linestyle='dashed', linewidth=1)
min_ylim, max_ylim = plt.ylim()
plt.text(x.mean()*1.1, max_ylim*0.9, 'Mean: {:.2f}'.format(x.mean()))


