创建图例时出现“RuntimeError:不能将单个艺术家放入多个图形中”

Bas*_*ian 5 python matplotlib

我打算在一个单独的图中为已经在另一个图中绘制的元素创建一个新的图例。

这里建议使用以下解决方案,但它失败了PolyCollections,例如,由fill_between.

doesntwork=True

import matplotlib.pyplot as plt

# Here I am creating a figure and saving it to a png file

fig, ax = plt.subplots()
ax.plot( [0,1], [1,0], label='item 1')
if doesntwork:
    ax.fill_between([0,1], [2,1], y2=[1.5,0.5], label='item 2')
ax.legend()
fig.savefig('image.png')


# Here I want the legend stored in a separate png file ...

# ... create a new figure for this purpose
fig_leg = plt.figure(figsize=(1.5, 0.8))
ax_leg = fig_leg.add_subplot(111)

# ... draw the legend
ax_leg.legend(*ax.get_legend_handles_labels(), loc='center')

# ... turn of the axis and save to file
ax_leg.axis('off')
fig_leg.savefig('legend.png')
Run Code Online (Sandbox Code Playgroud)

不做时fill_between,通过设置doesntwork=False,一切正常,legend.png生成显示图例。

随着doesntwork=True我得到:

RuntimeError: Can not put single artist in more than one figure
Run Code Online (Sandbox Code Playgroud)

我怎样才能让它工作doesntwork=True