You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在R中为绘制的南美国家地图设置Bluges色系?

问题描述

我已通过maps、ggplot2和dplyr包绘制了包含巴西、阿根廷等10个南美国家的地图,代码如下:

library(maps)
library(ggplot2)
library(dplyr)

p=c("Brazil", "Argentina", "Chile", "Uruguay", "Paraguay", "Ecuador", "Peru", "Venezuela",
         "Colombia", "Bolivia")

mp<-map_data("world", region=p) 

mlola <- mp %>%  group_by(region) %>% 
  summarize(mlo= mean(long), mla=mean(lat))


ggplot(mapa_paises,aes( x= long, y = lat, group=group, fill=region)) +
  geom_polygon( )+
  theme(panel.background = element_rect(fill=NA))

现在我希望使用Blues蓝色系渲染该地图,尝试引入RColorBrewer包并设置geom_polygon的color参数为"Blues",但未产生预期效果,查阅geom_polygon帮助文档后仍未找到解决方法,请问该如何正确设置?

解决方案

你存在两个核心问题:一是混淆了color(多边形边框颜色)和fill(多边形填充色)的作用;二是没有通过正确的函数调用RColorBrewer的配色方案,同时代码里还有一处变量名错误。以下是修正步骤:

  1. 加载RColorBrewer包
    首次使用需先安装,之后加载:

    install.packages("RColorBrewer")
    library(RColorBrewer)
    
  2. 修正变量名错误
    代码中ggplot(mapa_paises,...)的mapa_paises是未定义变量,应改为存储地图数据的mp。

  3. 正确应用Blues蓝色系填充
    使用scale_fill_brewer()函数指定配色方案,这是ggplot调用RColorBrewer色系的标准方式。geom_polygon的color参数用来设置国家边框颜色,可添加白色边框让国家边界更清晰。修正后的完整代码:

    library(maps)
    library(ggplot2)
    library(dplyr)
    library(RColorBrewer)
    
    p=c("Brazil", "Argentina", "Chile", "Uruguay", "Paraguay", "Ecuador", "Peru", "Venezuela",
             "Colombia", "Bolivia")
    
    mp<-map_data("world", region=p) 
    
    mlola <- mp %>%  group_by(region) %>% 
      summarize(mlo= mean(long), mla=mean(lat))
    
    ggplot(mp,aes( x= long, y = lat, group=group, fill=region)) +
      geom_polygon(color = "white") +
      scale_fill_brewer(palette = "Blues") +
      theme(panel.background = element_rect(fill=NA))
    
  4. 可选:手动定制蓝色系
    如果需要更精准的颜色控制,可以用brewer.pal()生成对应数量的颜色向量,再通过scale_fill_manual()设置:

    # 生成10种Blues色系颜色(匹配10个国家)
    blues_palette <- brewer.pal(10, "Blues")
    ggplot(mp,aes( x= long, y = lat, group=group, fill=region)) +
      geom_polygon(color = "white") +
      scale_fill_manual(values = blues_palette) +
      theme(panel.background = element_rect(fill=NA))
    

内容的提问来源于stack exchange,提问作者slow_learner

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 00:20:24