Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/335.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 带有两行的单个图例项_Python_Matplotlib - Fatal编程技术网

Python 带有两行的单个图例项

Python 带有两行的单个图例项,python,matplotlib,Python,Matplotlib,我想生成一个自定义matplotlib图例,对于每个条目,每个标签有两行,如本例所示: 根据一些研究,似乎可以简单地为fig.legend(句柄、标签)`方法提供两个handles'(参见示例)。但是,如下面的示例代码所示,这只是将这些行相互重叠 import matplotlib.lines as mlines import matplotlib.pyplot as plt blue_line = mlines.Line2D([], [], color='r') green_line =

我想生成一个自定义
matplotlib
图例,对于每个条目,每个标签有两行,如本例所示:

根据一些研究,似乎可以简单地为fig.legend(句柄、标签)`方法提供两个
handles'(参见示例)。但是,如下面的示例代码所示,这只是将这些行相互重叠

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)  
因此,我想我要么需要变换一个
Line2D
对象,要么生成一个包含两条线的新
Patch
对象。然而,我不知道如何做到这一点-有没有一种简单的方法来组合两个补丁,或者我错过了组合手柄的技巧

上下文
如果这对其他人有帮助的话,上下文是我正在使用讨论的技术,这是一个双轴,它被着色以同时显示两个不同的图。但是,这两行有相同的标签,因此我想将它们组合在一起。

我在反复研究后得出了一个不合适的解决方案。我张贴它,以防它有助于其他人,但更愿意这样做的正确。它使用两列,第一列的标签作为“/”或者一列可以同样使用“and”


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

为了有多个这样的条目,可以提供一些参数元组,然后
处理程序使用这些参数来绘制图例

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

很好,谢谢你。需要注意的是,为了一次拥有多个不同的“集合”行,必须创建不同的
AnyObject
类,这些类可以用作键。我更新了解决方案,以适应需要多个这样的条目的情况。请注意,
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=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()