112

Using the pandas library in python and using

.plot()

on a dataframe, how do I display the plot without a legend?

cottontail
  • 10,268
  • 18
  • 50
  • 51
Bilal Syed Hussain
  • 8,664
  • 11
  • 38
  • 44

3 Answers3

197

There is a parameter in the function corresponding to legend; by default it is True

df.plot(legend=False)

Following is the definition of the .plot() method

Definition: df.plot(frame=None, x=None, y=None, subplots=False, sharex=True, sharey=False, use_index=True, figsize=None, grid=None, legend=True, rot=None, ax=None, style=None, title=None, xlim=None, ylim=None, logx=False, logy=False, xticks=None, yticks=None, kind='line', sort_columns=False, fontsize=None, secondary_y=False, **kwds)

Nipun Batra
  • 11,007
  • 11
  • 52
  • 77
  • 4
    To be precise, this is not really the correct answer since using `.plot()` automatically draws a legend, so it needs to be removed afterwards. In most cases, one would probably chose to use `.plot(legend=False)` but there are cases where you do not have that choice. Since I just encountered one, I added a new answer below. – ImportanceOfBeingErnest Dec 05 '16 at 16:05
  • This can also be used for variations like `df.plot.bar()` by using `df.plot.bar(legend=False)` – Daan Klijn Mar 02 '20 at 14:10
35

In order to remove a legend that has once been drawn, use

plt.gca().get_legend().remove()

assuming that you have imported matplotlib.pyplot as plt or

ax.get_legend().remove()

if ax is the axes where the legend resides.

Alternatively, see Nipun Batras answer if there is some choice to turn the legend off from the beginning in which case one can simply use

df.plot(legend=False)
ImportanceOfBeingErnest
  • 321,279
  • 53
  • 665
  • 712
  • 3
    This is crucial if you are using pandas **parellel_coordinates**, where the call to plot() is buried inside code that you can't easily access. Using plt.gca().legend_.remove() **after** the call to parallel_coordinates successfully turned off the legend. – user5920660 Sep 08 '17 at 19:46
0

I prefer the set_visible(False) syntax because it aligns nicely with other syntaxes that hide stuff, such as hiding spines.

import pandas as pd
df = pd.DataFrame({'A': range(11), 'B': 2, 'C': 5})

ax = df.plot()
ax.legend().set_visible(False)
ax.spines[['right', 'top']].set_visible(False)

plot

cottontail
  • 10,268
  • 18
  • 50
  • 51