R语言ggplot绘制多X轴折线图问题咨询,附示例数据与代码
多X轴ggplot绘图解决方案
你可以通过两种常用方案实现需求:
方案1:借助ggh4x包实现嵌套X轴(效果更贴合示例图)
ggh4x包扩展了ggplot2的坐标轴能力,可以直接生成多层嵌套的X轴标签:
依赖安装
install.packages(c("ggplot2", "ggh4x"))
完整绘图代码
library(ggplot2) library(ggh4x) # 示例数据 df <- data.frame( Time = c(" ","Phase 1","Phase 1","Phase 1","Phase 1"," ", " ","Phase 2","Phase 2","Phase 2","Phase 2"," "), Condition = c("BO", "BO", "BO", "BO","BO","BO", "OB","OB","OB","OB","OB","OB"), Phase = c("Baseline", "T1", "T2", "T1", "T2", "Follow-Up", "Baseline", "T1", "T2", "T1", "T2", "Follow-Up"), Change = c(0,-2.84, -5.02, -6.81,-7.41,-6.80, 0, -3.35,-6.92,-7.05,-6.59,-6.41) ) # 锁定X轴顺序避免自动排序错乱 df$x_id <- factor(1:nrow(df), levels = 1:nrow(df)) ggplot(df, aes(x = x_id, y = Change, color = Condition, group = Condition)) + geom_line(linewidth = 1) + geom_point(size = 2) + # 配置三层嵌套X轴 scale_x_discrete( labels = df$Phase, guide = axis_nested( nest_levels = ~ interaction(Phase, Condition, Time), expand = c(0,0.5) ) ) + labs(x = NULL, y = "Change") + theme_bw() + theme( axis.text.x = element_text(angle = 45, hjust = 1), ggh4x.axis.nesttext.x = element_text(hjust = 0.5), ggh4x.axis.nestline.x = element_line(linewidth = 0.5) )
方案2:ggplot2原生分面实现(无需额外依赖)
用分面功能将分组标签放在X轴外侧充当多层标签,适配性更强:
library(ggplot2) # 复用上述df数据 ggplot(df, aes(x = Phase, y = Change, color = Condition, group = Condition)) + geom_line(linewidth = 1) + geom_point(size = 2) + # 分面充当外层X轴标签 facet_grid(~ Condition + Time, scales = "free_x", space = "free_x", switch = "x") + labs(x = NULL, y = "Change") + theme_bw() + theme( axis.text.x = element_text(angle = 45, hjust = 1), strip.placement = "outside", strip.background.x = element_blank() )
两种方案都可以实现多X轴效果,你可以根据自己的需求调整线条样式、颜色、字号等主题参数。
内容的提问来源于stack exchange,提问作者Matt Landry
相关产品推荐
相关产品推荐

