世界地图 - 使用ggplot2将国家的一半映射到不同的颜色

Xu *_*ang 8 plot r ggplot2

我正在为这个问题寻找一个ggplot2解决方案:

世界地图 - 将国家的一半映射到不同的颜色

我从下面的问题重现了这个例子,这是基于这里的问题(ggplot map with l).

library(rgdal)
library(ggplot2)
library(maptools)

# Data from http://thematicmapping.org/downloads/world_borders.php.
# Direct link: http://thematicmapping.org/downloads/TM_WORLD_BORDERS_SIMPL-0.3.zip
# Unpack and put the files in a dir 'data'

gpclibPermit()
world.map <- readOGR(dsn="data", layer="TM_WORLD_BORDERS_SIMPL-0.3")
world.ggmap <- fortify(world.map, region = "NAME")

n <- length(unique(world.ggmap$id))
df <- data.frame(id = unique(world.ggmap$id),
                 growth = 4*runif(n),
                 category = factor(sample(1:5, n, replace=T)))

## noise
df[c(sample(1:100,40)),c("growth", "category")] <- NA


ggplot(df, aes(map_id = id)) +
     geom_map(aes(fill = growth, color = category), map =world.ggmap) +
     expand_limits(x = world.ggmap$long, y = world.ggmap$lat) +
     scale_fill_gradient(low = "red", high = "blue", guide = "colorbar")
Run Code Online (Sandbox Code Playgroud)

hrb*_*str 10

你有几个选择.绘制多边形非常简单,但不能有两个不同的fill尺度.此解决方案使用点形注释,但可以更改为geom_point按颜色(或颜色和形状)进行缩放.我认为这是你能做的最好的事情,可以在一个单独的程序中手动覆盖两张地图.

你也可能(可能)想要调整美国边界框,因为中心有点偏离(实际上,其中一些是真的很明显).

我也删除了南极洲.如果你愿意,你可以添加它,但它浪费了房地产IMO.

library(rgdal)
library(ggplot2)
library(maptools)
library(rgeos)
library(RColorBrewer)

world.map <- readOGR(dsn="/Users/bob/Desktop/TM_WORLD_BORDERS_SIMPL-0.3/", layer="TM_WORLD_BORDERS_SIMPL-0.3")

# Get centroids of countries
theCents <- coordinates(world.map)

# extract the polygons objects
pl <- slot(world.map, "polygons")

# Create square polygons that cover the east (left) half of each country's bbox
lpolys <- lapply(seq_along(pl), function(x) {
  lbox <- bbox(pl[[x]])
  lbox[1, 2] <- theCents[x, 1]
  Polygon(expand.grid(lbox[1,], lbox[2,])[c(1,3,4,2,1),])
})

# Slightly different data handling
wmRN <- row.names(world.map)

n <- nrow(world.map@data)
world.map@data[, c("growth", "category")] <- list(growth = 4*runif(n),
                                                  category = factor(sample(1:5, n, replace=TRUE)))

# Determine the intersection of each country with the respective "left polygon"
lPolys <- lapply(seq_along(lpolys), function(x) {
  curLPol <- SpatialPolygons(list(Polygons(lpolys[x], wmRN[x])),
                             proj4string=CRS(proj4string(world.map)))
  curPl <- SpatialPolygons(pl[x], proj4string=CRS(proj4string(world.map)))
  theInt <- gIntersection(curLPol, curPl, id = wmRN[x])
  theInt
})

# Create a SpatialPolygonDataFrame of the intersections
lSPDF <- SpatialPolygonsDataFrame(SpatialPolygons(unlist(lapply(lPolys,
                                                                slot, "polygons")), proj4string = CRS(proj4string(world.map))),
                                  world.map@data)

whole <- world.map[grep("Antarctica", world.map$NAME, invert=TRUE),]
half <- lSPDF[grep("Antarctica", lSPDF$NAME, invert=TRUE),]

whole <- fortify(whole, region="ISO3")
half <- fortify(half, region="ISO3")

world.map$scaled_growth <- as.numeric(scale(world.map@data$growth, 
                                            center = min(world.map@data$growth), 
                                            scale = max(world.map@data$growth)))

growth <- world.map@data[,c("ISO3", "scaled_growth")]
colnames(growth) <- c("id", "scaled_growth")
growth$scaled_growth <- factor(as.numeric(cut(growth$scaled_growth, 8))) # make it discrete

half_centers <- data.frame(cbind(coordinates(gCentroid(lSPDF, byid = TRUE)),
                                 id=world.map@data$ISO3, category=world.map@data$category))
half_centers$category <- factor(half_centers$category)

