Animation not being cut in the smartest way

Viewed 24

I'm running a code that generates an animation, as well as a few separated frames:

# Comparação entre random walk e difusão em 1d
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation

M = 100 # Número de walkers
L = 100 # Tamanho da malha

# A cada intervalo de tempo, mover o walker e propagar a difusão

p = 0.1 # Probabilidade de andar
pinv = 1.0-p
nsteps = 2001 # Número de intervalos de tempo

# Iniciando os walkers

x = np.zeros(M) # Posição inicial dos walkers
edges = np.array(range(-L,L+1))-0.5
xc = 0.5*(edges[:-1]+edges[1:])
y = np.zeros(M)

#%%

def animate(it):
    global x
    x = get_data(x, M)

    # Trajetória dos walkers no eixo x
    if (np.mod(it,noutput)==0):
        plot.set_offsets(np.array((x, y)).T)
        ax.set_title('Tempo = {}'.format(it))
        
    noutput2 = 100
    if (np.mod(it,noutput2)==0):
        plot.set_offsets(np.array((x, y)).T)
        ax.set_title('Tempo = {}'.format(it))
        plt.savefig('tempo_{}.png'.format(it), dpi = 300, bbox_inches = 'tight')
    return plot
    
def get_data(x, M):
    # Atualizar a posição de todos os walkers
    for iw in range(M):
        rnd = np.random.rand(1)
        dx = -1*(rnd<p)+1*(rnd>pinv)
        x[iw] = x[iw] + dx
    return x

plt.ion()
noutput = 5
fig, ax = plt.subplots()
fig.set_size_inches(12, 2)
ax.set_xlim((-100, 100))
ax.axes.get_yaxis().set_visible(False)
ax.set_xlabel('Distância percorrida')
x = get_data(x, M)
plot = ax.scatter (x, y, s = 1)
            
ani = animation.FuncAnimation(fig = fig, func = animate, frames = nsteps, interval = 50)
ani.save('randomwalk1d.mp4')
plt.show()

Because of bbox_inches = 'tight', the frames are being saved just fine:

enter image description here

But the animation has some issues (the x axis label is being cut). Here's how it looks:

enter image description here

Is there a way to implement bbox_inches = 'tight' into the animation, or something similar? I tried plt.tight_layout() but it still cuts the x axis label. I'd like the animation to look the same as the individual frames.

1 Answers

I found out what I had to do. I had to use fig.set_tight_layout(True) for it to correctly apply the tight layout.

Related