首页 > 解决方案 > 如何使用 R 将 gganimate 图与表(数据框)合并

问题描述

我正在使用gganimate,我需要在“移动”图附近添加一个表格(数据框)。我不在乎桌子是否是静态的。

我可以在ggplot使用包中的grid.arrange命令绘制绘图时做到这一点gridExtra,但恐怕我不知道在使用gganimate.

标签: rggplot2gganimate

解决方案


绝对可以使用geom_tablefrom ggpmisc

1

代码

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)

数据

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))

推荐阅读