tomer_shoham
tomer_shoham

Reputation: 11

How to merge gganimate plots with tables (data frames) using R

I'm using gganimate, and I need to add a table (data frame) near the "moving" plot. I don't care if the table is static or not.

I can do that when plotting ggplot plots by using grid.arrange command from the gridExtra package, but I'm afraid I have no idea how to do that when using gganimate.

Upvotes: 1

Views: 625

Answers (1)

Roman
Roman

Reputation: 4989

Definitely possible with the geom_table from ggpmisc.

1

Code

g <- ggplot(gapminder, aes(gdpPercap, lifeExp, size = pop, color = continent)) + 
    geom_point() + 
    scale_x_log10() +
    annotate(geom = "table", x = Inf, y = -Inf,
             label = list(mytable), 
             vjust = 0, hjust = 1) +
    transition_time(year) +
    labs(title = "Year: {frame_time}")

animate(g)

Data

library(gapminder)
library(ggplot2)
library(gganimate)
library(ggpmisc)

# Transform to numeric to prevent an integer overflow 
gapminder$pop <- as.numeric(gapminder$pop)    

# Create table
mytable <- gapminder %>%
    filter(year == 2007) %>%
    group_by(continent = continent) %>%
    summarise(pop_mn_2007 = round(sum(pop)/1000000, 1),
              avg_lifeExp_2007 = round(mean(lifeExp), 2))

Upvotes: 2

Related Questions