Figure legend cropped when working with animations

I got some trouble when I work with figure legend placed outside of the boxing bounds. Here is a simple example which shows the difference of behavior when using Axes legend and Figure legend.

With Axes:

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation

fig,ax = plt.subplots()
dt = 0.01
N_frames=30
x=np.random.choice(100,size=N_frames,) #Create random trajectory
y=np.random.choice(100,size=N_frames,) #Create random trajectory
graph, = plt.plot([], [], color="gold",lw=5,markersize=3,label='Time: 0')
L=ax.legend(loc="center left", bbox_to_anchor=(0.8, 0.3)) #Define legend objects

def init():
    ax.set_xlim(0, 100)
    ax.set_ylim(0, 100)
    return graph,

def animate(i):
    lab = 'Time:'+str(round(dt+dt*i,2))
    graph.set_data(x[:i], y[:i])
    L.get_texts()[0].set_text(lab) #Update label each at frame

    return graph,

ani = animation.FuncAnimation(fig,animate,frames=np.arange(N_frames),init_func=init,interval=200)

plt.close()
fname = fig_save_path.joinpath("test1.gif")
writer = animation.FFMpegWriter(fps=5)
ani.save(fname, writer=writer)

test1

But it gets cropped with fig.legend:

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation

fig,ax = plt.subplots()
dt = 0.01
N_frames=30
x=np.random.choice(100,size=N_frames,) #Create random trajectory
y=np.random.choice(100,size=N_frames,) #Create random trajectory
graph, = plt.plot([], [], color="gold",lw=5,markersize=3,label='Time: 0')
L=fig.legend(loc="center left", bbox_to_anchor=(0.8, 0.3)) #Define legend objects

def init():
    ax.set_xlim(0, 100)
    ax.set_ylim(0, 100)
    return graph,

def animate(i):
    lab = 'Time:'+str(round(dt+dt*i,2))
    graph.set_data(x[:i], y[:i])
    L.get_texts()[0].set_text(lab) #Update label each at frame

    return graph,

ani = animation.FuncAnimation(fig,animate,frames=np.arange(N_frames),init_func=init,interval=200)

plt.close()
fname = fig_save_path.joinpath("test2.gif")
writer = animation.FFMpegWriter(fps=5)
ani.save(fname, writer=writer)

test2

How can I overcome this issue ?

I tried using: ani.save(fname, writer=writer, savefig_kwargs=dict(bbox_inches="tight")) but the kwarg is ignored…

Thanks in advance !

I don’t know that this has anything to do with animations.

Here you asked for the legend 80% of the way across the Axes.

And here you asked the legend 80% of the way across the Figure.

Naturally this will be further right.