如何在matplotlib的FuncAnimation中使用axes坐标添加固定位置文本
问题排查与修正
你代码中存在3处导致固定文本无法正常显示的错误:
- 坐标轴变量名拼写错误:你声明的子图变量为
ax1,但transform参数中误写为不存在的ax.transAxes - axes坐标系取值错误:axes归一化坐标系的x、y取值范围均为
[0,1],你设置的y=3超出视口范围,文本会被渲染到不可见区域 - 重复创建文本对象:每次动画回调都新建text对象,会产生大量冗余元素拖慢渲染效率
完整修正代码
import matplotlib.pyplot as plt import random from itertools import count from matplotlib.animation import FuncAnimation from datetime import datetime import mplfinance as mpf %matplotlib notebook # 创建子图 fig = plt.figure(figsize=(8,4)) fig.patch.set_facecolor('#121416') ax1=plt.subplot2grid((9,18), (0,0),colspan=12, rowspan=7 ) ax2=plt.subplot2grid((9,18), (0,12),colspan=6, rowspan=3) ax3=plt.subplot2grid((9,18), (3,12),colspan=6, rowspan=3) ax4=plt.subplot2grid((9,18), (6,12),colspan=6, rowspan=3) ax5=plt.subplot2grid((9,18), (7,0),colspan=12, rowspan=3) # 提前创建固定位置文本,使用ax1的axes坐标系 fixed_text = ax1.text(x=0.05, y=0.9, s='position 1', transform=ax1.transAxes, color='white') ax1.set_title(label='graph 1', loc='center', fontsize=15, color='white' ) # 提前创建线对象,避免每次循环重复绘图产生冗余图层 line1, = ax1.plot([], [], color='green') line2, = ax2.plot([], [], color='white') line3, = ax3.plot([], [], color='green') line4, = ax4.plot([], [], color='white') line5, = ax5.plot([], [], color='green') # 初始化坐标值 x_vals=[] y1_vals=[] y2_vals=[] y3_vals=[] y4_vals=[] y5_vals=[] index = count() def animate(i): # 生成并追加数据 x_vals.append(next(index)) y1_vals.append(random.randint(0,4)) y2_vals.append(random.randint(0,3)) y3_vals.append(random.randint(0,2)) y4_vals.append(random.randint(0,3)) y5_vals.append(random.randint(0,4)) # 更新线对象数据,而非重复绘图 line1.set_data(x_vals, y1_vals) line2.set_data(x_vals, y2_vals) line3.set_data(x_vals, y3_vals) line4.set_data(x_vals, y4_vals) line5.set_data(x_vals, y5_vals) # 自适应坐标轴范围,避免数据超出视口 for ax in [ax1, ax2, ax3, ax4, ax5]: ax.relim() ax.autoscale_view() # 如果需要更新文本内容可以在这里修改,不需要的话可以省略 # fixed_text.set_text(f'position 1, 当前帧数: {i}') # 启动动画 anim = FuncAnimation(fig, animate, interval=1000) plt.show()
补充说明
如果需要调整固定文本的位置,直接修改text方法的x、y参数即可,取值范围均为0到1:x=0对应子图左边缘,x=1对应右边缘;y=0对应子图下边缘,y=1对应上边缘。
内容的提问来源于stack exchange,提问作者sachimugu
相关产品推荐
相关产品推荐

