在 matplotlib 中更改图例中的标记 [英] Change marker in the legend in matplotlib

查看:44
本文介绍了在 matplotlib 中更改图例中的标记的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设您绘制了一组数据:

Suppose that you plot a set of data:

plt.plot(x,y, marker='.', label='something')
plt.legend()

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

On the display, you will obtain . something, but how do you do to change it to - something, so that the marker that appears in the legend is a line a not a dot?

推荐答案

解决方案当然取决于要转换标记的条件.手动执行此操作很简单:

The solution surely depends on the criterion by which you want to transform the marker. Doing this manually is straight forward:

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

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

Doing the same in an automated way, i.e. each line in the plot gets its corresponding legend handle, which is a line in the same color, but without markers:

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

这篇关于在 matplotlib 中更改图例中的标记的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