【问题标题】:Specify the order for groups when using unite from dplyr for plotting with ggplot使用 dplyr 中的 unite 使用 ggplot 进行绘图时指定组的顺序
【发布时间】:2019-07-05 03:16:54
【问题描述】:

我想做这样的事情

Add multiple comparisons using ggsignif or ggpubr for subgroups with no labels on x-axis

我已经走到这一步了:

包和示例数据

library(tidyverse)
library(ggpubr)
library(ggpol)
library(ggsignif)

example.df <- data.frame(species = sample(c("primate", "non-primate"), 50, replace = TRUE),
                         treated = sample(c("Yes", "No"), 50, replace = TRUE),
                         gender = sample(c("male", "female"), 50, replace = TRUE), 
                         var1 = rnorm(50, 100, 5))

级别

example.df$species <- factor(example.df$species, 
                             levels = c("primate", "non-primate"), labels = c("p", "np"))
example.df$treated <- factor(example.df$treated, 
                             levels = c("No", "Yes"), labels = c("N","Y"))
example.df$gender <- factor(example.df$gender, 
                            levels = c("male", "female"), labels = c("M", "F"))

由于我没有运气让ggsignifggpubr 在需要引用的组未在 x 轴中明确命名时正确放置重要组(因为它们是x 轴中的每个变量,并且仅在填充图例中而不是 x 轴中指示,我尝试了这个。

example.df %>% 
  unite(groups, species, treated, remove = F, sep= "\n") %>% 
  {ggplot(., aes(groups, var1, fill= treated)) + 
     geom_boxjitter() +
     facet_wrap(~ gender, scales = "free") +
     ggsignif::geom_signif(comparisons =  combn(sort(unique(.$groups)), 2, simplify = F),
                           step_increase = 0.1)}

我明白了,

具有为每个组计算的显着性值的分面图

但是,x 轴上组合组的顺序不是我想要的。我想为每个方面订购 p/N、np/N、p/Y、np/Y。

我该怎么做?任何帮助是极大的赞赏。

编辑:使用 mutate 创建一个新变量,并使用我喜欢的绘图顺序解决它使其成为有序因子。

example.df %>% 
  unite(groups, species, treated, remove = F, sep= "\n") %>% 
  mutate(groups2 = factor(groups, levels = c("p\nN", "np\nN", "p\nY", "np\nY"),
                          ordered = TRUE)) %>% 
  {ggplot(., aes(groups2, var1, fill= treated)) +
     geom_boxjitter() + 
     facet_wrap(~gender,scales = "free") +
     ggsignif::geom_signif(comparisons = combn(sort(unique(.$groups2)), 2, simplify = F), 
                           step_increase = 0.1)}

但我仍在寻找完全不必使用 unite 并保留原始因子并仍然使用 ggsignifggpubr 绘制显着性值的解决方案。

【问题讨论】:

    标签: r ggplot2 dplyr ggpubr


    【解决方案1】:

    interaction(来自基本包)的默认参数似乎给出了您正在寻找的因子排序:

    example.df %>%
      mutate(groups = interaction(species, treated, sep = "\n")) %>%
      {ggplot(., aes(groups, var1, fill= treated)) + 
        geom_boxjitter() +
        facet_wrap(~ gender, scales = "free") +
        geom_signif(comparisons = combn(sort(as.character(unique(.$groups))), 2, simplify = F),
                    step_increase = 0.1)}
    

    【讨论】:

      猜你喜欢
      • 2014-01-08
      • 1970-01-01
      • 1970-01-01
      • 2021-06-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多