Python 通过 matplotlib 图例中的标记删除线
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21285885/
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
Remove line through marker in matplotlib legend
提问by jlconlin
I have a matplotlibplot generated with the following code:
我有一个matplotlib使用以下代码生成的图:
import matplotlib.pyplot as pyplot
Fig, ax = pyplot.subplots()
for i, (mark, color) in enumerate(zip(
['s', 'o', 'D', 'v'], ['r', 'g', 'b', 'purple'])):
ax.plot(i+1, i+1, color=color,
marker=mark,
markerfacecolor='None',
markeredgecolor=color,
label=i)
ax.set_xlim(0,5)
ax.set_ylim(0,5)
ax.legend()
with this as the generated figure:

以此作为生成的图:

I don't like the lines through the markers in the legend. How can I get rid of them?
我不喜欢图例中通过标记的线条。我怎样才能摆脱它们?
采纳答案by tom10
You can specify linestyle="None"as a keyword argument in the plot command:
您可以linestyle="None"在 plot 命令中指定为关键字参数:
import matplotlib.pyplot as pyplot
Fig, ax = pyplot.subplots()
for i, (mark, color) in enumerate(zip(
['s', 'o', 'D', 'v'], ['r', 'g', 'b', 'purple'])):
ax.plot(i+1, i+1, color=color,
marker=mark,
markerfacecolor='None',
markeredgecolor=color,
linestyle = 'None',
label=`i`)
ax.set_xlim(0,5)
ax.set_ylim(0,5)
ax.legend(numpoints=1)
pyplot.show()


Since you're only plotting single points, you can't see the line attribute except for in the legend.
由于您只绘制单个点,因此除了图例之外,您看不到线属性。
回答by M4rtini
You should use a scatterplot here
你应该在这里使用散点图
import matplotlib.pyplot as pyplot
Fig, ax = pyplot.subplots()
for i, (mark, color) in enumerate(zip(
['s', 'o', 'D', 'v'], ['r', 'g', 'b', 'purple'])):
ax.scatter(i+1, i+1, color=color,
marker=mark,
facecolors='none',
label=i)
ax.set_xlim(0,5)
ax.set_ylim(0,5)
ax.legend(scatterpoints=1)
pyplot.show()
回答by Hooked
You can set the rcparamsfor the plots:
您可以rcparams为绘图设置:
import matplotlib
matplotlib.rcParams['legend.handlelength'] = 0
matplotlib.rcParams['legend.numpoints'] = 1


All the legend.* parameters are available as keywords if you don't want the setting to apply globally for all plots. See matplotlib.pyplot.legenddocumentation and this related question:
如果您不希望将设置全局应用于所有绘图,则所有图例.* 参数都可用作关键字。请参阅matplotlib.pyplot.legend文档和此相关问题:
legend setting (numpoints and scatterpoints) in matplotlib does not work
回答by blalterman
To simply remove the lines once the data has been plotted:
在绘制数据后简单地删除线条:
handles, labels = ax.get_legend_handles_labels()
for h in handles: h.set_linestyle("")
ax.legend(handles, labels)

