【问题标题】:Remove line through marker in matplotlib legend通过 matplotlib 图例中的标记删除线
【发布时间】:2022-01-23 05:55:12
【问题描述】:

我有一个使用以下代码生成的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()

以此作为生成的图:

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

【问题讨论】:

    标签: python matplotlib legend


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

      您可以在 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()
      

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

      【讨论】:

      • 有趣的是,这仍然“绘制”(或分配空间)图例中的线,看看我们的答案之间的图例中的间距。
      • 就个人而言,我认为这些符号看起来不错,周围有一点空间,但如果我要优化它,我会放比上面显示的少一点。填充也可以使用关键字参数进行 tweeked,例如:handletextpad=-.5, columnspacing=0, borderpad=-.5, borderaxespad=0 等,包括可用作关键字参数的handlelength
      • uff,不是None,而是"None"
      【解决方案3】:

      您可以为绘图设置rcparams

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

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

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

      【讨论】:

      • 这是一个设置全局参数的好例子。对于非全局设置,我更喜欢 @tom10 的答案。
      【解决方案4】:

      你应该在这里使用散点图

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

      【讨论】:

      • 这是我的第一反应,但我认为这个例子可能太具体了——如果 OP 想要一个多点的真实情节怎么办?
      • 嗯,可能是这样。我只是假设他不知道散点图功能。如果他真的想要一个多点的真实情节,他应该在这里寻求其他答案之一。
      • 我确实知道scatter 的情节。但我需要更通用的东西。我只是在这里以plot 为例。我当前的真实应用程序实际上使用errorbarscatter 不允许我绘制误差线。
      猜你喜欢
      • 2020-05-01
      • 2013-08-12
      • 2022-06-11
      • 1970-01-01
      • 1970-01-01
      • 2011-08-09
      • 2016-01-30
      • 2019-01-05
      相关资源
      最近更新 更多