如何在 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+ 瀏覽量

開啟你的 職業生涯

完成課程即可獲得認證

開始
廣告