Gif You See Things May Not Be So Easy for You After All

Photo by Jakob Owens on Unsplash

A Simple Way to Turn Your Plots into GIFs in Python

Impress your audience with animated plots

Over time, I have seen quite a big share of nicely animated plots showing, for example, how sales of different products changed over time, how the market share of a given company evolved, the number of infections, etc. Recently, I thought that there must be a simple way to create such animations in Python. After a quick research, I found just the right library for the job. In this short article, I will show you how to easily convert your plots into animated GIFs in a few lines of code.

Setup

As always, we start by importing the libraries. For creating the GIFs we will be using — cue the drum roll —the gif library. After all the imports, we also increase the DPI (dots per inch) to 300, so that our animations will be in higher resolution.

Plot #1: a simple line plot

I was thinking about which kinds of plots to use for the demonstration and I decided to go with line plots, as they show how some values change over time. This makes them perfect candidates for an animation. And to be a bit more precise about the underlying data, we will be looking at stock prices.

We start by downloading Tesla's stock prices from the years 2019–2021.

We have downloaded daily data, which results in a DataFrame with > 1000 rows. For our use case, this might be an overkill. That is why we resample the data to monthly frequency by taking each month's last value.

          tsla_df = df[["Adj Close"]].resample("M").last()        

Then, we define a helper function to display each frame of the animation separately.

There are a few things worth mentioning here:

  • we create the function to display how the plot looks like at each frame of the animation. In our case, each frame corresponds to the plot showing data up until a particular date. We will combine those frames into an animation later on.
  • while defining the function, we used the @gif.frame decorator (required step).
  • we used the following snippet df.iloc[i:] = np.nan to mask all the data after the current frame. This is a simple trick to display the entire x-axis from start, so we do not observe a constantly expanding axis. In my opinion, it is simply easier on the eyes.
  • when plotting with matplotlib, the function should not return anything (that is different when we are using plotly or altair).

Then, we use a for loop to get all the frames of the animation and append them to a list.

Lastly, we put all the frames together and save the GIF. We do so using the save function. We provide the list of frames, the intended name of the GIF, its duration, and the unit of time in which it is expressed. Lastly, we should also specify the between argument. It decides whether the duration argument describes the time between frames ("frames") or the duration of the entire animation ("startend"). We go for the latter.

Below, we can observe the output of our work.

Animation by author

On a side note, that is quite an impressive growth 📈!

Plot #2: multiple time series

Speaking of growth, let's take it a step further. This time, we download the stock prices of five tech companies (arbitrarily chosen: Tesla, Twitter, Facebook, Amazon, Apple) from the same time frame. Similarly to the previous example, we also resample the data to a monthly frequency. Then, we calculate how the prices changed in each month relative to the anchor period (first row), which is December 2018.

You can see the preview of the DataFrame below:

Once again, we define a helper function used for plotting the frames. The logic is pretty much the same as last time. The biggest change comes at the end of the function, where we move the legend outside of the plot. Otherwise, it can jump around the plot between the frames, depending on the current position of the lines. This way, we make its location fixed outside of the plotting area.

Note: The code for manipulating the legend was adapted from this StackOverflow answer, where you can also find out how to place it in other parts of the plot. This can definitely come in handy when working with matplotlib!

We do not show the rest of the process (storing the frames and saving the GIF), as nothing changed there as compared to the first animation.

Finally, we can have a look at the result.

Animation by author

At this point, it is worth mentioning that the gif library is by no means restricted to creating GIFs from line plots. We can work with any plots we want. Probably the only thing we need to keep in mind is that the animation should emphasize the story we are trying to convey, instead of just creating an animation for the animation's sake.

Takeaways

  • gif is a handy library that can transform your regular plots into dynamic, easily sharable animations,
  • the library works well with matplotlib, plotly, altair,
  • we can create animations based on various types of charts.

Personally, I think that I would still prefer to have a static plot (or interactive one as in plotly), rather than the animation. Because then we can really dive deeper into the analysis and try to identify patterns. However, such animated plots are definitely nice to "show off" in special cases — it all depends on the purpose.

You can find the code used for this article on my GitHub. Also, any constructive feedback is welcome. You can reach out to me on Twitter or in the comments.

Liked the article? Become a Medium member to continue learning by reading without limits. If you use this link to become a member, you will support me at no extra cost to you. Thanks in advance and see you around!

You might also be interested in one of the following:

References

  • https://github.com/maxhumber/gif

pirkleadame1937.blogspot.com

Source: https://towardsdatascience.com/a-simple-way-to-turn-your-plots-into-gifs-in-python-f6ea4435ed3c

0 Response to "Gif You See Things May Not Be So Easy for You After All"

إرسال تعليق

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel