我在R中制作传单地图,我想将特定数据分配给特定区域。现在我正在使用一个占位符来试图找出它,但我没有运气。我有一些excel文件中的某些数据,我想分配给某些县。我该怎么办呢?
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")
)
答案 0 :(得分:1)
您可以创建一个包含相关数据的单独数据框,并在绘图时参考它。您只需要小心确保数据框中的县的顺序与地理数据中的县的顺序相匹配。您已经提取的县名应该作为匹配该订单的“关键”。
从上面的代码中,将#placeholder部分更改为..
data_to_plot <- data.frame("NAME"=bothcountynames,"data"=###YOURDATA_IN_CORRECT_ORDER###))
..包含您要绘制的数据。您也可以使用名称设置单列数据框,然后执行合并/连接,因为这可能是维护所需顺序的更简单方法。
在传单调用中,放置fillColor = pal(data_to_plot$data)
。如果您引用的数据存储在单独的对象中,则基本上不需要~
。