繁体   English   中英

使用ggplot可视化因子水平之间的差异

[英]Visualise differences between factor levels using ggplot

我想创建一个情节,但我不知道如何成功实现此目标。

我有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_lowCI_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() ,以便更轻松地连接这些表。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM