Matplotlib图例半色线入口

Matplotlib legend half-color line entry

有没有办法在 Matplotlib 中为单个图例条目绘制多色线?

例如,在下图中,条目 Class 1 和 2 的行在中间点的左侧显示为黑色,在右侧显示为灰色。

您可以通过元组图例处理程序 (HandlerTuple) 组合每个标签的处理程序。

from matplotlib import pyplot as plt
from matplotlib.legend_handler import HandlerTuple
import numpy as np

fig, ax = plt.subplots()
ax.plot(np.random.rand(2), color='black', ls='--', label='Class 1')
ax.plot(np.random.rand(2), color='.7', ls='--', label='Class 1')
ax.plot(np.random.rand(2), color='black', ls='-', label='Class 2')
ax.plot(np.random.rand(2), color='.7', ls='-', label='Class 2')

handles, labels = ax.get_legend_handles_labels()
unique_labels = list(np.unique(labels))
combined_handles = [tuple([h for h, l in zip(handles, labels) if l == label]) for label in unique_labels]

ax.legend(handles=combined_handles, labels=unique_labels, handlelength=3,
          handler_map={tuple: HandlerTuple(ndivide=None, pad=0)})
plt.show()

PS:如果你有两个子图,你可以组合两者的句柄和标签:

from matplotlib import pyplot as plt
from matplotlib.legend_handler import HandlerTuple
import numpy as np

fig, ax1 = plt.subplots()
ax1.plot(np.random.rand(2), color='black', ls='--', label='Class 1')
ax1.plot(np.random.rand(2), color='black', ls='-', label='Class 2')
ax2 = ax1.twinx()
ax2.plot(np.random.rand(2), color='.7', ls='--', label='Class 1')
ax2.plot(np.random.rand(2), color='.7', ls='-', label='Class 2')

handles1, labels1 = ax1.get_legend_handles_labels()
handles2, labels2 = ax2.get_legend_handles_labels()
labels = labels1 + labels2
unique_labels = list(np.unique(labels))
combined_handles = [tuple([h for h, l in zip(handles1 + handles2, labels) if l == label]) for label in unique_labels]

ax1.legend(handles=combined_handles, labels=unique_labels, handlelength=3,
           handler_map={tuple: HandlerTuple(ndivide=None, pad=0)})
plt.show()