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

时间:2014-01-22 14:39:11

标签: 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()

将此作为生成的数字: matplotlib generated figure

我不喜欢图例中标记的线条。我该怎样摆脱它们?

4 个答案:

答案 0 :(得分:39)

您可以在plot命令中将linestyle="None"指定为关键字参数:

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

enter image description here

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

答案 1 :(得分:7)

您可以为地块设置rcparams

import matplotlib
matplotlib.rcParams['legend.handlelength'] = 0
matplotlib.rcParams['legend.numpoints'] = 1

enter image description here

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

legend setting (numpoints and scatterpoints) in matplotlib does not work

答案 2 :(得分:4)

只需在绘制数据后删除线条:

handles, labels = ax.get_legend_handles_labels()
for h in handles: h.set_linestyle("")
ax.legend(handles, labels)

答案 3 :(得分:2)

你应该在这里使用散点图

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