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

如何在R ggplot2离散地图图例中手动调整NA条目的位置?

解决ggplot2图例中NA条目位置问题

要把NA条目移到图例底部,只需要在guide_legend()里添加na.position = "bottom"参数即可,同时保留reverse = TRUE来维持类别从高到低的顺序。

修改后的完整代码:

or <- or %>% 
  mutate(nonirr_rent_class = cut(nonirr_crop_rent, breaks = c(0, 50, 100, 150, 200), include.lowest = T)) 

nonirr_breaks<-c("0-50", "50-100", "100-150", "150-200")


(
  nonirr_rent <- ggplot(data = or) +
    geom_sf(aes(fill = nonirr_rent_class)) +
    labs(fill = "$/acre") +
    ggtitle("Non-irrigated cropland rent, 2023") +
    theme_void() +
    theme(plot.title = element_text(hjust = 0.5, size = 14)) +
    scale_fill_discrete_sequential(
      palette = "YlGn",
      labels = nonirr_breaks, 
      na.value="gray", 
      guide = guide_legend(reverse = TRUE, na.position = "bottom")
    )
)

说明

  • reverse = TRUE 实现了将类别反转,让最高租金区间(150-200,最深绿色)显示在图例顶部,最低区间在下方
  • na.position = "bottom" 强制将NA对应的灰色条目固定在图例最底部,不会随类别反转而移动

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 03:42:39