Cumulative points over year on map with R ggplot2 and ggplotly

萝らか妹 提交于 2020-06-27 17:47:05

问题


I am trying to plot new locations opened over each month on a map cumulatively. I am able to create an animation with new locations each month, but not cumulatively. In other words, I want to see the new locations add to the existing ones.

Here is the sample data

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

This is what I have tried

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

The output does not show locations cumulatively. I want to see all four locations in the end basically.


回答1:


If you use gganimate you can include transition_states to animate your points. For cumulative addition of points, use shadow_mark to include data behind the current frame.

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

Edit: To save the animation as a .gif, use anim_save.

anim_save("mapanim.gif", map)

In addition, if you want to change the width/height of the final animation, you can specify, for example:

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



来源:https://stackoverflow.com/questions/57734180/cumulative-points-over-year-on-map-with-r-ggplot2-and-ggplotly

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!