通过matplotlib图例中的标记删除线条

jlc*_*lin 29 python matplotlib legend

我有一个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()
Run Code Online (Sandbox Code Playgroud)

用这个作为生成的数字: matplotlib生成的数字

我不喜欢图例中标记的线条.我怎么能摆脱他们?

tom*_*m10 43

您可以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()
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

由于您只绘制单个点,因此除了图例外,您无法看到线属性.


Hoo*_*ked 7

您可以rcparams为图表设置:

import matplotlib
matplotlib.rcParams['legend.handlelength'] = 0
matplotlib.rcParams['legend.numpoints'] = 1
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

如果您不希望设置全局应用于所有绘图,则所有图例.*参数都可用作关键字.请参阅matplotlib.pyplot.legend文档和此相关问题:

matplotlib中的图例设置(numpoints和散点)不起作用


M4r*_*ini 5

你应该在这里使用散点图

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()
Run Code Online (Sandbox Code Playgroud)


小智 5

要在绘制数据后简单地删除线条:

handles, labels = ax.get_legend_handles_labels()
for h in handles: h.set_linestyle("")
ax.legend(handles, labels)
Run Code Online (Sandbox Code Playgroud)