Matplotlib:在图例内移动标记位置

2024-05-29 08:20:32 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个绘图,在其中我需要的信息编码线的风格,颜色和标记。 但是,当我创建图例时,标记覆盖了线条的很大一部分,导致线条样式难以识别。例如:

markers obscuring line-style in the legend

是否可以将标记移动到一侧(左侧或右侧),以便整条线及其线样式可见?类似于以下内容(在inkscape中手动移动):

markers moved to side not to obscure line-style in the legend


Tags: 标记信息绘图编码颜色风格样式手动
1条回答
网友
1楼 · 发布于 2024-05-29 08:20:32

一个想法是画一个更长的句柄(例如plt.legend(handlelength=4.0))。此外,可以使用两个点代替中心的一个点,每端一个点(plt.legend(numpoints=2)

下面是一个示例的样子:

import matplotlib.pyplot as plt

plt.plot([0, 1], [2, 1], ls='-.', marker='D', color='r', label='A')
plt.plot([0, 1], [1, 0], ls=' ', marker='D', color='b', label='B')
plt.legend(numpoints=2, handlelength=4.0)
plt.show()

legend with longer handles

更复杂的方法是使用新的tuple handlerlegend guide)并使用两个处理程序创建元组。第一个处理程序仅包含线型(删除标记),第二个处理程序仅包含标记(删除线型):

import matplotlib.pyplot as plt
from matplotlib.legend_handler import HandlerTuple
from copy import copy

plt.plot([0, 1], [2, 1], ls='-.', marker='D', color='r', label='A')
plt.plot([0, 1], [1, 0], ls=' ', marker='D', color='b', label='B')
handles, labels = plt.gca().get_legend_handles_labels()
new_handles = []
for h in handles:
    h1 = copy(h)
    h1.set_marker('')
    h2 = copy(h)
    h2.set_linestyle('')
    new_handles.append((h1, h2))
plt.legend(handles=new_handles, labels=labels, handlelength=4.0,
           handler_map={tuple: HandlerTuple(ndivide=None)})
plt.show()

legend with tuple handler

相关问题 更多 >

    热门问题