Animated Plot Collection

2023/05/13

I took a break from learning Rust to make a repository of animated plots using Matplotlib.

I was initially going to use Rust for this, but ended up deciding not to - though plotters looks very cool! This is mostly because I came to the conclusion that no Rust library is mature enough to do what I want, which is to make nice-looking stuff for one-off use cases like presentations. A Rust solution would probably be faster and more maintainable, but these Python scripts are simple and easy to extend, which is a better value proposition for one-off projects.

This repository got started when I realized that, completely without my knowledge, someone upgraded Matplotlib to have a very intuitive interface for animations. I seem to remember it being awful, but when I checked on it, it was as simple as passing a function argument to plt.FuncAnimation and handling the rest yourself.

Maybe the coolest thing I found is that you can overlay graphs on videos! We can do this by noticing that Matplotlib allows you to write output to arbitrary buffers, meaning that we can get a raw RGBA pixel array. I can’t take the credit for this, I found it on StackOverflow:

io_buf = io.BytesIO()
fig.savefig(io_buf, format='raw', dpi=DPI)
io_buf.seek(0)
img_arr = np.reshape(np.frombuffer(io_buf.getvalue(), dtype=np.uint8),
                     newshape=(int(fig.bbox.bounds[3]), int(fig.bbox.bounds[2]), -1))
io_buf.close()

This gives a nice pipeline of load video frame -> do pixel-level art -> overlay graph relevant to frame -> write prettier video. Note that I am not trying to write rendering library! This is an easy way to get nice videos, not a performant way.