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

ggarrange合并图表时图例尺寸异常及左侧留白问题求助

问题:ggarrange合并图表后左侧留白、图例标记混乱

我有两幅图表,其中一幅包含图例,另一幅没有。单独绘制和导出时两者均显示正常,但使用ggarrange工具合并这两幅图后,左侧出现了留白区域,同时图例的标记尺寸也变得混乱。

复现代码(基于iris数据集)

library(tidyverse)
library(ggpubr)
library(showtext)

showtext_auto()  ##It reduces font size to a customization friendly level

setwd("C:/Users/mdnah/Desktop")

A<- iris %>% 
  gather(key="cat", value = "value", -Species) %>% 
  group_by(Species, cat) %>% 
  summarise(mn= mean(value)) %>%
  filter(Species!="setosa") %>% 
  ggplot(aes("", mn, fill=cat))+
  geom_bar(stat = "identity", position = "fill")+
  scale_fill_discrete(name=NULL, guide= guide_legend(label.position = "left"))+
  coord_polar(theta = "y", start = 0)+
  facet_wrap(~Species, nrow=1)+
  theme_void()+
  theme(text = element_text(family = "serif", size = 20, lineheight = 0.3),
        legend.box.margin = margin(-20,-10,0,0),
        legend.spacing.x = unit(0.2, "cm"),
        legend.key.size = unit(0.3, "cm"),
        legend.position="left")
print(A)
# ggsave("FigA.jpg", width = 4, height = 2)

B<- iris %>% 
  gather(key="cat", value = "value", -Species) %>% 
  group_by(Species, cat) %>% 
  summarise(mn= mean(value)) %>%
  filter(Species!="setosa") %>% 
  ggplot(aes(mn, reorder(cat, mn)))+
  geom_bar(stat = "identity", width = 0.7)+
  scale_x_continuous(expand = c(0,0))+
  facet_wrap(~Species, nrow = 1)+
  theme_minimal()+
  theme(axis.text = element_text(colour = "black", lineheight = 0.3),
        text = element_text(family = "serif", size = 20),
        strip.text = element_blank(),
        panel.spacing = unit(1, "cm"),
        axis.title = element_blank())
print(B)
# ggsave("FigB.jpg", width = 4, height = 2.5)

ggarrange(A, B, nrow=2)
ggsave("FigAB.jpg", width = 4, height = 4.5) #widths are equal, so I just added up the heights.

效果对比

  • 当前生成效果:左侧存在多余留白,图例的标记尺寸变形,与单独绘制时的预期样式不符
  • 期望效果:左侧无多余留白,图例标记尺寸正常,两幅图紧凑对齐

已尝试的解决方法

  • 使用get_legend()分离图例grob,但无法将其放置到理想位置
  • 尝试嵌套ggarrange(顶部组合图A的图例与图A,底部放置图B),未解决问题
  • 发现小字号不会导致图例标记变形,曾怀疑是lineheight的问题,但实际并非如此

猜测方向

问题可能与字体大小或元素边距有关。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 09:10:39