Matplotlib中如何从vlines返回的LineCollection提取Line2D用于图例?
Matplotlib中vlines竖直线添加图例的解决方案
LineCollection是批量线条的容器,内部并没有单独的Line2D对象实例,不存在从LineCollection提取Line2D的方法,官方也没有提供反向提取的接口。以下是几种实用的替代方案:
方案一:手动构造Line2D对象作为图例项
直接创建一个和竖直线样式匹配的Line2D对象,专门用于图例展示:
import matplotlib.pyplot as plt from matplotlib.lines import Line2D fig, ax = plt.subplots(1,1) ax.plot(meas['times'], meas['data'], label='measurement') # 绘制竖直线,记录样式 vlins = ax.vlines([trigger_time], 0, 100) # 获取现有图例的手柄与标签 lines, labels = ax.get_legend_handles_labels() # 生成匹配样式的Line2D对象 legend_handle = Line2D( [], [], color=vlins.get_edgecolor()[0], linestyle=vlins.get_linestyle()[0], linewidth=vlins.get_linewidth()[0] ) # 更新图例 ax.legend(lines + [legend_handle], labels + ['trigger event']) plt.show()
方案二:改用plot绘制单条竖直线
如果仅需绘制单条竖直线,直接用ax.plot替代vlines,返回的就是Line2D对象,可直接添加图例:
fig, ax = plt.subplots(1,1) ax.plot(meas['times'], meas['data'], label='measurement') # 用plot绘制竖直线,x坐标固定为trigger_time,y覆盖0到100 ax.plot([trigger_time, trigger_time], [0, 100], label='trigger event') ax.legend() plt.show()
方案三:自定义图例条目
通过ax.legend的handles参数直接传入自定义条目,本质和方案一类似:
fig, ax = plt.subplots(1,1) ax.plot(meas['times'], meas['data'], label='measurement') ax.vlines([trigger_time], 0, 100) # 直接构造图例手柄列表 handles = [ plt.Line2D([], [], color='C0', label='measurement'), plt.Line2D([], [], color='C1', label='trigger event') ] ax.legend(handles=handles) plt.show()
内容的提问来源于stack exchange,提问作者Axel Heinrici
相关产品推荐
相关产品推荐

