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')
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.
Make a dictionary d with keys Column1 and Column2. Make a data frame using DataFrame (d). Plot the data frame with a list of styles. Using legend(), place a legend on the figure.
Which argument must be set with plotting function for Legend () to display the legends? Arguments. the x and y co-ordinates to be used to position the legend. They can be specified by keyword or in any way which is accepted by xy.
Well, Simply chain it.
dframe.rank(ascending=False).plot(kind= 'bar').legend(loc='best')
Assuming 'dframe' is a DataFrame.
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()
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