Matplotlib如何将含PolyCollection的图例生成为独立可保存实例
问题解决:Matplotlib独立图例中添加fill_between生成的PolyCollection元素
问题原因
独立创建的新figure实例默认没有配置PolyCollection类型的图例处理器,因此无法直接识别fill_between返回的对象生成对应图例条目。
解决方法(兼容Matplotlib 3.3.2版本)
推荐使用代理图形对象的方案,兼容性最强,无需依赖版本特性:
- 从
matplotlib.patches导入Patch类,手动创建和填充区域样式完全一致的代理对象 - 将代理对象传入独立figure的
legend方法即可
完整可运行修改代码
import matplotlib.pyplot as plt import numpy as np from matplotlib.patches import Patch # 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']) # create new plot only for legend legendFig = plt.figure('Legend plot') # 创建和填充区域同样式的代理对象 fill_proxy = Patch(facecolor=fill.get_facecolor()[0], edgecolor=fill.get_edgecolor()[0], alpha=fill.get_alpha()) # 传入代理对象生成包含填充区域的图例 legendFig.legend([line1, line2, fill_proxy],['Log','Sin', 'Area']) plt.show()
可选方案:指定图例处理器
也可以直接给legend方法传入PolyCollection对应的处理器,不需要创建代理对象:
from matplotlib.legend_handler import HandlerPolyCollection # 调用legend时添加handler_map参数 legendFig.legend([line1, line2, fill],['Log','Sin', 'Area'], handler_map={type(fill): HandlerPolyCollection()})
内容的提问来源于stack exchange,提问作者ABot
相关产品推荐
相关产品推荐

