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

如何移除ggplot混合图例中栅格填充标签内的线条?

解决栅格列图例出现黑线的问题

问题根源是ggplot默认会给填充型图例(fill)的图例项添加边框,当你添加颜色型(color)的线图层后,边框颜色被自动继承为color参数的设置,从而出现黑线。以下两种方法可解决:

方法一:单独修改填充图例的边框

在scale_fill_manual()中添加guide参数,强制将图例项的边框设为透明:

colors_6 =
  c("darkolivegreen1", # Crop
    "#FDE333", # Open Canopy
    "#CCAA50", # Barren/fallow
    "cadetblue1", # Water
    "#A4A4A4", # Developed
    "#0A6B22") # Closed Canopy

ggplot(my_raster)+
 geom_spatraster(data = my_raster, aes(fill = Classes))+
 geom_point(data = the_points, aes(x = X, y = Y))+
 scale_fill_manual(values = colors_6,
                   labels = c("Crop", "Open Canopy", "Barren/Fallow",
                              "Water", "Developed", "Closed Canopy"),
                   guide = guide_legend(override.aes = list(color = NA)))+ # 移除图例边框
 geom_sf(data = roads, aes(color = "Roads"), alpha = 0.5, show.legend = 'line')+
 geom_sf(data = rivers, aes(color = "Rivers"), alpha = 0.5, show.legend = 'line')+
 scale_color_manual(name = "", values = c("Roads" = "black", "Rivers" = "blue")) # 修正原代码中名称不匹配问题

方法二:全局关闭图例项边框

如果不想单独设置某一个图例,可在theme()中全局关闭所有图例项的边框:

colors_6 =
  c("darkolivegreen1", # Crop
    "#FDE333", # Open Canopy
    "#CCAA50", # Barren/fallow
    "cadetblue1", # Water
    "#A4A4A4", # Developed
    "#0A6B22") # Closed Canopy

ggplot(my_raster)+
 geom_spatraster(data = my_raster, aes(fill = Classes))+
 geom_point(data = the_points, aes(x = X, y = Y))+
 scale_fill_manual(values = colors_6,
                   labels = c("Crop", "Open Canopy", "Barren/Fallow",
                              "Water", "Developed", "Closed Canopy"))+
 geom_sf(data = roads, aes(color = "Roads"), alpha = 0.5, show.legend = 'line')+
 geom_sf(data = rivers, aes(color = "Rivers"), alpha = 0.5, show.legend = 'line')+
 scale_color_manual(name = "", values = c("Roads" = "black", "Rivers" = "blue"))+
 theme(legend.key = element_rect(color = NA)) # 全局移除图例边框

注意:原代码中scale_color_manual的values里写的"Flowlines"和图层的"Rivers"名称不匹配,已修正为"Rivers" = "blue",否则河流颜色无法正确显示。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 05:43:25