Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How remove a specific legend label in the Dataframe.plot?

I am trying to plot two DataFrame together by 'bar' style and 'line' style respectively, but have trouble when showing the legend only for the bars, excluding the line.

Here are my codes:

import numpy as np
import pandas as pd

np.random.seed(5)
df = pd.DataFrame({'2012':np.random.random_sample((4,)),'2014':np.random.random_sample((4,))})
df.index = ['A','B','C','D']
sumdf = df.T.apply(np.sum,axis=1)
ax = df.T.plot.bar(stacked=True)
sumdf.plot(ax=ax)
ax.set_xlim([-0.5,1.5])
ax.set_ylim([0,3])
ax.legend(loc='upper center',ncol=3,framealpha=0,labelspacing=0,handlelength=4,borderaxespad=0)

Annoyingly got this: Figure, where the line legend is also shown in the legend box. I want to remove it rather than make it invisible.

But I do not find the way.

Thank you!

like image 831
L. Li Avatar asked Apr 08 '18 03:04

L. Li


People also ask

How do you remove the legend from a plot?

If you want to plot a Pandas dataframe and want to remove the legend, add legend=None as parameter to the plot command.

How do you get rid of the legend in pandas plot?

Using plt. gca(). legend_. remove() after the call to parallel_coordinates successfully turned off the legend.


1 Answers

If a matplotlib.legend's label starts with an underscore, it will not be shown in the legend by default.

You can simply change

sumdf.plot(ax=ax)

to

sumdf.plot(ax=ax, label='_')

enter image description here

like image 71
Ami Tavory Avatar answered Sep 25 '22 15:09

Ami Tavory