我想创建一个情节,但我不知道如何成功实现此目标。
我有2个数据框,一个包含每个因子水平的平均值,另一个包含这些水平之间的成对差异。
contrasts <- data.frame(Level1 = c("setosa", "setosa", "versicolor"),
Level2 = c("versicolor", "virginica", "virginica"),
Diff = c(0.65, 0.46, -0.20),
CI_low = c(0.53, 0.35, -0.32),
CI_high = c(0.75, 0.56, -0.09))
means <- data.frame(Species = c("setosa", "versicolor", "virginica"),
Mean = c(3.42, .77, 2.97))
我的目标是使用均值作为三角形的起点,该三角形将“投影”到相应对比度的水平上,该高度等于CI(CI_low
和CI_high
) 。这样看起来就像是(请原谅我的画):
使用以下内容,我轻松添加了初始要点:
library(tidyverse)
means %>%
ggplot() +
geom_point(aes(x = Species, y= Mean)) +
geom_ribbon(data=contrasts, aes(x=Level1, ymin=CI_low, ymax=CI_high))
但是我很难添加三角形。有任何想法吗?非常感谢!
感谢Yuriy Barvinchenko,它提供了获得此代码的代码:
contrasts %>%
bind_cols(id=1:3) %>%
inner_join(means, by=c('Level1' = 'Species')) %>%
select(id, x=Level1, y=Mean) %>%
bind_rows( (contrasts %>%
bind_cols(id=1:3) %>%
select(id, x=Level2, y=CI_low)),
(contrasts %>%
bind_cols(id=1:3) %>%
select(id, x=Level2, y=CI_high))) %>%
ggplot(aes(x = x, y= y, group=id)) +
geom_polygon()
但是,基于均值,我希望中间级别(杂色)是“最低”的,而在该图中,维吉尼亚是最低的。
答案 0 :(得分:3)
如果我正确理解了您的问题,则需要这样的代码:
contrasts <- tibble(Level1 = c("setosa", "setosa", "versicolor"),
Level2 = c("versicolor", "virginica", "virginica"),
Diff = c(0.65, 0.46, -0.20),
CI_low = c(0.53, 0.35, -0.32),
CI_high = c(0.75, 0.56, -0.09))
means <- tibble(Species = c("setosa", "versicolor", "virginica"),
Mean = c(3.42, .77, 2.97))
library(tidyverse)
contrasts %>%
bind_cols(id=1:3) %>%
inner_join(means, by=c('Level1' = 'Species')) %>%
select(id, x=Level1, y=Mean) %>%
bind_rows( (contrasts %>%
bind_cols(id=1:3) %>%
select(id, x=Level2, y=CI_low)),
(contrasts %>%
bind_cols(id=1:3) %>%
select(id, x=Level2, y=CI_high))) %>%
ggplot(aes(x = x, y= y, group=id)) +
geom_polygon()
请注意,为了避免因素,我使用tibble()
而不是data.frame()
,以便更轻松地连接这些表。