如何在 Matplotlib 中向分布图(sns.distplot)中添加垂直线?


若要向分布图中添加垂直线,我们可以采取以下步骤 -

  • 创建一个数字列表。
  • 使用 sns.displot() 创建一个轴。
  • 获取轴 ax 的 x 和 y 数据。
  • 在图中绘制一条垂直线。
  • 删除第 0th 索引处的线。
  • 若要显示该图形,请使用 show() 方法。

示例

import seaborn as sns, numpy as np
import matplotlib.pyplot as plt
plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True
x = [5, 6, 7, 2, 3, 4, 1, 8, 2]
ax = sns.distplot(x, kde=True)
x = ax.lines[0].get_xdata()
y = ax.lines[0].get_ydata()
plt.axvline(x[np.argmax(y)], color='red')
ax.lines[0].remove()
plt.show()

输出

更新于: 06-May-2021

3K+ 浏览量

开启你的 职业生涯

完成课程即可获得认证

开始
广告
© . All rights reserved.