在直方图中绘制平均线(matplotlib)

我正在使用 python 中的 matplotlib 绘制一个直方图,并且希望绘制一条代表数据集平均值的线,在直方图上以虚线的形式覆盖(或者也许其他颜色也可以)。对于如何在直方图上画一条覆盖的线有什么想法吗?

我正在使用 plot ()命令,但不确定如何绘制垂直线(例如,我应该为 y 轴赋什么值?

谢谢!

141553 次浏览

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.

You can use plot or vlines to draw a vertical line, but to draw a vertical line from the bottom to the top of the y axis, axvline is the probably the simplest function to use. Here's an example:

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>

Result: plot

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

Which produces following result: Average line with text