如何创建带有阈值线的 matplotlib 条形图?
How to create a matplotlib bar chart with a threshold line?
我想知道如何创建带有阈值线的 matplotlib 条形图,高于阈值线的部分应为红色,低于阈值线的部分应为绿色。请给我一个简单的例子,我在网上找不到任何东西。
像 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")
您可以像这样简单地使用 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)
我想知道如何创建带有阈值线的 matplotlib 条形图,高于阈值线的部分应为红色,低于阈值线的部分应为绿色。请给我一个简单的例子,我在网上找不到任何东西。
像 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")
您可以像这样简单地使用 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)