如何建立帶有閾值線的 matplotlib 條形圖?
要使用閾值線建立 Matplotlib 條形圖,我們必須使用 axhline() 方法。
步驟
- 設定影像大小並調整子圖之間和周圍的填充。
- 初始化變數 threshold。
- 為 bars 值準備列表。
- 根據閾值獲得下限和上限條形值。
- 使用 subplots() 方法建立一個影像和一組子圖。
- 用 x、a_threshold 和 b_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()
輸出

廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP