r - 如何使用 gganimate 包在 R 中绘制动态地图?
问题描述
据我所知 gganimate 已经在 1.0.3 版本中,我们可以使用transition_*
函数来绘制动态图。但是当我运行以下代码时,出现错误:
Error in `$<-.data.frame`(`*tmp*`, "group", value = "") :
replacement has 1 row, data has 0
代码:
library(ggmap)
library(gganimate)
world <- map_data("world")
world <- world[world$region!="Antarctica",]
data <- data.frame(state = c("Alabama","Alaska","Alberta","Alberta","Arizona"),
lon = c(-86.55,-149.52,-114.05,-113.25,-112.05),
lat = c(33.30,61.13,51.05,53.34,33.30)
)
ggplot()+
geom_map(data = world,
map = world,
aes(long,lat,map_id = region),
color = '#333300',
fill = '#663300') +
geom_point(data = data,
aes(x = lon, y = lat),
size = 2.5) +
geom_jitter(width = 0.1) +
transition_states(states = state)
解决方案
您没有在顶层ggplot()
行中定义数据,因此state
intransition_*
无处不在。
我也不清楚为什么你geom_jitter
的代码中有一个级别。就像transition_*
,它没有要继承的顶级数据/美学映射,所以它也会抛出错误,transition_*
没有首先触发错误。此外,即使我们添加映射,考虑到数据中的纬度/经度坐标范围,0.1 的抖动在视觉上也几乎没有影响。
您可以尝试以下方法:
# put data in top level ggplot()
ggplot(data,
aes(x = lon, y = lat))+
geom_map(data = world,
map = world,
aes(long,lat,map_id = region),
color = '#333300', fill = '#663300',
# lighter background for better visibility
alpha = 0.5) +
geom_point(size = 2.5) +
# limit coordinates to relevant range
coord_quickmap(x = c(-180, -50), y = c(25, 85)) +
transition_states(states = state)
推荐阅读
- bash - 如何在bash中用多个字符的定义字符串拆分字符串?
- python - Django:如何更正创建的日期/时间
- c# - 如何在 axml 中使用自定义文本视图?
- android - 错误运行应用程序默认活动未找到
- javascript - pdfMake管道上的Nodejs内存不足
- c# - 如何在c#中检查两个字符串的长度是否相等?
- sql - 如何获得列之间的唯一组合?
- haskell - Haskell 空主函数
- tensorflow - 如何从对象检测中加载保存的模型以进行推理?
- python - 错误:TypeError:“str”对象在尝试选择随机获胜者时无法解释为整数(Python)