r - ggplot2中带有facet_wrap的 map

标签 r plot ggplot2

我想通过ggplot2中的数据变量facet_wrap绘制 map 图-例如在以下示例中为“宠物”。这是否需要为每个变量类别完整复制强化 map 数据?那会让我有些傻。有替代方法吗?

require(ggplot2)
(nz_dat = data.frame(island = rep(c('North.Island ','South.Island '), 3),
           pets = c('cats','cats','dogs','dogs','birds','birds'),
           n = c(13, 26, 48, 74, 24, 17)))
             island  pets  n
1 North.Island   cats 13
2 South.Island   cats 26
3 North.Island   dogs 48
4 South.Island   dogs 74
5 North.Island  birds 24
6 South.Island  birds 17

nz = map_data("nz")
nz = subset(nz, nz$region %in% c('North.Island ','South.Island ')) # 2 main islands

# simple plot
ggplot(nz, aes(long, lat, group=group, fill=factor(region))) + 
  geom_polygon() + coord_quickmap()

enter image description here

最佳答案

您可以对美学进行一些调整:

library(ggthemes) # for theme_map

gg <- ggplot()

# lay down a base map (no borders or fills)
# geom_map is a great way to do map layers like you would in any GIS
gg <- gg + geom_map(data=nz, map=nz,
                    aes(x=long, y=lat, map_id=region),
                    color="#00000000", fill="#0000000", size=0.5)

# since "island" equates to the "nz" map id of "region" use that
# to "map" (in the data operation sense) the value in "n" to the
# named polygon
gg <- gg + geom_map(data=nz_dat, map=nz,
                    aes(fill=n, map_id=island, color=n))

# it's highly unlikely these values needed a continuous scale
# so use a shortcut to colorbrewer with scale_*_distiller, scaling
# both the color & fill so there are no black borders
gg <- gg + scale_fill_distiller()
gg <- gg + scale_color_distiller()

# the OP did good here since it's better than Mercator for 
# NZ and NZMG coord system is not avail with coord_map()
gg <- gg + coord_quickmap()

# ggplot will make many maps!
gg <- gg + facet_wrap(~pets)

# ggplot will make clean maps!
gg <- gg + theme_map()

# put the legend wherever you want
gg <- gg + theme(legend.position="right")
gg

enter image description here

关于r - ggplot2中带有facet_wrap的 map ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31876236/

相关文章:

r - 动态创建函数和表达式

r - ggplot2中具有时间序列的月和日的日期序列在年份中具有方面

r - 使用 ggplot 的 geom_tile() 时的边距调整

r - 使用多个图形ggplot2在R视口(viewport)中居中标题

r - 如何将多列中的字符串添加到R中单列中的多行

r - 使用正态分布计算 R 中的比例

通过 read.big.matrix 读取 R 中的大数据

python - Matplotlib:如何使用特定的十六进制颜色和特定标记进行绘图?

r - 如何使用多行文本在分组条形图的条形上添加值?

删除 ggplot2 中的负绘图区域