我对使用R相对较新,我正在尝试使用数据来创建美国各州的地图,以便勾画并为某些区域着色。我试图以黑色显示一个州及其县。最重要的是,我想在各县之间创建厚红色边框,并根据我的一些数据填充一些县。
基本上我想组合这两个图像:
Then I would like to fill the map above like this
这是我到目前为止尝试此任务的代码:
# Maping IA, plan 74406IA0010001
# Importing data
library(ggplot2)
library(ggmap)
library(maps)
library(mapdata)
library(stringr)
library(plyr)
library(dplyr)
setwd("/Users/erinmay/Desktop/WL_RA/marketplace2/data")
county <- map_data("county")
plan <- read.csv("IA_2017.csv")
# Using subset
iowa <- subset(county, region=="iowa") #county point files for iowa
# Merging in map data
countyplan <- merge(x=iowa, y=plan, by=c("region","subregion"), all.x=TRUE)
countyplan <- countyplan[order(countyplan$chosen_plan),]
# Creating map
final <- ggplot(data=countyplan) +
geom_path(aes(x=long,y=lat,group=RatingArea),colour='black') +
geom_polygon(aes(x=long,y=lat,group=group,fill=chosen_plan)) +
coord_map() + coord_fixed(1.3)
ggsave(final,height=6,width=10,unit='in',file='iowa.pdf')
先谢谢你的帮助!
以下是数据: https://www.dropbox.com/s/x8x2l50dvmg0lsb/QHP_IA_2017.csv?dl=0
答案 0 :(得分:0)
根据OP的澄清编辑回答,仅为每个评级区域的外部边框着色:
据我了解,所有多边形在ggplot方面都是相同的。因此,如果必须为多边形的轮廓着色,则无论两个相邻多边形是否属于同一评级区域,它都将对所有边进行着色。
您将在相同的计划区域中使用溶解多边形,之前将它们强化为数据框。 (注意:您可以将现有数据框转换回多边形,但可能更容易从原始数据源获取多边形数据。)
library(maps); library(dplyr); library(tidyr); library(maptools); library(rgeos)
# get map data
county_map <- map("county", fill = T, plot = FALSE)
# create mapping table between county names & rating areas
county_map_match <- data.frame(name = county_map$names) %>%
separate(name, c("region", "subregion"), sep = ",", remove = FALSE) %>%
left_join(plan %>% select(region, subregion, RatingArea))
rownames(county_map_match) <- county_map_match$name
# convert map to SpatialPolygon, then join with mapping table for SpatialPolygonDataFrame
county_map <- map2SpatialPolygons(county_map, IDs = county_map$names)
county_map <- SpatialPolygonsDataFrame(county_map, county_map_match)
# remove invalidities in the county map
gIsValid(county_map) #returns FALSE: there are invalid self-intersecting geometries in the polygons, which will cause problems
county_map <- gBuffer(county_map, byid = TRUE, width = 0)
gIsValid(county_map) #returns TRUE
# dissolve county map by rating area & fortify to data frame
area_map <- unionSpatialPolygons(county_map, IDs = county_map$RatingArea)
area_map <- fortify(area_map)
area_map$group <- gsub(".1", "", x= area_map$group, fixed = T)
获得评级区域的数据框版本后,您可以将其合并到ggplot中:
ggplot(countyplan,
aes(x=long,y=lat, group = group, fill = chosen_plan)) +
geom_polygon(size = 0.5, colour = "black") +
geom_polygon(data = area_map,
aes(x=long, y=lat, group = group, colour = group),
fill = NA, size = 2) +
scale_fill_manual(name = "Chosen Plan", values = c("darksalmon"), na.value = "grey") +
scale_color_discrete(name = "Rating Area") +
coord_map() + coord_fixed(1.3)
您可以从RColorBrewer
包中获得更好的调色板&amp;如果您愿意,可以在scale_XX_brewer()
电话中使用它们。可在此处引用各种颜色的名称:http://sape.inf.usi.ch/quick-reference/ggplot2/colour