gpt4 book ai didi

python - 在 matplotlib 中更改图例中的标记

转载 作者:太空宇宙 更新时间:2023-11-03 15:48:29 25 4
gpt4 key购买 nike

假设您绘制一组数据:

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

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

最佳答案

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

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

enter image description here

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

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

enter image description here

关于python - 在 matplotlib 中更改图例中的标记,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48391146/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com