使用ggplot向世界地图中的特定国家/地区添加颜色

时间:2020-04-05 08:18:32

标签: r ggplot2

我正在尝试使用ggplot生成一张世界地图,其中美国,加拿大和巴西为红色。

这是我尝试过的

thismap = map_data("world")

ggplot(thismap, aes(long, lat, group=group))+geom_polygon(fill="white", colour="gray")+
  ggtitle("Map of World")

但是,我无法获得那些红色的国家

1 个答案:

答案 0 :(得分:1)

尝试一下。我在设置颜色的df中添加一列。在ggplot内部,将此列映射到fill aestehtic(!!)上。要获得正确的颜色,请使用scale_fill_identity

library(ggplot2)
library(dplyr)

thismap = map_data("world")

# Set colors
thismap <- mutate(thismap, fill = ifelse(region %in% c("Brazil", "Canada", "USA"), "red", "white"))

# Use scale_fiil_identity to set correct colors
ggplot(thismap, aes(long, lat, fill = fill, group=group)) + 
  geom_polygon(colour="gray") + ggtitle("Map of World") + 
  scale_fill_identity()

reprex package(v0.3.0)于2020-04-05创建