Average line for bar chart in matplotlib

前端 未结 1 1455
孤城傲影
孤城傲影 2020-12-30 09:06

How do we draw an average line (horizontal) for a histogram in using matplotlib?

Right now, I\'m able to draw the histogram without any issues. Here is the code I\'m

相关标签:
1条回答
  • 2020-12-30 09:36

    If you'd like a vertical line to denote the mean use axvline(x_value). This will place a vertical line that always spans the full (or specified fraction of) y-axis. There's also axhline for horizontal lines.

    In other works, you might have something like this:

    ax.axvline(data1.mean(), color='blue', linewidth=2)
    ax.axvline(data2.mean(), color='green', linewidth=2)
    

    As a more complete, but unnecessarily complex example (most of this is nicely annotating the means with curved arrows):

    import numpy as np
    import matplotlib.pyplot as plt
    
    data1 = np.random.normal(0, 1, 1000)
    data2 = np.random.normal(-2, 1.5, 1000)
    
    fig, ax = plt.subplots()
    
    bins = np.linspace(-10, 5, 50)
    ax.hist(data1, bins=bins, color='blue', label='Dataset 1',
            alpha=0.5, histtype='stepfilled')
    ax.hist(data2, bins=bins, color='green', label='Dataset 2',
            alpha=0.5, histtype='stepfilled')
    
    ax.axvline(data1.mean(), color='blue', linewidth=2)
    ax.axvline(data2.mean(), color='green', linewidth=2)
    
    # Add arrows annotating the means:
    for dat, xoff in zip([data1, data2], [15, -15]):
        x0 = dat.mean()
        align = 'left' if xoff > 0 else 'right'
        ax.annotate('Mean: {:0.2f}'.format(x0), xy=(x0, 1), xytext=(xoff, 15),
                xycoords=('data', 'axes fraction'), textcoords='offset points',
                horizontalalignment=align, verticalalignment='center',
                arrowprops=dict(arrowstyle='-|>', fc='black', shrinkA=0, shrinkB=0,
                                connectionstyle='angle,angleA=0,angleB=90,rad=10'),
                )
    
    ax.legend(loc='upper left')
    ax.margins(0.05)
    plt.show()
    

    enter image description here

    0 讨论(0)
提交回复
热议问题