Python 如何创建带有阈值线的 matplotlib 条形图?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28129606/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to create a matplotlib bar chart with a threshold line?
提问by alwbtc
I'd like to know how to create a matplotlib bar chart with a threshold line, the part of bars above threshold line should have red color, and the parts below the threshold line should be green. Please provide me a simple example, I couldn't find anything on the web.
我想知道如何创建带有阈值线的 matplotlib 条形图,阈值线以上的部分应为红色,阈值线以下的部分应为绿色。请给我一个简单的例子,我在网上找不到任何东西。
采纳答案by Carsten
Make it a stacked bar chart, like in this example, but divide your data up into the parts above your threshold and the parts below. 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")
回答by Abu Shoeb
You can simply use axhline
like this. See this documentation
你可以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)