Skip to content

Temperature time series

Thomas Lin Pedersen edited this page Dec 10, 2018 · 2 revisions

submitted by Thomas Lin Pedersen

Time series animation are very popular. The gist of it is often that the lines are gradually build up along the time axis to emphasise the time-dimension of the data. Detractors of this type of animation will say that the animation does not show anything that a static plot of the full dataset would not show. They often ignore the fact that emphasising the time dimension can be a goal itself and help viewers situate themselves in the plot. Further, there is no doubt that an animation is more commanding of attention, which can often be a goal in itself.

The Data

For this example we'll simply use the build-in airquality dataset. We'll make one change though and recode the Month column to contain actual month names.

airq <- airquality
airq$Month <- format(ISOdate(2004,1:12,1),"%B")[airq$Month]

The Code

We'll dive straight in and create a rather complex animation - read below for a discussion about what's going on.

ggplot(airq, aes(Day, Temp, group = Month)) + 
  geom_line() + 
  geom_segment(aes(xend = 31, yend = Temp), linetype = 2, colour = 'grey') + 
  geom_point(size = 2) + 
  geom_text(aes(x = 31.1, label = Month), hjust = 0) + 
  transition_reveal(Day) + 
  coord_cartesian(clip = 'off') + 
  labs(title = 'Temperature in New York', y = 'Temperature (°F)') + 
  theme_minimal() + 
  theme(plot.margin = margin(5.5, 40, 5.5, 5.5))

reveal

Discussion

There is a lot going on in the above ggplot2 code, but most of it is styling. Here is the gist of it:

  • We use transition_reveal() to allow the lines to gradually be build up. transition_reveal() knows to only keep old data for path and polygon type layers which means that our segment, point, and text layers only appears as single data points in each frame
  • We set clip = 'off' in the coordinate system to allow the text layer to draw outside the plotting area and we add a wider right margin to allow space for the text
  • We do not use transition_time() + shadow_mark()/shadow_trail() as combination does not allow for a connected line. Shadows exists as separate data elements and cannot be combined with the data in the current frame, meaning that it would result in a number of disconnected line segments instead of a single connected line for each temperature profile