使用dplyr中的unite进行ggplot绘图时,指定组的顺序

时间:2019-02-11 15:22:50

标签: r ggplot2 dplyr ggpubr

我想做这样的事情

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)}

我明白了,

Faceted图,为每个组计算显着性值 Faceted plot with significance values computed for every group

但是,组合轴在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进行绘制的显着性值的解决方案。

1 个答案:

答案 0 :(得分:1)

interaction的默认参数(来自基本软件包)似乎给出了您要查找的因子顺序:

result

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)}