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

如何在ggplot的facet_wrap中调整轴标签与分面标签位置预留图例空间

解决ggplot2分面图表的轴标签与分面标签调整需求

完全可以实现你提到的三个调整需求,以下是修改后的代码及对应说明:

调整说明

  • x轴标签左移:在theme()中设置axis.title.x = element_text(hjust = 0),hjust=0代表完全左对齐
  • 右侧y轴标签上移:通过theme()里的axis.title.y.right = element_text(vjust = 1.2)调整垂直位置,数值越大标签越靠上,可根据实际效果微调
  • 分面标签左移:修改strip.text.x的hjust参数为0,让分面标题左对齐,为右侧图例预留空间

修改后的完整代码

p <- ggplot(data_Long, aes(x = Week, y = count)) +
  geom_line(aes(colour = Temp, linetype = Water)) +
  labs(x = "Germination weeks", y = "% Germination", colour = "Temperature (°C)", 
       linetype = "Water Availibility") +
  theme_classic() +
  theme(
    strip.text.x = element_text(size=10, face="italic", hjust = 0), # 分面标签左移
    legend.position = c(0.85,0.15),
    axis.title.x = element_text(hjust = 0), # x轴标签左移
    axis.title.y.right = element_text(vjust = 1.2) # 右侧y轴标签上移
  )+
  scale_y_continuous( limits=c(0, 100),
                      sec.axis = sec_axis(~ ., 
                                          breaks = c(25, 50, 75), 
                                          labels = c("5/15", "10/25", "15/40"), 
                                          name = "Temperature (°C)")) +
  geom_segment(aes(x = 0, y = 75, xend = 8, yend = 75), colour = "grey", size=0.2) +
  geom_segment(aes(x = 8, y = 50, xend = 12, yend = 50), colour = "grey", size=0.2) +
  geom_segment(aes(x = 12, y = 25, xend = 24, yend = 25), colour = "grey", size=0.2) +
  geom_segment(aes(x = 24, y = 50, xend = 26, yend = 50), colour = "grey", size=0.2) +
  geom_segment(aes(x = 8, y = 75, xend = 8, yend = 50), colour = "grey", size=0.2) +
  geom_segment(aes(x = 12, y = 50, xend = 12, yend = 25), colour = "grey", size=0.2) +
  geom_segment(aes(x = 24, y = 25, xend = 24, yend = 50), colour = "grey", size=0.2) +
  annotate('rect', xmin=13, xmax=24, ymin=0, ymax=25, alpha=.1, fill='blue')+ ######Win1
  annotate('rect', xmin=7, xmax=7.2, ymin=0, ymax=75, alpha=.1, fill='blue')+ #####Wet 1
  annotate('rect', xmin=9, xmax=9.2, ymin=0, ymax=50, alpha=.1, fill='blue') + #####Wet 2
  annotate('rect', xmin=11, xmax=11.2, ymin=0, ymax=50, alpha=.1, fill='blue') + #####Wet 3
  facet_wrap(~Species, ncol = 2)+
  scale_color_manual(values=c("royalblue", "orange", "forestgreen", "firebrick3"))+
  scale_x_continuous(breaks=c(0, 5, 10, 15, 20, 25 ))

p

额外提示

  • 移除了原代码中重复的ylim(0,100),因为scale_y_continuous已经设置了limits,避免参数冲突
  • 可根据图表实际显示效果,微调hjust和vjust的数值,达到最理想的布局

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.13 03:34:53