单独进行动画处理geom_text和geom_point

时间:2020-09-05 20:21:20

标签: r ggplot2 gganimate

我有一个PC空间上的国家/地区数据集。我想在此空间上绘制所有点(请参见下图)。

ggplot(ind_countries,
       aes(PC1, PC2)) +
  geom_point()

enter image description here

我只想在动画中显示国家/地区的名称,然后在点上放置该名称而消失。我已经尝试过gganimate,但无法完全获得所需的视觉效果。

ggplot(ind_countries %>% slice(1:10),
       aes(PC1, PC2)) +
  shadow_mark() +
  geom_point()+
  geom_text(aes(label=Area)) +
  transition_states(Area)

enter image description here

但是我不想在国家名称之间进行内插,国家名称应该是固定的。更重要的是,当使用全部〜200个标签时,此视觉效果将变得非常混乱。就像我完成ggplot(...) + geom_text()一样。

或者,我希望所有点都像静态图片一样,并通过国名进行动画处理以突出显示它们(使用颜色和名称或等效名称)。

数据

structure(list(Area = c("Afghanistan", "Albania", "Algeria", 
"Angola", "Antigua and Barbuda", "Argentina", "Armenia", "Australia", 
"Austria", "Azerbaijan"), PC1 = c(`1` = -533.00304848187, `2` = -733.478134192073, 
`3` = -862.469905878461, `4` = 210.741387772907, `5` = -75.9683314876284, 
`6` = -432.40416113792, `7` = -739.448970021204, `8` = -153.020907842885, 
`9` = -266.078280799454, `10` = -856.759952967809), PC2 = c(`1` = 242.086883796857, 
`2` = 204.143228785502, `3` = 179.014761012001, `4` = -453.158827266088, 
`5` = -76.6617307886724, `6` = 31.1628432885813, `7` = 206.38294390879, 
`8` = -58.8035296785091, `9` = -100.898331142746, `10` = 240.75679171712
), PC3 = c(`1` = 65.4343509859609, `2` = 83.3998919734866, `3` = 216.37491156154, 
`4` = -104.167202758037, `5` = -203.978295596104, `6` = -12.4117893989394, 
`7` = 37.4440357817306, `8` = -174.038394855287, `9` = -64.9420372105368, 
`10` = 133.284279359949)), row.names = c(NA, -10L), class = c("tbl_df", 
"tbl", "data.frame"))

1 个答案:

答案 0 :(得分:1)

以下是您替代要求的一种可能方法:

animation

ind_countries %>%
  ggplot(aes(PC1, PC2)) +
  
  # static layer with all the points constantly visible
  geom_point(data = . %>% select(-Area))+ 
  
  # animated layer, each red point appears in turn (can add other
  # changes for emphasis as well)
  geom_point(aes(group = Area), 
             colour = "red") + 
  
  # animated layer, each label appears in turn slightly above point (given the
  # number of points in the full dataset, geom_label will be easier to read
  # than geom_text
  geom_label(aes(group = Area, label=Area, y = PC2 + 25)) + 
  
  transition_states(Area)

第一个请求(不同动画层的不同退出与持久行为)可能可以通过某种方式完成,但我认为这不是那么简单。