使用 R ggplot2 和 ggplotly 在地图上一年的累积点

Wen*_*ndy 3 r ggplot2 ggplotly

我正在尝试在地图上累计绘制每个月打开的新位置。我可以每月创建一个包含新位置的动画,但不能累积。换句话说,我希望看到新地点添加到现有地点。

这是示例数据

DF <- data.frame("latitude" = c(42.29813,41.83280,41.83280,30.24354),
                 "longitude" =c(-71.23154,-72.72642,-72.72642,-81.62098),
                 "month" = c(1,2,3,4))
Run Code Online (Sandbox Code Playgroud)

这是我尝试过的

usa <- ggplot() +
  borders("usa", colour = "gray85", fill = "gray80") +
  theme_map() 

map <- usa +
   geom_point(aes(x = longitude, y = latitude, cumulative=TRUE,
                 frame=month,stat = 'identity' ),data = DF )
map

# Generate the Visual and a HTML output
ggp <- ggplotly(map)%>%
  animation_opts(transition = 0)
ggp
Run Code Online (Sandbox Code Playgroud)

输出不累计显示位置。基本上我想最后看到所有四个地点。

Ben*_*Ben 5

如果您使用,gganimate您可以包括transition_states动画您的点。对于点的累积添加,请使用shadow_mark包含当前帧后面的数据。

library(ggthemes)
library(gganimate)
library(ggplot2)

DF <- data.frame("latitude" = c(42.29813,41.83280,41.83280,30.24354),
                 "longitude" =c(-71.23154,-72.72642,-72.72642,-81.62098),
                 "month" = c(1,2,3,4))

usa <- ggplot() +
  borders("usa", colour = "gray85", fill = "gray80") +
  theme_map() 

map <- usa +
  geom_point(aes(x = longitude, y = latitude), color = "black", data = DF) +
  transition_states(month, transition_length = 0, state_length = 1) + 
  shadow_mark()

map
Run Code Online (Sandbox Code Playgroud)

编辑:要将动画另存为 .gif,请使用anim_save.

anim_save("mapanim.gif", map)
Run Code Online (Sandbox Code Playgroud)

另外,如果你想改变最终动画的宽度/高度,你可以指定,例如:

animate(map, height = 400, width = 600)
Run Code Online (Sandbox Code Playgroud)

地图上累积点的动画