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

前端 未结 2 1855
清酒与你
清酒与你 2021-02-04 06:46

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

2条回答
  •  执念已碎
    2021-02-04 07:32

    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

提交回复
热议问题