我想生成一个自定义matplotlib图例,对于每个条目,每个标签都有两行,如下例所示:
通过一些研究,似乎可以简单地提供两个handles' to thefig.legend(handles,labels)`方法(请参阅此示例)。但是,如下面的示例代码所示,这只是将线彼此重叠。
import matplotlib.lines as mlines
import matplotlib.pyplot as plt
blue_line = mlines.Line2D([], [], color='r')
green_line = mlines.Line2D([], [], linestyle='--', color='k')
fig, ax = plt.subplots(figsize=(5, 5))
handles = [(blue_line,green_line)]
labels = ['test']
fig.legend(handles=handles, labels=labels, fontsize=20)
Run Code Online (Sandbox Code Playgroud)
因此,我想我要么需要转换一个Line2D对象,要么生成一个Patch包含两行的新对象。但是,我不知道该怎么做-是否有简单的方法来组合两个补丁,还是错过了组合手柄的技巧?
如果这对其他人有帮助,上下文是我正在使用此处讨论的技术,该技术是双轴,其颜色被着色为可以同时显示两个不同的图。但是,这两行具有相同的标签,因此为什么要将它们组合在一起。
在matplotlib图例指南中,有一章介绍自定义图例处理程序。您可以根据需要调整它,例如:
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.legend_handler import HandlerBase
class AnyObjectHandler(HandlerBase):
def create_artists(self, legend, orig_handle,
x0, y0, width, height, fontsize, trans):
l1 = plt.Line2D([x0,y0+width], [0.7*height,0.7*height],
linestyle='--', color='k')
l2 = plt.Line2D([x0,y0+width], [0.3*height,0.3*height], color='r')
return [l1, l2]
x = np.linspace(0, 3)
fig, axL = plt.subplots(figsize=(4,3))
axR = axL.twinx()
axL.plot(x, np.sin(x), color='k', linestyle='--')
axR.plot(x, 100*np.cos(x), color='r')
axL.set_ylabel('sin(x)', color='k')
axR.set_ylabel('100 cos(x)', color='r')
axR.tick_params('y', colors='r')
plt.legend([object], ['label'],
handler_map={object: AnyObjectHandler()})
plt.show()
Run Code Online (Sandbox Code Playgroud)
为了有多个这样的条目,可以提供一些元组的参数,Handler然后用它们来绘制图例。
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.legend_handler import HandlerBase
class AnyObjectHandler(HandlerBase):
def create_artists(self, legend, orig_handle,
x0, y0, width, height, fontsize, trans):
l1 = plt.Line2D([x0,y0+width], [0.7*height,0.7*height],
linestyle=orig_handle[1], color='k')
l2 = plt.Line2D([x0,y0+width], [0.3*height,0.3*height],
color=orig_handle[0])
return [l1, l2]
x = np.linspace(0, 3)
fig, axL = plt.subplots(figsize=(4,3))
axR = axL.twinx()
axL.plot(x, np.sin(x), color='k', linestyle='--')
axR.plot(x, 100*np.cos(x), color='r')
axL.plot(x, .3*np.sin(x), color='k', linestyle=':')
axR.plot(x, 20*np.cos(x), color='limegreen')
axL.set_ylabel('sin(x)', color='k')
axR.set_ylabel('100 cos(x)', color='r')
axR.tick_params('y', colors='r')
plt.legend([("r","--"), ("limegreen",":")], ['label', "label2"],
handler_map={tuple: AnyObjectHandler()})
plt.show()
Run Code Online (Sandbox Code Playgroud)