在base R中创建ABAB图,可以通过以下步骤实现:
means <- tapply(df$Y, list(df$A, df$B), mean)
plot(1, type = "n", xlim = c(0, 1), ylim = c(0, 1), xlab = "A", ylab = "Y", main = "ABAB图")
segments(0, means[1, 1], 0.5, means[1, 1], lwd = 2) # A1B1
segments(0.5, means[1, 1], 0.5, means[2, 1], lwd = 2) # A1B2
segments(0.5, means[2, 1], 1, means[2, 1], lwd = 2) # A2B2
segments(1, means[2, 1], 1, means[1, 1], lwd = 2) # A2B1
points(rep(0, length(df$Y[df$A == "A1" & df$B == "B1"])), df$Y[df$A == "A1" & df$B == "B1"], pch = 16) # A1B1
points(rep(0.5, length(df$Y[df$A == "A1" & df$B == "B2"])), df$Y[df$A == "A1" & df$B == "B2"], pch = 16) # A1B2
points(rep(1, length(df$Y[df$A == "A2" & df$B == "B2"])), df$Y[df$A == "A2" & df$B == "B2"], pch = 16) # A2B2
points(rep(1, length(df$Y[df$A == "A2" & df$B == "B1"])), df$Y[df$A == "A2" & df$B == "B1"], pch = 16) # A2B1
legend("topright", legend = c("A1B1", "A1B2", "A2B2", "A2B1"), pch = 16, lwd = 2)
完整的代码如下:
# 创建数据框
df <- data.frame(A = rep(c("A1", "A2"), each = 10),
B = rep(c("B1", "B2"), times = 10),
Y = rnorm(20))
# 计算平均响应值
means <- tapply(df$Y, list(df$A, df$B), mean)
# 创建图形设备
plot(1, type = "n", xlim = c(0, 1), ylim = c(0, 1), xlab = "A", ylab = "Y", main = "ABAB图")
# 绘制线段
segments(0, means[1, 1], 0.5, means[1, 1], lwd = 2) # A1B1
segments(0.5, means[1, 1], 0.5, means[2, 1], lwd = 2) # A1B2
segments(0.5, means[2, 1], 1, means[2, 1], lwd = 2) # A2B2
segments(1, means[2, 1], 1, means[1, 1], lwd = 2) # A2B1
# 绘制数据点
points(rep(0, length(df$Y[df$A == "A1" & df$B == "B1"])), df$Y[df$A == "A1" & df$B == "B1"], pch = 16) # A1B1
points(rep(0.5, length(df$Y[df$A == "A1" & df$B == "B2"])), df$Y[df$A == "A1" & df$B == "B2"], pch = 16) # A1B2
points(rep(1, length(df$Y[df$A == "A2" & df$B == "B2"])), df$Y[df$A == "A2" & df$B == "B2"], pch = 16) # A2B2
points(rep(1, length(df$Y[df$A == "A2" & df$B == "B1"])), df$Y[df$A == "A2" & df$B == "B1"], pch = 16) # A2B1
# 添加图例
legend("topright", legend = c("A1B1", "A1B2", "A2B2", "A2B1"), pch = 16, lwd = 2)
这样就可以在base R中创建一个简单的ABAB图。请注意,这只是一个基本示例,你可以根据自己的需求进行修改和扩展。
领取专属 10元无门槛券
手把手带您无忧上云