Search code examples
pythonpandasmatplotlibplot

Modify the legend of pandas bar plot


I am always bothered when I make a bar plot with pandas and I want to change the names of the labels in the legend. Consider for instance the output of this code:

import pandas as pd
from matplotlib.pyplot import *

df = pd.DataFrame({'A':26, 'B':20}, index=['N'])
df.plot(kind='bar')

enter image description here Now, if I want to change the name in the legend, I would usually try to do:

legend(['AAA', 'BBB'])

But I end up with this:

enter image description here

In fact, the first dashed line seems to correspond to an additional patch.

So I wonder if there is a simple trick here to change the labels, or do I need to plot each of the columns independently with matplotlib and set the labels myself. Thanks.


Solution

  • To change the labels for Pandas df.plot() use ax.legend([...]):

    import pandas as pd
    import matplotlib.pyplot as plt
    
    fig, ax = plt.subplots()
    df = pd.DataFrame({'A':26, 'B':20}, index=['N'])
    df.plot(kind='bar', ax=ax)
    #ax = df.plot(kind='bar') # "same" as above
    ax.legend(["AAA", "BBB"]);
    

    enter image description here

    Another approach is to do the same by plt.legend([...]):

    import matplotlib.pyplot as plt
    df.plot(kind='bar')
    plt.legend(["AAA", "BBB"]);
    

    enter image description here