gpt4 book ai didi

r - 在 ggplot2 中躲避两个不同的几何体

转载 作者:行者123 更新时间:2023-12-03 16:19:39 26 4
gpt4 key购买 nike

假设我有两个不同的数据源。一种是重复观察,一种只是模型预测的平均值 +/- 标准误差。

n <- 30
obs <- data.frame(
group = rep(c("A", "B"), each = n*3),
level = rep(rep(c("low", "med", "high"), each = n), 2),
yval = c(
rnorm(n, 30), rnorm(n, 50), rnorm(n, 90),
rnorm(n, 40), rnorm(n, 55), rnorm(n, 70)
)
) %>%
mutate(level = factor(level, levels = c("low", "med", "high")))

model_preds <- data.frame(
group = c("A", "A", "A", "B", "B", "B"),
level = rep(c("low", "med", "high"), 2),
mean = c(32,56,87,42,51,74),
sem = runif(6, min = 2, max = 5)
)

现在我可以很容易地在同一张图上绘制这些
p <- ggplot(obs, aes(x = level, y = yval, fill = group)) +
geom_boxplot() +
geom_point(data = model_preds, aes(x = level, y = mean), size = 2, colour = "forestgreen") +
geom_errorbar(data = model_preds, aes(x = level, y = mean, ymax = mean + sem, ymin = mean - sem), colour = "forestgreen", size = 1) +
facet_wrap(~group)
enter image description here
并使用它直观地查看模型预测和观察结果之间的差异。
但我认为这看起来有点难看,所以理想情况下会想要从箱线图 geom 中“躲避”点和误差条 geom。
如果你能原谅我的快速绘画,像这样:
enter image description here
好像 position_dodge()可能是要走的路,但我还没有想出如何以这种方式组合两个不同的几何体,并且文档没有任何示例。
可能是不可能的,但我想我会要求检查

最佳答案

由于图形语法将绘图的各个方面清楚地分开,因此无法在绘图的不同层(几何和统计数据)之间交流信息。这也意味着位置调整不能跨层共享,因此它们可以以多层方式躲避。
您可以做的下一个最好的事情是使用 position = position_nudge()在每一层中,因此它们似乎在各个层中都被躲避了。您可能还想调整 width箱线图和误差条的参数。下面的例子:

library(tidyverse)

n <- 30
obs <- data.frame(
group = rep(c("A", "B"), each = n*3),
level = rep(rep(c("low", "med", "high"), each = n), 2),
yval = c(
rnorm(n, 30), rnorm(n, 50), rnorm(n, 90),
rnorm(n, 40), rnorm(n, 55), rnorm(n, 70)
)
) %>%
mutate(level = factor(level, levels = c("low", "med", "high")))

model_preds <- data.frame(
group = c("A", "A", "A", "B", "B", "B"),
level = rep(c("low", "med", "high"), 2),
mean = c(32,56,87,42,51,74),
sem = runif(6, min = 2, max = 5)
)

ggplot(obs, aes(x = level, y = yval, fill = group)) +
geom_boxplot(position = position_nudge(x = -0.3),
width = 0.5) +
geom_point(data = model_preds, aes(x = level, y = mean),
size = 2, colour = "forestgreen",
position = position_nudge(x = 0.3)) +
geom_errorbar(data = model_preds,
aes(x = level, y = mean, ymax = mean + sem, ymin = mean - sem),
colour = "forestgreen", size = 1, width = 0.5,
position = position_nudge(x = 0.3)) +
facet_wrap(~group)

创建于 2021-01-17 由 reprex package (v0.3.0)

关于r - 在 ggplot2 中躲避两个不同的几何体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65765703/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com