How to create a matplotlib bar chart with a threshold line?

Multi tool use


How to create a matplotlib bar chart with a threshold line?
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.
2 Answers
2
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")
Sure, just make
threshold
an array of your desired value, instead of a single value. You'd have to change the dashed line, though.– Carsten
Jan 24 '15 at 20:59
threshold
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)
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
Thank you, but what if the threshold doesn't have same value everywhere, for example for x < 3 threshold is 50, and for x >=3 threshold is 70? Is it possible to draw the chart the same way I want?
– alwbtc
Jan 24 '15 at 20:54