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

R ggplot:调整两个不同图例间的水平间距

解决ggplot双图例水平间距过大的问题

你遇到的问题是ggplot中两个独立图例(填充组和形状组)在底部排列时,组间默认间距过大。之前调整的legend.spacing.x只控制同个图例内部项的间距,而**legend.box.spacing才是控制不同图例组之间的间距**,直接调整它就能搞定。

快速解决:缩小图例组间距

在theme()里给legend.box.spacing设置负的单位值,就能把两个图例组拉近:

library(tidyverse)

df = tibble(quintile = c(1, 1, 1, 1),
            class = c("real_assets", "fin_assets", "liabilities", "net_wealth"),
            value = c(349874, 29449, -12233, 367090))

ggplot() +
  geom_col(data = df %>% filter(class != "net_wealth"),
           aes(x=quintile, y=value, fill=class), position = "stack") +
  geom_point(data = df %>% filter(class == "net_wealth"),
           aes(x=quintile, y=value, shape=class)) +
  theme(legend.title=element_blank(),
        legend.position = "bottom",
        # 负数值会拉近两个图例组,可根据实际效果微调
        legend.box.spacing = unit(-0.6, "cm"))

进阶方案:合并为单个图例

如果想彻底消除组间空白,也可以把形状项整合到填充图例里,让所有类别在同一个图例中展示:

ggplot() +
  geom_col(data = df %>% filter(class != "net_wealth"),
           aes(x=quintile, y=value, fill=class), position = "stack") +
  # 给散点添加fill映射,方便统一图例
  geom_point(data = df %>% filter(class == "net_wealth"),
           aes(x=quintile, y=value, fill=class, shape=class)) +
  # 手动指定填充色,net_wealth设为NA不显示填充
  scale_fill_manual(values = c("real_assets" = "#F8766D", "fin_assets" = "#00BA38", 
                               "liabilities" = "#619CFF", "net_wealth" = NA)) +
  # 手动指定形状,其他类别设为NA不显示形状
  scale_shape_manual(values = c("real_assets" = NA, "fin_assets" = NA, 
                                "liabilities" = NA, "net_wealth" = 18)) +
  theme(legend.title=element_blank(),
        legend.position = "bottom")

这样所有图例项会排成一排,完全没有组间空白,视觉上更紧凑。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.05 22:37:43