[英]Matplotlib legend in separate figure with PolyCollection object
我需要将图例创建为单独的图形,更重要的是可以将其保存在新文件中的单独实例。 我的情节由线条和填充的线段组成。
问题是fill_between
元素,我无法将其添加到外部图形/图例中。
我意识到,这是一种不同类型的对象,它是一个PolyCollection
,而线图是Line2D
元素。
如何处理PolyCollection
以便我可以在外部图例中使用它?
信息:matplotlib 版本 3.3.2
import matplotlib.pyplot as plt
import numpy as np
# Dummy data
x = np.linspace(1, 100, 1000)
y = np.log(x)
y1 = np.sin(x)
# Create regular plot and plot everything
fig = plt.figure('Line plot')
ax = fig.add_subplot(111)
line1, = ax.plot(x, y)
line2, = ax.plot(x, y1)
fill = ax.fill_between(x, y, y1)
ax.legend([line1, line2, fill],['Log','Sin','Area'])
ax.plot()
# create new plot only for legend
legendFig = plt.figure('Legend plot')
legendFig.legend([line1, line2],['Log','Sin']) <----- This works
# legendFig.legend([line1, line2, fill],['Log','Sin', 'Area']) <----- This does not work
你忘了提到这里不起作用的意思。 显然,您会收到一条错误消息: RuntimeError: Can not put single artist in more than one figure
。
Matplotlib 不允许放置在一个图形中的元素在另一个图形中重复使用。 该line
没有给出错误只是一个幸运的巧合。
要在另一个图形中使用元素,您可以创建一个新元素,并从原始元素复制样式:
from matplotlib.lines import Line2D
from matplotlib.collections import PolyCollection
legendFig = plt.figure('Legend plot')
handle_line1 = Line2D([], [])
handle_line1.update_from(line1)
handle_line2 = Line2D([], [])
handle_line2.update_from(line2)
handle_fill = PolyCollection([])
handle_fill.update_from(fill)
legendFig.legend([handle_line1, handle_line2, handle_fill], ['Log', 'Sin', 'Area'])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.