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

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


You can simply use axhline like this. See this documentation

# For your caseplt.axhline(y=threshold,linewidth=1, color='k')# Another example - You can also define xmin and xmaxplt.axhline(y=5, xmin=0.5, xmax=3.5)


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 npimport matplotlib.pyplot as plt# some example datathreshold = 43.0values = np.array([30., 87.3, 99.9, 3.33, 50.0])x = range(len(values))# split it upabove_threshold = np.maximum(values - threshold, 0)below_threshold = np.minimum(values, threshold)# and plot itfig, 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 thresholdax.plot([0., 4.5], [threshold, threshold], "k--")fig.savefig("look-ma_a-threshold-plot.png")

Example plot showing the result of the code