Search code examples
python-3.xpandasmatplotlibmatplotlib-animation

How do i add a text on matplotlib FuncAnimation


i am having difficulty adding a text to a static position using axes coordinate and not the data coordinate while running matplotlib funcanimation . Would you mind helping me out a bit?

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()

desired image


Solution

  • I see a few things that may be wrong:

    ax1.text(y=3, x=0.05, s='position 1',  transform=ax.transAxes, color='white' )
    
    1. ax.transAxes should be ax1.transAxes
    2. ax1 has a white background, so you won't see color='white' text. Try black: color='k'
    3. Axes coordinates go from 0.0 to 1.0 (fraction of the Axes object). Therefore y=3 will not work. Try y=0.9

    When I made the above changes, it worked for me.