【发布时间】:2017-02-14 12:48:05
【问题描述】:
我的问题类似于this,但那里的答案对我不起作用。基本上,我正在尝试使用“模糊”设计生成回归不连续图,该设计使用治疗组和对照组的所有数据,但仅在治疗组和对照组的“范围”内绘制回归线。
下面,我模拟了一些数据并使用基本图形生成了模糊 RD 图。我希望用 ggplot2 复制这个情节。请注意,其中最重要的部分是浅蓝色回归线使用所有蓝点拟合,而桃色回归线使用所有红点拟合,尽管仅绘制在个人预期的范围内接受治疗。这是我在 ggplot 中难以复制的部分。
我想迁移到 ggplot,因为我想使用 faceting 在参与者嵌套的各个单元中生成相同的图。在下面的代码中,我展示了一个使用geom_smooth 的非示例。当组内没有模糊性时,它可以正常工作,否则会失败。如果我可以让geom_smooth 仅限于特定范围,我想我会被设置。感谢您提供任何和所有帮助。
模拟数据
library(MASS)
mu <- c(0, 0)
sigma <- matrix(c(1, 0.7, 0.7, 1), ncol = 2)
set.seed(100)
d <- as.data.frame(mvrnorm(1e3, mu, sigma))
# Create treatment variable
d$treat <- ifelse(d$V1 <= 0, 1, 0)
# Introduce fuzziness
d$treat[d$treat == 1][sample(100)] <- 0
d$treat[d$treat == 0][sample(100)] <- 1
# Treatment effect
d$V2[d$treat == 1] <- d$V2[d$treat == 1] + 0.5
# Add grouping factor
d$group <- gl(9, 1e3/9)
生成带底的回归不连续图
library(RColorBrewer)
pal <- brewer.pal(5, "RdBu")
color <- d$treat
color[color == 0] <- pal[1]
color[color == 1] <- pal[5]
plot(V2 ~ V1,
data = d,
col = color,
bty = "n")
abline(v = 0, col = "gray", lwd = 3, lty = 2)
# Fit model
m <- lm(V2 ~ V1 + treat, data = d)
# predicted achievement for treatment group
pred_treat <- predict(m,
newdata = data.frame(V1 = seq(-3, 0, 0.1),
treat = 1))
# predicted achievement for control group
pred_no_treat <- predict(m,
newdata = data.frame(V1 = seq(0, 4, 0.1),
treat = 0))
# Add predicted achievement lines
lines(seq(-3, 0, 0.1), pred_treat, col = pal[4], lwd = 3)
lines(seq(0, 4, 0.1), pred_no_treat, col = pal[2], lwd = 3)
# Add legend
legend("bottomright",
legend = c("Treatment", "Control"),
lty = 1,
lwd = 2,
col = c(pal[4], pal[2]),
box.lwd = 0)
ggplot 的非示例
d$treat <- factor(d$treat, labels = c("Control", "Treatment"))
library(ggplot2)
ggplot(d, aes(V1, V2, group = treat)) +
geom_point(aes(color = treat)) +
geom_smooth(method = "lm", aes(color = treat)) +
facet_wrap(~group)
注意第 1 组和第 2 组超出治疗范围的回归线。
【问题讨论】:
标签: r plot ggplot2 visualization