如何创建带有阈值线的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()