将多个小提琴图合并到一个图中

时间:2020-05-27 08:37:00

标签: r

有没有一种生成图B所示的图的方法?

enter image description here 我知道如何生成单个小提琴图,但不知道如何将它们组合起来,如图所示。我会给你一些人工数据:

     Cl            Sig1                Sig2            Sig3       
     1             3.5                 2.5             3.7        
     1             2.1                 2               1.7    
     1             0.8                 6               2.5     
     2             9.1                 3.6             0.23   
     2             10.1                8.5             4.7        
     3             11.1                12.5            20        
     3             23.5                19.7            18        
     3             21.5                20              15.7        
     3             18.4                11              13.9     

1 个答案:

答案 0 :(得分:3)

使用以下代码

library(tidyverse)

df %>% pivot_longer(cols = -Cl, names_to = "Sig", values_to = "value") %>% 
  mutate(cl = factor(Cl, levels = c(1, 2, 3))) %>% 
  ggplot() + geom_violin(aes(cl, value, fill=cl)) + facet_wrap(Sig~.)

enter image description here

如果要复制提供的图,请使用

df %>% pivot_longer(cols = -Cl, names_to = "Sig", values_to = "value") %>% 
  mutate(cl = factor(Cl, levels = c(1, 2, 3))) %>% 
  ggplot() + geom_violin(aes(cl, value, fill=cl)) + 
    facet_wrap(Sig~.) + theme_bw() + coord_flip()

enter image description here

如果您不想trim小提琴情节,请使用

df %>% pivot_longer(cols = -Cl, names_to = "Sig", values_to = "value") %>% 
  mutate(cl = factor(Cl, levels = c(1, 2, 3))) %>% 
  ggplot(aes(cl, value, fill=cl)) + geom_violin(trim = FALSE) + 
    facet_wrap(Sig~.) + theme_bw() + coord_flip()

enter image description here

数据

df = structure(list(Cl = c(1L, 1L, 1L, 2L, 2L, 3L, 3L, 3L, 3L), Sig1 = c(3.5, 
2.1, 0.8, 9.1, 10.1, 11.1, 23.5, 21.5, 18.4), Sig2 = c(2.5, 2, 
6, 3.6, 8.5, 12.5, 19.7, 20, 11), Sig3 = c(3.7, 1.7, 2.5, 0.23, 
4.7, 20, 18, 15.7, 13.9)), class = "data.frame", row.names = c(NA, 
-9L))

您的Cl 2没有正确的复制品可用于小提琴演奏。