2017-09-23 83 views
1

我正在R中製作小冊子地圖,並且我想將特定數據分配給特定區域。現在我正在使用佔位符來試圖找出它,但我沒有運氣。我從某個Excel文件中獲得了某些我想要分配給某些縣的數據。我會怎麼做呢?如何將特定數據分配給R小冊子中的特定區域

library(maptools) 
library(leaflet) 
library(rjson) 
library(magrittr) 
library(sf) 
library(xlsx) 



## reads in the JSON data of all counties in USA 
counties <- sf::read_sf("http://eric.clst.org/wupl/Stuff/gz_2010_us_050_00_500k.json") 

## selects kansas and missouri county lines 
kscounties<-counties[counties$STATE=="20",] 
mocounties<-counties[counties$STATE=="29",] 


## variable containing all kansas and missouricounty names 
kscountynames<-kscounties$NAME 
mocountynames<-mocounties$NAME 


## combines both counties 
bothcounties<-rbind(kscounties,mocounties) 
bothcountynames<-c(kscountynames,mocountynames) 




## color pallette 
pal<-colorNumeric("viridis",NULL) 

## placeholder 
percent=c(1:100) 


## creates leaflet of kansas and missouri counties 
leaflet(bothcounties) %>% 
    addTiles() %>% 
    addPolygons(stroke = FALSE, smoothFactor = 0.3, fillOpacity = 1, 
    fillColor = ~pal(percent), 
    label = ~paste(bothcountynames, "\n", formatC(percent, big.mark = ",") 
        )) %>% 

     setView(-98.4,38.5,zoom=6) %>% 
     addLegend(position="bottomright",pal = pal, values = percent, opacity = 1.0,title="Percent") %>% 
    addLayersControl(position="topleft", 
        baseGroups = c("1","2"), 
       overlayGroups=c("A","B","C","D","E","F") 

回答

1

你只需創建一個包含有問題的數據的單獨數據幀和打印時參考。您必須小心確保數據框中縣的順序與地理數據中縣的順序相匹配。您已經提取的縣名應該作爲匹配該順序的「關鍵」。

從上面的代碼,..with要繪製的數據#placeholder部分改爲..

data_to_plot <- data.frame("NAME"=bothcountynames,"data"=###YOURDATA_IN_CORRECT_ORDER###)) 

。您也可以只設置一個帶有名稱的單列數據框,然後進行合併/合併,因爲這可能是維護所需順序的更簡單方法。

在傳單電話中,放fillColor = pal(data_to_plot$data)。如果您引用的數據存儲在單獨的對象中,則基本上不需要~

相關問題