r - ggplot2 中的误差线和线条不匹配
问题描述
我对 ggplot2 中的错误栏有疑问。
我想绘制连续 [iv] 和标称 [条件] 变量之间的交互。我使用这样的代码
iv = runif(n = 100, min = 1, max = 7)
condition <- rep(letters[1:2], length.out = 100)
y = runif(n = 100, min = 1, max = 100)
df <- data.frame(iv, condition, y)
lm20 <- lm(y ~ condition * iv, data = df)
summary(lm20)
df$condition <- as.factor(df$condition)
ggeffect(lm20, terms = c("condition", "iv")) %>%
plot(show.title = FALSE) +
stat_summary(fun.y = mean,
geom = "point") +
stat_summary(fun.y = mean,
geom = "line") +
stat_summary(fun.data = mean_cl_boot,
geom = "errorbar") +
scale_y_continuous("Voting intentions", limits = c(0, 100)) +
scale_colour_discrete(name = "Control", labels = c("Low", "Medium", "High")) +
scale_x_discrete("Condition", labels = c("Low","High")
这就是我得到的:
我遇到两个问题
- 误差线和线不匹配
- 我无法更改 X 轴上的标签
解决方案
下面是一个仅使用 ggplot2 的解决方案,所以没有那么优雅......看看它是否成功!
# Create data frame with the effects
df <- as.data.frame(ggeffect(lm20, terms = c("condition", "iv")))
# Add coordinates manually
df$x2 <- rep(1:2, 3) + rep(c(-.1,0,.1), each = 2)
# Plot
ggplot(df, aes(x2, predicted, col = group)) +
geom_errorbar(aes(x = x2, ymin = predicted-std.error, ymax = predicted+std.error), width = .1) +
geom_segment(df %>% pivot_wider(id_cols = group, names_from = x, values_from = c(predicted:conf.high, x2)),
mapping = aes(x = x2_a, xend = x2_b, y = predicted_a, yend = predicted_b)) +
geom_point(size = 2) +
scale_color_discrete("Control",c("#9b2756", "#003054","#66b0a5"), labels=c("Low", "Medium", "High")) +
scale_y_continuous("Voting intentions", limits = c(0, 100)) +
scale_x_continuous("Condition", breaks = 1:2, labels = c("Low","High"))
推荐阅读
- java - Java为什么这个数组等于打印假?
- c# - 如何从父组件中的事件更新子组件属性
- python-3.x - 从 a中刮取数据用 BeautifulSoup 和 Requests 和 Pandas
- server - 赛普拉斯 - “页面重新加载”后“路线”不起作用
- html - 在 Angular 8 中绑定 youtube 链接?
- mysql - SQL查询打印两个表中的两列,计数
- javascript - 如何在 HTML 文件中捆绑每个外部和内联 JS 脚本
- node.js - 尝试全局安装节点
- xamarin - 嵌入式图像问题 Xamarin
- sql - 使用带有 IN 运算符的子查询和自定义值