Search code examples
pythonmatplotlibplot

add legend with the exact value of a mean line


I have made a plot using matplotlib library, which depicts two histograms and the mean lines. I think that the plot would be more clear if I add the legend. I want to create a legend, which says what exact values have this two mean lines. Below I attache my code and the plot which I generated and the picture which shows what I want to achieve (it is picture where I added the legend using powerpoint):

def setPlot(data, mycolor, myalpha, mylinestyle):
    plt.style.use('ggplot')
    plt.rc('xtick',labelsize=12)
    plt.rc('ytick',labelsize=12)
    plt.xlabel("Incomes")
    plt.hist(data, bins=50, color= mycolor, alpha=myalpha)
    plt.axvline(numpy.mean(data), color=mycolor, linestyle=mylinestyle, linewidth=1.5)
    plt.show()

enter image description here

enter image description here

I will be grateful for any suggestions.

-----------SOLUTION--------

Thanks to the great advises from wwii and tom I was able to implement the solution to my idea. I have tried to concatenate both suggestions, and this is what I obtained:

def setPlot(data, mycolor, myalpha, mylinestyle):
    plt.style.use('ggplot')
    plt.rc('xtick',labelsize=12)
    plt.rc('ytick',labelsize=12)
    plt.xlabel("Incomes")
    plt.hist(data, bins=50, color= mycolor, alpha=myalpha)
    plt.axvline(numpy.mean(data), color=mycolor, linestyle=mylinestyle, linewidth=1.5, label=str(numpy.mean(data)))
    plt.legend(loc='upper right')
    plt.show()

And the example of my generated plot: enter image description here

Many thanks for all your help!


Solution

  • You just need to give your axvline a label, then call plt.legend after plotting both your histograms. Like this:

    import matplotlib.pyplot as plt
    import numpy
    
    def setPlot(data, mycolor, myalpha, mylinestyle):
        plt.style.use('ggplot')
        plt.rc('xtick',labelsize=12)
        plt.rc('ytick',labelsize=12)
        plt.xlabel("Incomes")
        plt.hist(data, bins=50, color= mycolor, alpha=myalpha)
        plt.axvline(numpy.mean(data), color=mycolor, linestyle=mylinestyle,
                    linewidth=1.5,label='{:5.0f}'.format(numpy.mean(data)))
    
    setPlot(numpy.random.rand(100)*30000.,'r',0.5,'--')
    setPlot(numpy.random.rand(100)*20000.,'b',0.5,'-')
    
    plt.legend(loc=0)
    
    plt.savefig('myfig.png')
    

    enter image description here