Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 952
Benares Avatar asked Oct 15 '15 13:10

Benares


People also ask

How do you add a legend to a bar chart in Python?

If you feel adding the legend inside the chart is noisy, you can use the bbox_to_anchor option to plot the legend outside. bbox_to_anchor have (X, Y) positions, where 0 is the bottom-left corner of the graph and 1 is the upper-right corner.

How do you change the legend in Matplotlib?

To change the position of a legend in Matplotlib, you can use the plt. legend() function. The default location is “best” – which is where Matplotlib automatically finds a location for the legend based on where it avoids covering any data points.


Video Answer


1 Answers

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

like image 70
Sergey Bushmanov Avatar answered Sep 22 '22 00:09

Sergey Bushmanov