32

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')

Daniel Lima
  • 925
  • 1
  • 8
  • 22
  • 1
    Can you show an example code where `plt.legend(loc='lower left')` does not work? – ImportanceOfBeingErnest Jan 17 '20 at 17:07
  • @danielLima Just call `plt.legend(loc='lower left')` after calling `df.plot(...)` – JohanC Jan 17 '20 at 17:19
  • Hi, I am actually looking into a way to do it via pandas, when calling df.plot() – Daniel Lima Jan 17 '20 at 17:28
  • Yes, but the command is the same. So unless you can show a code where `plt.legend(loc='lower left')` does not give the desired result, the question is not very useful. – ImportanceOfBeingErnest Jan 17 '20 at 17:41
  • 2
    @DanielLima Pandas plotting is just a layer upon matplotlib. Pandas brings its own way of passing data, but the settings are all handled by matplotlib. It doesn't make sense for Pandas to copy all of matplotlib's extensive functionality. Pandas quickly creates a plot from dataframes. If you need finetuning, there comes matplotlib. – JohanC Jan 17 '20 at 18:57
  • Have you had a chance to look at my answer? I can add more explanation if it is still unclear – William Miller Jan 20 '20 at 00:58
  • 1
    I have edited my answer in response to your edit, I would recommend taking a look – William Miller Jan 27 '20 at 06:29

3 Answers3

42

Well, Simply chain it.

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

Assuming 'dframe' is a DataFrame.

Aadil Rashid
  • 679
  • 6
  • 6
  • Welcome to StackOverflow! Very nice solution :-) – r_31415 Feb 21 '21 at 21:08
  • 2
    Docs for ```.legend``` are at https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.legend.html – phhu Apr 21 '21 at 16:08
  • 4
    Not working for pandas 1.3.5. I get "AttributeError: 'numpy.ndarray' object has no attribute 'legend'" when trying df.plot().legend() – erickfis Feb 08 '22 at 12:03
26

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

William Miller
  • 9,839
  • 3
  • 25
  • 46
6

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

PeterPanda
  • 86
  • 1
  • 2