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

如何在ggplot中缩小坐标轴与坐标轴刻度标签的间距?

问题:ggplot垂直x轴标签与轴间距无法缩小

我尝试在ggplot的theme()函数的axis.text.x参数中使用hjust和vjust来缩小x轴垂直标签与轴之间的间距,但始终无法得到理想效果。

原代码

d %>%
  filter(ISO3 == "SLE") %>%
  select(starts_with("DQQ"), YEAR_WAVE) %>%
  pivot_longer(cols = starts_with("DQQ"), names_to = "DQQ", values_to = "Value") %>%
  filter(Value == 1) %>%
  ggplot(aes(DQQ, fill = as.factor(YEAR_WAVE))) +
  geom_bar(position = "dodge") +
  labs(fill = "Year") +
  scale_y_continuous(expand = c(0, 200)) +
  theme(
    panel.background = element_rect(fill = "white"),
    panel.border = element_blank(),
    axis.line.x = element_blank(),
    axis.line.y = element_blank(),
    plot.margin = unit(c(0, .5, 0, 0), "cm"),
    axis.ticks.length = unit(0, "cm"),
    #aspect.ratio = 0.5,
    legend.position = c(0.75, .95),
    legend.justification = c("right", "top"),
    legend.box.just = "right",
    legend.margin = margin(6, 6, 6, 6),
    axis.text.x = element_text(face="bold", color="#993333", size = 12, angle=90, hjust = 0.1, vjust = 0.5)
  )

问题图示

垂直x轴标签间距过大的柱状图


解决方案

仅靠hjust和vjust不足以调整旋转后标签与轴的间距,可通过以下几种方式优化:

  • 调整axis.text.x的margin参数:当标签旋转90度时,用margin直接控制标签与轴的距离。将axis.text.x修改为:

    axis.text.x = element_text(face="bold", color="#993333", size = 12, angle=90, hjust = 1, vjust = 0.5, margin = margin(t = -5, r = 0, b = 0, l = 0))
    

    其中t(顶部)设为负数,可让标签向x轴方向靠近,数值可根据实际效果调整(如-3、-5)。

  • 压缩x轴扩展间距:给x轴添加scale_x_discrete(expand = c(0, 0.1)),减少x轴两端的空白,让标签更紧凑。

  • 优化hjust参数:旋转90度时,hjust=1能让标签右端对齐轴的位置,比hjust=0.1更贴合轴的方向,配合vjust=0.5保证垂直居中。

修改后完整代码

d %>%
  filter(ISO3 == "SLE") %>%
  select(starts_with("DQQ"), YEAR_WAVE) %>%
  pivot_longer(cols = starts_with("DQQ"), names_to = "DQQ", values_to = "Value") %>%
  filter(Value == 1) %>%
  ggplot(aes(DQQ, fill = as.factor(YEAR_WAVE))) +
  geom_bar(position = "dodge") +
  labs(fill = "Year") +
  scale_y_continuous(expand = c(0, 200)) +
  scale_x_discrete(expand = c(0, 0.1)) + # 压缩x轴两端空白
  theme(
    panel.background = element_rect(fill = "white"),
    panel.border = element_blank(),
    axis.line.x = element_blank(),
    axis.line.y = element_blank(),
    plot.margin = unit(c(0, .5, 0, 0), "cm"),
    axis.ticks.length = unit(0, "cm"),
    #aspect.ratio = 0.5,
    legend.position = c(0.75, .95),
    legend.justification = c("right", "top"),
    legend.box.just = "right",
    legend.margin = margin(6, 6, 6, 6),
    axis.text.x = element_text(face="bold", color="#993333", size = 12, angle=90, hjust = 1, vjust = 0.5, margin = margin(t = -4, r = 0, b = 0, l = 0))
  )

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 00:44:55