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

R语言中使用facet_wrap()时如何为各面板添加y轴线条及标题下划线?

解决ggplot分面图的两个需求:显示所有面板y轴线条与添加面板标题下划线

修改后的完整代码

location=rep(c("A","B","C"),each=5)
nitrogen=rep(c(0,10,20,30,40), time=3)
yield=c(15,20,25,29,38,10,20,40,50,55,15,17,16,17,20)
dataA=data.frame(location, nitrogen, yield)

library(ggplot2)

ggplot(data=dataA, aes(x=nitrogen, y=yield))+
  stat_smooth(method='lm', linetype=1, se=FALSE, formula=y~x, linewidth=0.5) +
  geom_point(color="black", size=4) +
  scale_x_continuous(breaks=seq(0,40,10), limits = c(0,40)) +
  scale_y_continuous(breaks=seq(0,60,10), limits = c(0,60)) +
  labs(x="N rate", y="Grain Yield") +
  facet_wrap(~location) +
  theme_classic(base_size=20, base_family="serif")+
  # 实现需求的核心设置
  theme(panel.border = element_rect(color = "black", fill = NA, linewidth = 0.5),
        axis.line.x = element_line(linewidth = 0.5, colour = "black"),
        strip.text = element_text(face = "underline"),
        strip.background= element_rect(color="white", size=0.5,linetype="solid"))+
  windows(width=5.5, height=5)

关键修改点说明

1. 让所有面板显示y轴线条

默认theme_classic()的分面布局仅保留最左侧面板的y轴线条,要实现每个面板都显示y轴:

  • 用panel.border = element_rect(color = "black", fill = NA, linewidth = 0.5)为每个面板添加黑色边框(填充设为透明,避免遮挡图表内容)
  • 单独指定axis.line.x维持x轴原有线条样式,防止被面板边框覆盖

2. 给面板标题添加下划线

直接在theme()中设置strip.text = element_text(face = "underline"),即可为每个分面的标题添加下划线样式。

内容的提问来源于stack exchange,提问作者J.K Kim

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 17:22:35