如何用facet_wrap创建含3个子图的X轴?R ggplot技术求助
解决方案
要实现基于Hour列创建3个子图的需求,需按以下步骤调整代码:
1. 补全误差棒数据datX的Hour信息
当前datX仅包含Well分组,缺少对应Hour维度的信息,需根据你的实验逻辑为每条记录匹配对应时间点,示例如下(请根据实际实验设计调整映射规则):
datX <- datX %>% mutate(Hour = case_when( Well %in% c("0", "8") ~ 0, Well == "16" ~ 24, Well == "32" ~ 48 ))
2. 修正原代码语法错误
原代码中geom_errorbar语句末尾缺失闭合括号,需补充完整:
geom_errorbar(data = datX, mapping = aes(x = E2F4, ymin = Colonies - Errors, ymax = Colonies + Errors))
3. 调整分面变量为Hour
将facet_wrap的分组维度从Well替换为Hour,并保持横向排列:
facet_wrap(~Hour, nrow = 1, strip.position = "bottom")
完整修改后的代码
ggplot(welldata, aes(x = E2F4, y = Colonies, color = Clone, fill = E2F4)) + geom_point(aes(color = Clone), size = 2) + geom_errorbar(data = datX, mapping = aes(x = E2F4, ymin = Colonies - Errors, ymax = Colonies + Errors)) + facet_wrap(~Hour, nrow = 1, strip.position = "bottom") + theme_minimal() + theme(strip.placement = "outside", panel.spacing = unit(0, "cm"), strip.text = element_text(size = 10, margin = margin(b=15)), legend.title = element_text(size = 10), plot.title = element_text(margin = margin(b=10)))
额外说明
如果需要同时结合Well与Hour生成子图,可将分面变量改为~interaction(Hour, Well),但需确保数据中存在足够的有效组合来生成3个子图。同时要保证welldata与datX的Hour分组完全对应,避免误差棒无法匹配对应子图的问题。
内容的提问来源于stack exchange,提问作者astaf
相关产品推荐
相关产品推荐

