Daniel Lima
Daniel Lima

Reputation: 995

Set the legend location of a pandas plot

I know how to set the legend location of matplotlib plot with plt.legend(loc='lower left'), however, I am plotting with pandas method df.plot() and need to set the legend location to 'lower left'.

Does anyone know how to do it?

Edited: I am actually looking for a way to do it through pandas' df.plot(), not via plt.legend(loc='lower left')

Upvotes: 38

Views: 70661

Answers (3)

PeterPanda
PeterPanda

Reputation: 136

With pandas 1.5.3 you can chain legend() behind plot() see matplotlib.

Example:

matched.set_index(
    matched.index.date
).plot(kind='barh', stacked=True
).legend(
    bbox_to_anchor=(1.0, 1.0),
    fontsize='small',
);

Screenshot Jupyter cell

Upvotes: 11

William Miller
William Miller

Reputation: 10320

Edit

To clarify the original answer, there is presently no way to do this through pandas.DataFrame.plot. In its current implementation (version 1.2.3) the 'legend' argument of plot accepts only a boolean or the string 'reverse':

legend : False/True/'reverse'
   Place legend on axis subplots

It does not accept legend position strings. The remaining **kwargs are passed into the underlying matplotlib.pyplot method which corresponds to the specified 'kind' argument (defaults to matplotlib.pyplot.plot). None of those methods allow for legend positioning via their keyword arguments.

Therefore, the only way to do this at present is to use plt.legend() directly - as outlined in my original answer, below.


As the comments indicate, you have to use plt.legend(loc='lower left') to put the legend in the lower left. Even when using pandas.DataFrame.plot - there is no parameter which adjusts legend position, only if the legend is drawn. Here is a complete example to show the usage

import pandas as pd
import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 10, 100)
y = np.random.random(100)

df = pd.DataFrame({'x': x, 'y':y})
df.plot(kind='scatter', x='x', y='y', label='Scatter')
plt.legend(loc='lower left')
plt.show()

enter image description here

Upvotes: 25

Aadil Rashid
Aadil Rashid

Reputation: 779

Well, Simply chain it.

dframe.rank(ascending=False).plot(kind= 'bar').legend(loc='best')

Assuming 'dframe' is a DataFrame.

Upvotes: 51

Related Questions