1
library(dplyr)
library(plotly)
library(wesanderson)
library(animation)
library(ggthemes)
library(scales)
states_map <-map_data("state")
StateCodes <- c("AL","AK","CA","AL","AK","CA")
year <- c(2010,2010,2010,2011,2011,2011)
n <- c(1.1,1.2,1.3,2.1,2.2,2.3)
data <- data.frame(StateCodes,year,n)
saveGIF({
for (i in 2010:2011) {
m<-ggplot(subset(data,year==i), aes(map_id = StateCodes)) +
geom_map(aes(fill = (n)), map = states_map, color ="black") +
expand_limits(x = states_map$long, y = states_map$lat) +
theme_few()+
theme(legend.position = "bottom",
axis.ticks = element_blank(),
axis.title = element_blank(),
axis.text = element_blank()) +
scale_fill_gradient(low="white", high="blue") +
guides(fill = guide_colorbar(barwidth = 10, barheight = .5)) +
ggtitle(paste("Value in Year",i))
print(m)
}
}, interval = 1, movie.name = "value_usa.gif", ani.width = 800, ani.height = 600)
在运行上述代码中,我得到了错误Error in unit(x, default.units) : 'x' and 'units' must have length > 0
。有一些资源敦促使用as.factor(n)
,但这也不起作用。为了便于理解,我尽可能减少了上面的例子。我做了一个很好的类似项目。可以发现here关于geom_map错误: “错误在单元(X,default.units): 'x' 和 '单元' 的长度必须> 0”
''中的states_map''region'这些都充分命名的Statecodes'contains缩写。我建议保持一致。 – Haboryme
我在运行该行时出错,states_map < - map_data(“state”),错误:ggplot2不知道如何处理类列表的数据。 –
@Haboryme是的,你是对的。直到你指出来,我才意识到我的愚蠢的错误。谢谢! – adhok