Matplotlib 更改处理图例中的偏移量

问题描述

是否可以更改图例中手柄的偏移量?

在 3 和 6 中,标记就在点上,如果它再靠右一点会更好,这样可以更好地看到手柄的类型。 我对 markerscalehandlelength 进行了一些调整,但这显然没有太大变化。

如何更改偏移量?

import matplotlib.pyplot as plt
import numpy as np

x = np.array([1,2])
y = np.array([1,3])

plt.plot(x,y,'o-.',color='b',markersize=6,label='test',markeredgecolor="black")

plt.legend(markerscale=0.9,fontsize="medium",handlelength=3)
plt.show()

解决方法

这是一个使用 tuple handler 的想法,如 legend guide 中所述。对于每一行,可以有两个条目,一个只有线条样式,一个只有标记样式。设置 pad=0 会忽略两部分之间的填充,因此默认 handlelength 仍然有效。可能需要最新的 matplotlib 版本。

from matplotlib import pyplot as plt
from matplotlib.lines import Line2D
from matplotlib.legend_handler import HandlerTuple

for i,(ls,ms) in enumerate(zip([':','--','-.',':','-.'],['o','o','^','v','d'])):
    plt.plot([0,10],[i,i + 1],marker=ms,ls=ls,mec='black',label=i + 1,color='cornflowerblue' if i < 3 else 'orange')
plt.xlim(-0.5,14)
handles,labels = plt.gca().get_legend_handles_labels()
new_handles = []
for h in handles:
    l = Line2D([],[])
    l.update_from(h)
    l.set_marker('')
    m = Line2D([],[])
    m.update_from(h)
    m.set_linestyle('')
    new_handles.append((l,m))
plt.legend(handles=new_handles,labels=labels,handler_map={tuple: HandlerTuple(ndivide=None,pad=0)})
plt.show()

legend with linestyle and marker style separated

另一种方法是尝试使用 custom line style