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

R语言基础plot绘图默认图例超出边距的解决求助

解决R中sf对象绘图图例显示不全的问题

问题背景

现有包含非洲国家空间几何与语言信息的sf数据框:

# 数据结构示例
name                     n                                                                              geometry langs
   <chr>                <int>                                                                        <GEOMETRY [°]> <chr>
 1 Algeria                  1 POLYGON ((11.56067 24.09791, 10.77136 24.56253, 10.30385 24.37931, 9.948261 24.93695… Algerian Arabic/Darja
 2 Angola                   1 MULTIPOLYGON (((13.3756 -5.864241, 13.02487 -5.984389, 12.73517 -5.965682, 12.32243 … NA   
 ...
 17 Ethiopia                 1 POLYGON ((37.59377 14.2131, 36.42951 14.42211, 36.27022 13.56333, 35.86363 12.57828,… Amharic-Oromo-Tigrinya
 20 Ghana                    1 POLYGON ((0.8369312 6.279979, 0.5703841 6.914359, 0.4909575 7.411744, 0.7120292 8.31… Hausa-Nigerian Pidgin-Twi

使用基础plot()绘制地图时,默认图例无法完整显示:

par(mfrow = c(1,2), mar = c(2,2,4,1),font = 7,font.axis = 7, 
    fg = "azure4",  col.axis = "azure4", cex.axis = .75)
plot(african_langs[3:4])

尝试过调整窗口大小和手动添加legend()均无效,需找到正确显示图例的方法。

解决方法

1. 调整sf绘图的专属图例参数

sf包的plot()函数(实际调用plot.sf)自带图例控制参数,可直接调整图例尺寸和预留空间:

par(mfrow = c(1,2), mar = c(2,2,4,5), # 增大右侧边距给图例留空间
    font = 7,font.axis = 7, 
    fg = "azure4",  col.axis = "azure4", cex.axis = .75)
# 用key.width/key.height控制图例尺寸,legend.position指定位置
plot(african_langs[3:4], 
     key.width = lcm(2), # 图例宽度设为2厘米
     key.height = lcm(1), # 图例高度设为1厘米
     legend.position = "right",
     cex.main = 0.8) # 可选:缩小标题字号节省空间

2. 设置合理的绘图窗口尺寸

之前用dev.new()的像素单位数值过小,建议改用英寸/厘米作为单位创建足够大的窗口:

# 创建宽10英寸、高6英寸的绘图窗口
dev.new(width = 10, height = 6, unit = "in")
par(mfrow = c(1,2), mar = c(2,2,4,5),
    font = 7,font.axis = 7, 
    fg = "azure4",  col.axis = "azure4", cex.axis = .75)
plot(african_langs[3:4], key.width = lcm(2.5))

3. 拆分地图与图例的绘制流程

如果默认图例仍拥挤,可手动绘制地图后单独添加自定义图例:

dev.new(width = 10, height = 6)
par(mfrow = c(1,2), mar = c(2,2,4,5))
# 先绘制地图,关闭默认图例
plot(african_langs$geometry, 
     col = as.factor(african_langs$langs), 
     main = "非洲语言分布", 
     border = "white")
# 手动添加图例到右侧空白区
lang_levels <- na.omit(unique(african_langs$langs))
legend("right", 
       legend = lang_levels,
       fill = palette()[1:length(lang_levels)],
       cex = 0.7, # 缩小图例文字
       bty = "n") # 去掉图例边框

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 21:27:09