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

两盒软妹~` 提交于 2020-05-09 21:06:41

问题


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.


回答1:


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")

Example plot showing the result of the code




回答2:


You can simply use axhline like this. See this 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)


来源:https://stackoverflow.com/questions/28129606/how-to-create-a-matplotlib-bar-chart-with-a-threshold-line

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!