如何建立帶有閾值線的 matplotlib 條形圖?


要使用閾值線建立 Matplotlib 條形圖,我們必須使用 axhline() 方法。

步驟

  • 設定影像大小並調整子圖之間和周圍的填充。
  • 初始化變數 threshold
  • bars 值準備列表。
  • 根據閾值獲得下限和上限條形值。
  • 使用 subplots() 方法建立一個影像和一組子圖。
  • xa_thresholdb_threshold 值繪製條形圖。
  • 使用 axhline() 方法在軸線上新增一根水平線。
  • 使用 show() 方法來顯示影像。

例項

import numpy as np
import matplotlib.pyplot as plt

plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
threshold = 10
values = np.array([8.0, 10.0, 15.0, 9.0, 12.0])
x = range(len(values))

a_threshold = np.maximum(values - threshold, 0)
b_threshold = np.minimum(values, threshold)

fig, ax = plt.subplots()
ax.bar(x, b_threshold, 0.35, color="blue")
ax.bar(x, a_threshold, 0.35, color="yellow", bottom=b_threshold)

plt.axhline(threshold, color='red', ls='dotted')

plt.show()

輸出

更新日期:2021-06-03

3K+ 瀏覽量

開啟您的職業生涯

完成課程即可獲得認證

開始
廣告
© . All rights reserved.