我脑子里有一个想要创造的情节,但我不知道如何成功实现这个目标。
我有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()
然而,根据手段,我会预期中级(杂色)是“最低”,而在该图中,它是维吉尼卡,它是最低值。
如果我理解你的问题,你需要这样的代码:
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()
以避免因素,以便更容易地加入这些表。