我想知道如何使用阈值线创建matplotlib条形图,阈值线以上的条形部分应为红色,阈值线以下的部分应为绿色。请给我一个简单的例子,我在网上找不到任何东西。
答案 0 :(得分:16)
将其设为堆叠条形图,如this example中所示,但将数据划分为高于阈值的部分和下面的部分。例如:
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")
答案 1 :(得分:2)
您可以像这样简单地使用axhline
。看到这个documentation
# 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)