Python 情节图例:标记出现两次
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12732614/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python plot legend : markers appear twice
提问by Patrick
A simple plot with a legend made with matplotlib produces the following: the markers at the left of the labels of my legend appear twice. Can anyone know why and how to avoid the problem? My command is:
使用 matplotlib 制作的带有图例的简单图会产生以下结果:图例标签左侧的标记出现两次。谁能知道为什么以及如何避免这个问题?我的命令是:
pl.plot(x1,x2,'g^', label='regional')
pl.plot(y1,y2,'bo', label='local')
pl.legend( loc='upper left' )
Thank you
谢谢
采纳答案by unutbu
You can change the number of markers shown in the legend by using the numpointskeyword:
您可以使用numpoints关键字更改图例中显示的标记数量:
import matplotlib.pyplot as plt
import numpy as np
x1 = y1 = np.linspace(0, 10, 100)
x2 = np.sin(x1)
y2 = np.cos(y1)
plt.plot(x1,x2,'g--^', label='regional')
plt.plot(y1,y2,'b-o', label='local')
plt.legend( loc='upper left', numpoints = 1 )
plt.show()


I believe the reason the markers appear twice (by default) is because matplotlib is trying to show the linestyle connectors between the markers. It looks a little odd when there is no connector.
我相信标记出现两次的原因(默认情况下)是因为 matplotlib 试图显示标记之间的线型连接器。没有连接器时看起来有点奇怪。
If the plot had solid and dashed lines,
如果情节有实线和虚线,
plt.plot(x1,x2,'g--^', label='regional')
plt.plot(y1,y2,'b-o', label='local')
then the legend looks like this:
那么图例看起来像这样:


and now you can see the effect of the linestyle between the markers in the legend (as well as on the graph).
现在您可以看到图例(以及图形)中标记之间的线型效果。
If you don't want any legend handle at all, then you could use
如果您根本不想要任何图例句柄,那么您可以使用
plt.legend(..., handlelength=0)
For example,
例如,
import numpy as np
import matplotlib.pyplot as plt
x1 = y1 = np.linspace(0, 10, 100)
x2 = np.sin(x1)
y2 = np.cos(y1)
plt.plot(x1,x2,'g--^', label='regional')
plt.plot(y1,y2,'b-o', label='local')
plt.legend(loc='best', numpoints=1, handlelength=0)
plt.show()


You could use
你可以用
plt.legend(loc='best', numpoints=1, handlelength=0,
markerscale=0, handletextpad=0)
to remove the legend marker as well.
也删除图例标记。

