R ggplot2和ggplotly制作带有累积年度地图的点图。

3

我试图在地图上累积绘制每个月新增的位置。我已经能够创建每个月有新位置的动画,但无法进行累积。换句话说,我希望看到新位置添加到现有位置的地图上。

以下是示例数据:

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, cumulative=TRUE,
                 frame=month,stat = 'identity' ),data = DF )
map

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

输出结果不是累计的位置。基本上,我希望最终能看到所有四个位置。

你会考虑使用gganimate吗?还是只对plotly解决方案感兴趣? - Ben
嗨,Ben,如果有方法的话,我会使用gganimate。 - Wendy
1个回答

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

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


anim_save("mapanim.gif", map)

此外,如果您想要更改最终动画的宽度/高度,您可以指定,例如:

animate(map, height = 400, width = 600)

animation of cumulative points on map


非常感谢。我该如何将输出保存为gif或HTML文件? - Wendy
你可以使用 anim_save() 保存为 gif - 参见编辑后的答案示例。 - Ben

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接