Animated Line Graphs
Line graphs can be very useful indicators of data. Animating them draws your viewer in and grabs their attention.
Last updated
Line graphs can be very useful indicators of data. Animating them draws your viewer in and grabs their attention.
Last updated
For all of the basic animations, we'll use the txhousing
dataset within the ggplot2
library, for simplicity. This dataset contains "information about the housing market in Texas provided by the TAMU real estate center".
In a few minutes, we'll make this graph:
To get started, let's load all the libraries we'll need:
Now that we have the libraries, we can get the dataset. So that we can easily view it, let's put it into a variable.
We want to have a single number for sales and listings for each month and year. Luckily, the dataset already comes with a date
column that specifies both the month and the year, so we can just group based on date
and sum the sales and listings for every city to get a total.
Let's look at the data now.
Now that the data is in the right format, we're ready to plot. We'll start by first generating a static line graph, with the date on the x-axis and sales/listings on the y-axis (in two separate lines).
This doesn't look too pretty, so let's add a theme, some nicer colors, and fix the labels.
We're almost there. To convert this into an animation we have to add transition_reveal(date)
to the end of our code. transition_reveal
is somewhat self-explanatory: we want to reveal more and more of the line as animation goes on. Here, date
is what is actually moving the animation. Essentially, we're telling the computer to reveal more and more of each line as the date
increases.
The animation is now in place, but the text is cut off and the resolution isn't ideal. To fix this we put our animation into an object using the assignment operation (<-
) and then call animate()
on that object, with some self-explanatory parameters.
We're animating our animation, with 10 frames per second for 15 seconds. The animation's last 9 frames will pause before it wraps back around (end_pause
). The width and height are 9 and 8 inches each and the resolution (res
) or how many pixels will be in each inch, is 200 (i.e. the final animation will be 1800x1600 pixels).
When you run the animation()
function, it should automatically pop up in the "Viewer" tab in R. From there, you can open it in a new window and save it as a GIF from there. However, if you want to easily save it to your local directory within R, simple change some syntax:
Essentially, we're giving the animation its own specifications for animating, so that it can export seamlessly. If you're having trouble exporting or saving your chart, make sure that the package "gifski" is installed.
That's it! You've now successfully made an animated line chart.