python matplot lib中的冗余图例

时间:2018-06-21 19:31:41

标签: python matplotlib legend

我正在绘制两个条件,并且只需要两个图例。但是我的数据中有重复项,每个重复项都有一个单独的图例。为什么?如果以前已经解决过这个问题,我深表歉意,但是我为此花费了很多令人尴尬的时间,而且我发现很多情况对于我的情况来说似乎过于复杂。任何帮助,将不胜感激。

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()

enter image description here

2 个答案:

答案 0 :(得分:2)

a)使用返回的行

您应该只能从每个plot调用的返回行的第一行中创建图例。

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

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

这里的缺点是您需要手动重新命名标签。

b)每隔两个选择图例手柄/标签

如果这是不需要的,但又又知道要使用最初创建的图例中的第二个句柄和标签,则可以通过get_legend_handles_labels()获取这些句柄和标签。

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


可重现的示例:

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()

enter image description here

答案 1 :(得分:0)

如果您删除

ax.legend(numpoints=1)

并添加

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

您只会得到一个图例。

所以您的代码看起来像

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()
相关问题