R语言中调整堆叠图x轴顺序、添加双层标签及分组间距的方法
解决方案
针对你遇到的三个问题,以下是具体的解决步骤和代码:
1. 先处理数据结构
首先需要将包含问题编号和阶段(Before/After)的Question_num拆分为两个独立字段,同时指定因子顺序来固定x轴排列:
library(tidyverse) library(scales) # 拆分问题编号与阶段,同时设置因子顺序 graphdata3 <- graphdata3 %>% gather(key='Question_num', value='Answer', -Participant) %>% # 按下划线拆分(如果你的字段是其他分隔符,替换sep参数即可) separate(Question_num, into = c("Question", "Phase"), sep = "_") %>% # 手动指定问题顺序(比如Q1到Q5,按你需要的顺序调整) mutate(Question = factor(Question, levels = paste0("Q", 1:5)), # 固定Before/After的显示顺序 Phase = factor(Phase, levels = c("Before", "After")), # 保持回答选项的顺序不变 Answer = factor(Answer, levels = 5:1, labels=c('Strongly Agree','Agree','Neutral','Disagree','Strongly Disagree')))
2. 绘制带双层x轴、自定义顺序和组间距的堆叠图
使用分面(facet)功能实现组间距,同时调整分面标签位置来制作双层x轴:
ggplot(graphdata3, aes(x = Phase, fill = Answer)) + # 绘制百分比堆叠条形图 geom_bar(position = "fill") + # 按问题分面,space="free_x"实现不同问题组之间的间距 facet_grid(~Question, scales = "free_x", space = "free_x") + # 颜色方案保持你原来的设置 scale_fill_brewer(palette='Spectral', direction=-1) + # y轴设为百分比格式,取消上下留白 scale_y_continuous(expand = expansion(0), labels = percent_format()) + # 设置标签:上层x轴为Before/After,下层为问题编号 labs(x = NULL, y = 'Proportion of Answers (%)') + theme_classic() + theme( # 图例放在顶部 legend.position='top', # 将分面标签(问题编号)移到x轴下方作为下层标签 strip.position = "bottom", strip.placement = "outside", # 去掉分面标签的背景框 strip.background = element_blank(), # 调整上层x轴标签(Before/After)的间距 axis.text.x = element_text(margin = margin(t = 10)), # 调整下层问题标签的间距 strip.text.x = element_text(margin = margin(b = 10)) )
关键问题解决说明
- x轴顺序固定:通过将
Question设为因子并手动指定levels,确保问题按你需要的顺序排列,而非字母顺序。 - 双层x轴:利用分面标签作为下层的问题编号,x轴本身显示Before/After作为上层标签,通过
strip.position调整位置实现双层效果。 - 组间距:
facet_grid的space="free_x"参数会自动在不同问题的组之间添加间距,每个问题内的Before/After条形图则紧密排列。
内容的提问来源于stack exchange,提问作者lisa
相关产品推荐
相关产品推荐

