Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to delete legend in pandas

I try to plot with both pandas (pd) and matplotlib.pyplot (plt). But I don't want pandas to show legend yet I still need the plt legend. Is there a way I could delete the legend of pandas plot? (legend=False doesn't work)

import pandas as pd
import matplotlib.pyplot as plt

xs = [i for i in range(1, 11)]
ys = [i for i in range(1, 11)]

df = pd.DataFrame(list(zip(xs, ys)), columns=['xs', 'ys'])

fig, ax = plt.subplots()

# plot pd data-frame, I don't want this to show legend
df.plot(x='xs', y='ys', ax=ax, kind='line', legend=False)

# these doesn't work
ax.legend([])
ax.get_legend().remove()
ax.legend().set_visible(False)

# plot by plt, I only want this to show legend
ax.plot(xs, ys, label='I only need this label to be shown')

ax.legend()

plt.show()  # still showing both legends

Note: I prefer not to change the order of plotting (even though plot plt first and then pd could allow showing only plt legend, but the plt plot will get block by pd plot), and not using plt to plot the dataframe's data

like image 427
Jerry wu Avatar asked Jan 25 '26 12:01

Jerry wu


1 Answers

You can remove the 1st set of lines and labels from the legend:

fig, ax = plt.subplots()

df.plot(x='xs', y='ys', ax=ax, kind='line', label='Something')
ax.plot(xs, ys, label='I only need this label to be shown')

# Legend except 1st lines/labels
lines, labels = ax.get_legend_handles_labels()
ax.legend(lines[1:], labels[1:])

plt.show()

enter image description here

like image 171
ALollz Avatar answered Jan 27 '26 00:01

ALollz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!