gg <- ggplot()
gg <- gg + geom_map(data=whole, map=whole, aes(x=long, y=lat, map_id=id), alpha=0, color="black", size=0.15)
gg <- gg + geom_map(data=growth, map=whole, aes(fill=scaled_growth, map_id=id))
gg <- gg + geom_map(data=half, map=half, aes(x=long, y=lat, map_id=id), fill="white")
gg <- gg + geom_point(data=half_centers, aes(x=x, y=y, shape=category), size=2)
gg <- gg + scale_fill_brewer(palette="Pastel2")
gg <- gg + scale_shape_discrete()
gg <- gg + coord_equal()
gg
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述


arv*_*000 6

我认为你可以(有效地)得到两个不同的填充比例,只需要一点scale_fill_brewer和scale_fill_manual.

这是我的输出: 在此输入图像描述

我使用你在问题中发布的另一个帖子的第一段代码:

library(rgdal)
library(ggplot2)
library(maptools)

world.map <- readOGR(dsn="data", layer="TM_WORLD_BORDERS_SIMPL-0.3")

# Get centroids of countries
theCents <- coordinates(world.map)

# extract the polygons objects
pl <- slot(world.map, "polygons")

# Create square polygons that cover the east (left) half of each country's bbox
lpolys <- lapply(seq_along(pl), function(x) {
  lbox <- bbox(pl[[x]])
  lbox[1, 2] <- theCents[x, 1]
  Polygon(expand.grid(lbox[1,], lbox[2,])[c(1,3,4,2,1),])
})

# Slightly different data handling
wmRN <- row.names(world.map)

n <- nrow(world.map@data)
world.map@data[, c("growth", "category")] <- list(growth = 4*runif(n),
                                                  category = factor(sample(1:5, n, replace=TRUE)))

# Determine the intersection of each country with the respective "left polygon"
lPolys <- lapply(seq_along(lpolys), function(x) {
  curLPol <- SpatialPolygons(list(Polygons(lpolys[x], wmRN[x])),
                             proj4string=CRS(proj4string(world.map)))
  curPl <- SpatialPolygons(pl[x], proj4string=CRS(proj4string(world.map)))
  theInt <- gIntersection(curLPol, curPl, id = wmRN[x])
  theInt
})

# Create a SpatialPolygonDataFrame of the intersections
lSPDF <- SpatialPolygonsDataFrame(SpatialPolygons(
  unlist(lapply(lPolys,slot, "polygons")), 
  proj4string = CRS(proj4string(world.map))),
  world.map@data)
Run Code Online (Sandbox Code Playgroud)

现在我的贡献(从用户hrbrmstr借用整个/一半的名字!)

# get two data.frames, one with whole countries and the other with the left half
# this relies on code from SO user BenBarnes
whole <- fortify(world.map, region="ISO3")
half <- fortify(lSPDF, region="ISO3")

# random growth / category data, similar to the random data originally
# suggested by Xu Wang
set.seed(123)
df <- data.frame(id = unique(world.map@data$ISO3),
                 growth = 4*runif(n),
                 category = factor(sample(letters[1:5], n, replace=T)))

# make growth a factor; 5 levels for convenience
df$growth_fac <- cut(df$growth, 5)

# append growth and category factor levels together
growth_cat_levels <- c(levels(df$category), levels(df$growth_fac))

# adjust factors with new joint levels
df$growth_fac <- 
  factor(df$growth_fac, levels=growth_cat_levels)
df$category <-
  factor(df$category, levels=growth_cat_levels)

# create a palette with some sequential colors and some qualitative colors
pal <- c(scale_fill_brewer(type='seq', palette=6)$palette(5),
         scale_fill_brewer(type='qual', palette='Pastel2')$palette(5))


# merge data
whole <- data.frame(merge(whole, df, by='id'))
half <- data.frame(merge(half, df, by='id'))

# plot
ggplot() +
  geom_polygon(data=whole, 
               aes(x=long, y=lat, group=group, fill=growth_fac), 
               color='black', size=0.15) +
  geom_polygon(data=half,
               aes(x=long, y=lat, group=group, fill=category), 
               color=NA) +
  scale_shape_discrete() +
  coord_equal() +

  scale_fill_manual('Category, Growth', 
                    values=pal, breaks=growth_cat_levels) +
  guides(fill=guide_legend(ncol=2))
Run Code Online (Sandbox Code Playgroud)

一些说明:

  • 我仍然认为这是一张难以阅读的地图,但却是一个有趣的挑战
  • 我将'类别'名称从数字更改为alpha,以帮助避免与'增长'数据混淆.
  • 我还保留了由cut生成的"增长"数据标签,以帮助明确这是分类连续数据.
  • 起初,我在传说的左侧有增长颜色,但我换了它; 由于Category确定了左侧国家多边形的填充颜色,我认为Category应该出现在图例的左侧
  • 我尝试了几种不同的调色板选项.一个危险是定性尺度的颜色与连续尺度的范围太相似(就像我在此编辑之前的帖子一样).一侧灰度和一侧颜色有助于避免这种情况