2016-04-22 85 views
1

我想製作紐約市犯罪發生的多個地塊(以r爲單位)。我想爲每個分區製作地塊,即78個。我的數據記錄了7種不同類型的犯罪,我想用不同的顏色識別每種類型的犯罪。因此,對於每個情節(代表區),我會針對不同的犯罪有不同的顏色。我想在谷歌地球的衛星地圖上繪製數據。下面是代碼,當我試圖使該地塊我收到錯誤消息:ggplot2中的多個地塊

library(ggmap) 
library(ggplot2) 

FELONY <- read.csv("http://www.nyc.gov/html/nypd/downloads/excel/crime_statistics/Felony.csv") 
felony <- FELONY[FELONY$OccurrenceYear==2015,] 
attach(felony) 
Sepfel <- felony[felony$OccurrenceMonth== "Sep",] 

for(i in unique(Sepfel$Precinct)){ 
    map <- get_map(location='New York City', zoom=11, maptype="satellite") 
    ggmap(map) + 
    geom_point(subset(Sepfel,Sepfel$Precint==i), 
       aes(color=Offense, x=Longitude, y=Latitude),size=0.00001, alpha=1) + 
    ggtitle(paste("September 2015")) 
    } 

Error: ggplot2 doesn't know how to deal with data of class uneval 

回答

0

我選擇了兩個Precinct此演示。你想用ggplot對象創建一個列表,繪製並保存地圖。有關保存地圖的選項,請參閱代碼部分中的鏈接。 baptiste的答案將幫助您選擇保存圖像的最佳方式。我希望這能幫到您。

foo <- subset(felony, Precinct %in% c("040", "045")) 

mymap <- get_map(location = "New York City", zoom = 11, maptype = "satellite") 

mylist <- lapply(unique(foo$Precinct), function(x){ 

      g <- ggmap(mymap) + 
       geom_point(data = subset(foo, Precinct == x), 
          aes(color = Offense, x = Longitude, y = Latitude), 
          size = 0.5, alpha = 0.5) 
       labs(title = "September 2015") 

      g 
     } 
     ) 

### Credit to baptiste for this answer. 
### http://stackoverflow.com/questions/20500706/saving-multiple-ggplots-from-ls-into-one-and-seperate-files-in-r 

invisible(mapply(ggsave, file=paste0("Precinct-", unique(foo$Precinct), ".png"), plot = mylist)) 

enter image description here enter image description here

+0

嘿Jazzurro,非常感謝!有效。我非常非常感謝! – Stone

+0

@Stone我很高興聽到這個消息。你會考慮接受答案嗎? – jazzurro