首页 > 解决方案 > ggplot2 - 映射多边形 aes 填充 ggplot() 与 geom()

问题描述

我正在使用基本 R 数据集以及 ggplot2 和 mapproj 包在世界地图上练习 ggplot2 图形语法。在构建通过随机变量(在以下示例中称为“CountryColour”)为国家着色的地图时:

world_map <- map_data("world")
country_colours <- data.frame(region = c(names(table(world_map$region))),
      colour= sample(c(1:20), length(names(table(world_map$region))), replace = TRUE))
world_map <- merge(world_map, country_colours)
world_map <- world_map[order(world_map$region, world_map$order),]

我碰巧在 ggplot 组件中包含了 aes(fill) 参数:

ggplot(world_map[abs(world_map$long) < 180,], aes(x=long, y=lat, group=group, fill=colour)) + 
    geom_polygon(color="black") +
    coord_map(projection = "mercator")

输出图 1

现在,如果我将它包含在 ggplot() 组件本身中,我会得到完全相同的输出:

ggplot(world_map[abs(world_map$long) < 180,], aes(x=long, y=lat, group=group)) +
    geom_polygon(aes(fill=colour), color="black") +
    coord_map(projection = "mercator")

输出图 2

我想了解将填充功能放置在一个地方或另一个地方之间的概念差异。

标签: rggplot2

解决方案


推荐阅读