2017-09-23 90 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)。如果您引用的数据存储在单独的对象中,则基本上不需要~

相关问题