在 matplotlib 中更改图例中的标记

use*_*579 5 python matplotlib

假设您绘制一组数据:

plt.plot(x,y, marker='.', label='something')
plt.legend()
Run Code Online (Sandbox Code Playgroud)

在显示屏上,您将获得. something,但是如何将其更改为- something,以便图例中出现的标记是一条线而不是点?

Imp*_*est 5

解决方案肯定取决于您想要转换标记的标准。手动执行此操作很简单:

import matplotlib.pyplot as plt

line, = plt.plot([1,3,2], marker='o', label='something')
plt.legend(handles = [plt.plot([],ls="-", color=line.get_color())[0]],
           labels=[line.get_label()])

plt.show()
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

以自动方式执行相同操作,即图中的每条线都有其对应的图例句柄,即一条颜色相同但没有标记的线:

import matplotlib.pyplot as plt
from matplotlib.legend_handler import HandlerLine2D

plt.plot([1,3,2], marker='o', label='something')
plt.plot([2,3,3], marker='o', label='something else')

def update_prop(handle, orig):
    handle.update_from(orig)
    handle.set_marker("")

plt.legend(handler_map={plt.Line2D:HandlerLine2D(update_func=update_prop)})

plt.show()
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明