2016-11-25 395 views
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」

+0

''中的states_map''region'這些都充分命名的Statecodes'contains縮寫。我建議保持一致。 – Haboryme

+0

我在運行該行時出錯,states_map < - map_data(「state」),錯誤:ggplot2不知道如何處理類列表的數據。 –

+0

@Haboryme是的,你是對的。直到你指出來,我才意識到我的愚蠢的錯誤。謝謝! – adhok

回答

0

更改大小寫兩行:

Statecodes <- c("AL","AK","CA","AL","AK","CA") 

... 

m<-ggplot(subset(data,year==i), aes(map_id = Statecodes)) + 
相關問題