如何在 Matplotlib 中向分布图 (sns.distplot) 添加垂直线?
matplotlibserver side programmingprogramming更新于 2025/4/30 19:22:17
要向分布图添加垂直线,我们可以采取以下步骤−
- 创建一个数字列表。
- 使用 sns.displot() 创建轴。
- 获取轴 ax 的 x 和 y 数据。
- 在图上绘制一条垂直线。
- 删除第 0 个索引处的线。
- 要显示图形,请使用 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()
输出


