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

如何用ggplot绘制带处理组配对连线的栖息地分组箱线图

问题描述

我有如下数据框:

puck <- c("C125a", "C130a", "H100a", "H106a", "L12a", "L15a", "C125b", "C130b", "H100b", "H106b", "L12b", "L15b")
habitat <- c("C", "C", "H", "H", "L", "L","C", "C", "H", "H", "L", "L")
treatment <- c("light", "light", "light", "light", "light", "light", "dark", "dark", "dark", "dark", "dark", "dark")
colony <- c("C125", "C130", "H100", "H106", "L12", "L15", "C125", "C130", "H100", "H106", "L12", "L15")
resid <- c(0.200214909, -0.337518783, 0.053515029, 0.208246923, -0.193085211, -0.378099508, 0.336090273, -0.345066464, 0.001808814, -0.267078962, 0.049018966,0.383408025)
wt <- cbind(puck,habitat,treatment,colony,resid)

我想要绘制以habitat为x轴、resid为y轴、按treatment分组的箱线图,并在图上叠加带连线的处理组配对点(效果为同菌落的不同处理点用线连接)。

尝试了以下代码:

ggplot(data = wt, aes(x=Habitat,y=resid, color = Treatment))+
geom_point(aes(color = Treatment),position=position_jitterdodge(jitter.width=0),alpha=0.5)+
geom_line(aes(group = OG_colonyID))+
geom_boxplot(alpha=1)

但仅得到箱线图之间的单条竖线,请求解决该问题。


解决方法

你的代码存在三个核心问题,修正后即可实现目标:

  1. 数据类型错误:cbind()生成的是矩阵,resid会被强制转为字符型,ggplot无法识别为数值。需转为数据框并修正resid类型:
wt <- data.frame(puck, habitat, treatment, colony, resid = as.numeric(resid))
  1. 变量名大小写不匹配:代码中用了Habitat、Treatment、OG_colonyID,但数据框实际变量名是小写的habitat、treatment、colony,大小写不匹配导致映射失效。

  2. 连线位置与分组错误:要让同colony的两个处理点在同一habitat下连接,需将group设为colony,同时给geom_line设置和点、箱线图一致的位置偏移,确保元素对齐。


修正后的完整代码
library(ggplot2)

# 构造正确的数据框
puck <- c("C125a", "C130a", "H100a", "H106a", "L12a", "L15a", "C125b", "C130b", "H100b", "H106b", "L12b", "L15b")
habitat <- c("C", "C", "H", "H", "L", "L","C", "C", "H", "H", "L", "L")
treatment <- c("light", "light", "light", "light", "light", "light", "dark", "dark", "dark", "dark", "dark", "dark")
colony <- c("C125", "C130", "H100", "H106", "L12", "L15", "C125", "C130", "H100", "H106", "L12", "L15")
resid <- c(0.200214909, -0.337518783, 0.053515029, 0.208246923, -0.193085211, -0.378099508, 0.336090273, -0.345066464, 0.001808814, -0.267078962, 0.049018966,0.383408025)
wt <- data.frame(puck, habitat, treatment, colony, resid)

# 绘图
ggplot(data = wt, aes(x = habitat, y = resid, color = treatment)) +
  geom_boxplot(position = position_dodge(width = 0.8), alpha = 0.5) +
  geom_point(position = position_jitterdodge(jitter.width = 0.1, dodge.width = 0.8), alpha = 0.8) +
  geom_line(aes(group = colony), position = position_dodge(width = 0.8)) +
  labs(x = "Habitat", y = "Residuals", color = "Treatment") +
  theme_bw()

代码说明
  • position_dodge(width = 0.8)统一箱线图、点、线的分组间距,确保所有元素对齐;
  • geom_line的group = colony指定每个菌落的两个处理点之间连线;
  • 箱线图放在底层,避免遮挡上层的点和线;
  • 给点添加轻微抖动(jitter.width = 0.1),防止同位置点重叠。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 00:23:16