Python的matplotlib图例在单独的轴上与gridspec

fmo*_*lia 7 python matplotlib legend

假设我在python脚本中有一个matplotlib的gridspec实例.我想要做的是创建两个轴,并在一个轴上绘制图形,在另一个轴上绘制图例.就像是

import numpy as np
from matplotlib import gridspec, pyplot as plt

x = np.linspace(0,100)
y = np.sin(x)

gs = gridspec.GridSpec( 100, 100 )
ax1 = fig.add_subplot(gs[ :50, : ])
ax2 = fig.add_subplot(gs[ 55:, : ])
ax1.plot( s, y, label=r'sine' )
ax2.legend() # ?? Here I want legend of ax1
plt.show()
Run Code Online (Sandbox Code Playgroud)

有没有办法做到这一点?

tmd*_*son 7

您可以使用ax1.get_legend_handles_labels(),从第一个子图中获取图例句柄和标签,然后在第二个子图上创建图例时使用它们.

来自文档:

get_legend_handles_labels(legend_handler_map=None)

返回图例的句柄和标签

ax.legend() 相当于:

h, l = ax.get_legend_handles_labels() 
ax.legend(h, l)
Run Code Online (Sandbox Code Playgroud)
import numpy as np
from matplotlib import gridspec, pyplot as plt

x = np.linspace(0,100)
y = np.sin(x)

fig = plt.figure()

gs = gridspec.GridSpec( 100,100 )
ax1 = fig.add_subplot(gs[ :50, : ])
ax2 = fig.add_subplot(gs[ 55:, : ])

ax1.plot( x, y, label=r'sine' )

h,l=ax1.get_legend_handles_labels() # get labels and handles from ax1

ax2.legend(h,l)                     # use them to make legend on ax2

plt.show()
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述