You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Matplotlib的FuncAnimation更新xlim时Annotation注释消失问题求解

问题原因

  • AnnotationBbox的位置更新逻辑错误:你只修改了xybox属性,但AnnotationBbox的锚定基准是xy属性,xybox仅为相对于xy的偏移量。你没有更新xy的话,注释的实际锚点还停留在初始的(times[0],0)位置,当xlim动态右移后,这个位置已经超出当前显示范围,注释就被坐标轴自动裁剪隐藏了。
  • animate函数返回的artist列表格式错误:你返回的是(lines, ann_list)嵌套元组,matplotlib无法正确识别所有需要更新的artist,会导致注释渲染异常。

解决方法

按照以下三个修改点调整代码即可在动态更新xlim时保留注释:

  1. 修正注释的位置更新逻辑,直接修改xy属性设置注释的目标坐标:
# 替换原来修改xybox的代码
first_image_annotation.xy = (x1_and_x2, y1)
second_image_annotation.xy = (x1_and_x2, y2)
  1. 修正animate函数的返回值,把所有需要渲染的artist扁平化返回:
# 替换原来的 return lines, ann_list
return lines + ann_list
  1. 可选:如果需要避免注释被坐标轴裁剪,可以给AnnotationBbox添加clip_on=False参数:
first_image_annotation = AnnotationBbox(
    first_offset_image, (times[0], 0), xycoords='data', frameon=False, clip_on=False)

second_image_annotation = AnnotationBbox(
    second_offset_image, (times[0], 0), xycoords='data', frameon=False, clip_on=False)

内容的提问来源于stack exchange,提问作者Javier Salas

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 17:54:07