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')
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:
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.
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.
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.
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"]);
Another approach is to do the same by plt.legend([...])
:
import matplotlib.pyplot as plt df.plot(kind='bar') plt.legend(["AAA", "BBB"]);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With