【发布时间】:2020-02-22 09:23:26
【问题描述】:
假设我有这些数据。一个用于阴影州县,另一个用于标绘点。
library(tidyverse)
library(gganimate)
devtools::install_github("UrbanInstitute/urbnmapr")
library(urbanmapr)
#1. counties dataset for the shading of the background
data(counties)
#keep only Texas counties
counties <- filter(counties, state_fips==48)
#2. dots dataset for dots over time
dots <- data.frame(group = c(rep(1,3), rep(2,3)),
lat = c(rep(32, 3), rep(33, 3)),
long = c(rep(-100, 3), rep(-99,3)),
year = c(1:3, 1:3))
然后我绘制它们(首先不使用gganimate):
ggplot() +
geom_polygon(data = counties, aes(long, lat, group = county_fips, fill = as.numeric(county_fips))) +
scale_fill_gradient(low = "navy", high = "lightskyblue3") +
geom_point(data = dots, aes(long, lat, group=interaction(long, lat), color=year),
size=6, show.legend = FALSE) +
theme_bw() +
scale_color_gradientn(colours = c("red", "yellow", "darkgreen")) +
coord_map() +
labs(subtitle = paste('Year: {frame_time}')) +
theme(plot.subtitle = element_text(hjust = 0.8, vjust=-10, size=30)) +
theme(panel.background = element_rect(fill = 'white')) +
theme(panel.grid = element_blank(),axis.title = element_blank(),
axis.text = element_blank(),axis.ticks = element_blank(),
panel.border = element_blank())+
theme(legend.position = c(0.15, .15)) +
theme(legend.key.size = unit(2,"line"),legend.title=element_text(size=16),
legend.text=element_text(size=14)) +
labs(fill = "abc")
结果如下:
当我尝试使用 gganimate 为点设置动画时出现问题:
map <- ggplot() +
geom_polygon(data = counties, aes(long, lat, group = county_fips, fill = as.numeric(county_fips))) +
scale_fill_gradient(low = "navy", high = "lightskyblue3") +
geom_point(data = dots, aes(long, lat, group=interaction(long, lat), color=year),
size=6, show.legend = FALSE) +
theme_bw() +
scale_color_gradientn(colours = c("red", "yellow", "darkgreen")) +
coord_map() +
labs(subtitle = paste('Year: {frame_time}')) +
theme(plot.subtitle = element_text(hjust = 0.8, vjust=-10, size=30)) +
theme(panel.background = element_rect(fill = 'white')) +
theme(panel.grid = element_blank(),axis.title = element_blank(),
axis.text = element_blank(),axis.ticks = element_blank(),
panel.border = element_blank())+
theme(legend.position = c(0.15, .15)) +
theme(legend.key.size = unit(2,"line"),legend.title=element_text(size=16),
legend.text=element_text(size=14)) +
labs(fill = "abc") +
transition_time(year) +
shadow_mark(size=6)
anim_save("output/test.gif", map, end_pause=6, width = 800, height = 800, duration=8)
请注意,除了transition_time 和shadow_mark 行之外,它完全相同。结果如下:
背景颜色非常不同。可能是颜色反转或其他情况;我不知道。然而,在我使用更多点和不同值进行着色的真实示例中,着色与实际数据几乎没有相似之处。到底发生了什么,我该如何解决?
【问题讨论】:
-
counties数据集来自哪个包?也许library(noncensus)? -
counties数据集来自 Urban Institute 的urbnmapr。我很抱歉没有将其包含在代码中;我已经更新了它。我不确定noncensus是否包含相同的数据集。 -
这看起来很像一个错误。我看到你还提交了issue report。在解决之前,您可以考虑自己构建动画。最后
gganimate所做的基本上是为每一帧渲染一个图,然后使用gifsky 或其他渲染器将它们组合起来。