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

如何调整ggplot中facet_grid生成的箱线图间及与Y轴的间距?

解决ggplot箱线图间距问题

调整Y轴与箱线图的间距

  • 用scale_y_continuous()替代ylim(),通过expand = c(0, 0)参数移除Y轴和箱线图之间的多余间距,同时保留指定的数值范围:
scale_y_continuous(limits = c(50, 250), expand = c(0, 0))
  • 说明:ylim()会默认保留轴与图形的间距,而scale_y_continuous()的expand参数能精准控制这个间距。

调整分面(facet_grid)之间的间距

  • 在theme()中添加panel.spacing = unit(0, "lines"),可以将两个分面的间距缩至最小;如果需要微调,把0改成你需要的数值即可:
theme(
  # 其他已有的theme设置...
  panel.spacing = unit(0, "lines")
)

完整修改后的代码

kazakh_dor |> 
  ggplot(aes(x = CPosWord, y = ClengthMS, fill = TargetC)) + 
  geom_boxplot(width = 0.5,
               position = position_dodge(width = 0.5)) + 
  scale_y_continuous(limits = c(50, 250), expand = c(0, 0)) + 
  facet_grid( ~ Vfront) + 
  labs(x = "Word position", y = "Duration (ms)") + 
  ggtitle("Onsets") + 
  theme(axis.text.x = element_text(size = 11, angle = 90, vjust = 0.5, hjust = 1)) + 
  theme(
    legend.title = element_blank(),
    legend.position = "right",
    legend.direction = "vertical",
    legend.key.width = unit(2, "line"),
    legend.key.height = unit(1.5, "line"),
    legend.spacing.x = unit(0.5, "line"),
    legend.spacing.y = unit(0.5, "line"),
    legend.background = element_rect(fill = "white", size = 0.0, linetype = "solid"),
    panel.spacing = unit(0, "lines")
  )

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.25 16:37:56