Bfu38
Bfu38

Reputation: 1141

Combine many violin plots in one single figure

Is there a way to generate the plot as in figure B?

enter image description here I know how to generate single violin plots but I do not know how to combine them as in the figure. I will give you some artificial data:

     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     

Upvotes: 0

Views: 518

Answers (1)

UseR10085
UseR10085

Reputation: 8176

Use the following code

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

If you want to reproduce the plot you have provided use

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

If you don't want to trim your violin plot then use

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

Data

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

Your Cl 2 does not contain proper replications to be used for violin plot.

Upvotes: 3

Related Questions