How to add padding to title in `matplotlib.animation`?

Viewed 105

I created an animation using python matplotlib.animation library and I'm quite happy with it. The output is enter image description here

The only part I'm unhappy with is the title. As you can see it "jiggles" around. The update function in the animation looks like this

def update_curves(num):
    # do stuff with data to get lines
    title.set_text('September 5th, 1994 at 00:00h\n + {}y {}d'.format(int(time[num]/365),int(time[num]%365)))
    return title, lines

Is there a way to stop the y and d from moving around?

I tried searching SO for info on how padding might work but I haven't really seen something that is compatible with matplotlib.animation. Using tabs also doesn't work since they don't get displayed properly...

1 Answers

You can do this using good old string formatting:

title.set_text('September 5th, 1994 at 00:00h\n + {:3}y {:5}d'.format(int(i), int(i*20)))
title.set_family("monospace")

{:3} formats the string so that it is exactly 3 characters long, and is left padded with spaces.

If you use the normal serif/sans-serif font, you will still have some jitter since each digit/letter is not equal in width, but set the font family to monospace and it works correctly.

Related