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