I intend to create a new legend in a separate figure for elements already plotted in another figure.
The following solution is suggested here, but it fails for PolyCollections, e.g. produced by 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')
When doing without fill_between, by setting doesntwork=False, all is fine and legend.png is produced showing the legend.
With doesntwork=True I get:
RuntimeError: Can not put single artist in more than one figure
How can I get this to work with doesntwork=True?