我如何在 matplotlib FuncAnimation 上添加文本

How do i add a text on matplotlib FuncAnimation

我在 运行 matplotlib funcanimation 时使用轴坐标而不是数据坐标将文本添加到静态位置时遇到困难。你介意帮我一下吗?

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

#creats subplots
fig = plt.figure(figsize=(8,4))     [enter image description here][1]
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)

#values
x_vals=[]
y1_vals=[]
y2_vals=[]
y3_vals=[]
y4_vals=[]
y5_vals=[]
index = count()

def animate(i):
    #generate and append data
    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))

#plot graph
    ax1.plot(x_vals, y1_vals, color='green')
    ax2.plot(x_vals, y2_vals, color='white')
    ax3.plot(x_vals, y3_vals, color='green')
    ax4.plot(x_vals, y4_vals, color='white')
    ax5.plot(x_vals, y5_vals, color='green')

#add text and title
    **ax1.text(y=3, x=0.05, s='position 1',  transform=ax.transAxes, color='white' )**
    ax1.set_title(label='graph 1', loc='center', fontsize=15, color='white' )
#funcanimation
anim = FuncAnimation(fig, animate, interval=1000)
plt.show()

想要的图片

我看到一些可能有误的地方:

ax1.text(y=3, x=0.05, s='position 1',  transform=ax.transAxes, color='white' )
  1. ax.transAxes 应该是 ax1.transAxes
  2. ax1 具有白色背景,因此您不会看到 color='white' 文本。试试黑色:color='k'
  3. Axes 坐标从 0.0 到 1.0(Axes 对象的分数)。 因此 y=3 将不起作用。尝试 y=0.9

当我进行上述更改时,它对我有用。