简体   繁体   中英

redundant legends in python matplot lib

I am plotting two conditions and want only two legends. But there are replicates in my data, and I am getting a separate legend for each replicate. Why? I apologize if this has previously been addressed, but I have spent an embarrassing amount of time on this and much of what I find seems overly complex for my situation. Any help would be appreciated.

import matplotlib.pyplot as plt
import pandas as pd

#####read and organize data
alldata = pd.read_csv('Fig_1.csv')

CondtionA = list(zip(alldata.iloc[:,1],alldata.iloc[:,2]))
ConditionB = list(zip(alldata.iloc[:,7],alldata.iloc[:,8]))

### make the figure
fig, ax = plt.subplots()

plt.plot(alldata['Temperature'],ConditionA,linewidth = 1,c='k', linestyle = '--',label = 'ConditionA')
plt.plot(alldata['Temperature'],ConditionB,linewidth = 1,c='k', label = "ConditonB")
ax.legend(numpoints=1)

plt.show()

在此处输入图片说明

a) use returned lines

You should be able to create a legend from only the first item of the returned lines of each plot call.

lines1 = plt.plot(...)
lines2 = plt.plot(...)

plt.legend(handles=(lines1[0], lines2[0]), labels=("Label A", "Label B"))

The drawback here is that you need to name the labels again manually.

b) select every second legend handle/label

If that is undesired, but if in turn you know that you want to use every second handle and label from the originally created legend, you can get those handles and labels via get_legend_handles_labels() .

handles, labels = plt.gca().get_legend_handles_labels()
plt.legend(handles[::2], labels[::2])


Reproducible example:

 import numpy as np; np.random.seed(10) import matplotlib.pyplot as plt x=np.arange(10) a = np.cumsum(np.cumsum(np.random.randn(10,2), axis=0), axis=1) b = np.cumsum(np.cumsum(np.random.randn(10,2), axis=0), axis=1)+6 lines1 = plt.plot(x,a, label="Label A", color="k") lines2 = plt.plot(x,b, label="Label B", color="k", linestyle="--") # either: plt.legend(handles=(lines1[0], lines2[0]), labels=("Label A", "Label B")) # or alternatively: handles, labels = plt.gca().get_legend_handles_labels() plt.legend(handles[::2], labels[::2]) plt.show() 

在此处输入图片说明

If you remove

ax.legend(numpoints=1)

and add

plt.legend(handles=[p1,p2], bbox_to_anchor=(0.75, 1), loc=2, borderaxespad=0.)

You will get only one legend.

So your code will look like

import matplotlib.pyplot as plt
import pandas as pd

#####read and organize data
alldata = pd.read_csv('Fig_1.csv')

CondtionA = list(zip(alldata.iloc[:,1],alldata.iloc[:,2]))
ConditionB = list(zip(alldata.iloc[:,7],alldata.iloc[:,8]))

### make the figure
fig, ax = plt.subplots()

p1 = plt.plot(alldata['Temperature'],ConditionA,linewidth = 1,c='k', linestyle = '--',label = 'ConditionA')
p2 = plt.plot(alldata['Temperature'],ConditionB,linewidth = 1,c='k', label = "ConditonB")
#ax.legend(numpoints=1)
plt.legend(handles=[p1,p2], bbox_to_anchor=(0.75, 1), loc=2, borderaxespad=0.)


plt.show()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM