如何使用阈值线创建matplotlib条形图?

alw*_*btc 12 python charts matplotlib

我想知道如何使用阈值线创建matplotlib条形图,阈值线以上条形部分应为红色,阈值线以下部分应为绿色.请给我一个简单的例子,我在网上找不到任何东西.

Car*_*ten 18

使其成为堆叠条形图,如本示例所示,但将数据划分为高于阈值的部分和下面的部分.例:

import numpy as np
import matplotlib.pyplot as plt

# some example data
threshold = 43.0
values = np.array([30., 87.3, 99.9, 3.33, 50.0])
x = range(len(values))

# split it up
above_threshold = np.maximum(values - threshold, 0)
below_threshold = np.minimum(values, threshold)

# and plot it
fig, ax = plt.subplots()
ax.bar(x, below_threshold, 0.35, color="g")
ax.bar(x, above_threshold, 0.35, color="r",
        bottom=below_threshold)

# horizontal line indicating the threshold
ax.plot([0., 4.5], [threshold, threshold], "k--")

fig.savefig("look-ma_a-threshold-plot.png")
Run Code Online (Sandbox Code Playgroud)

显示代码结果的示例图


Abu*_*oeb 5

您可以axhline像这样简单地使用。请参阅此文档

# For your case
plt.axhline(y=threshold,linewidth=1, color='k')

# Another example - You can also define xmin and xmax
plt.axhline(y=5, xmin=0.5, xmax=3.5)
Run Code Online (Sandbox Code Playgroud)