Home > database >  multiple violin plots in one frame possible?
multiple violin plots in one frame possible?

Time:04-22

I am new to R. I created two violin plots from a .RData file. Is it possible to have both of them in one picture/frame instead of two separate?

I used in my example:

vioplot::vioplot(GER$K,las=2,main="GER$K",col="deepskyblue",notch=TRUE)
vioplot::vioplot(LIT$B,las=2,main="LIT$B",col="aquamarine",notch=TRUE)

thanks for your help. Jeff

CodePudding user response:

As Skaqqs suggested, an alternative is using ggplot2, which has great functionalities. The trade-off is that data needs to be in a specific format, called long.

I'm making an assumption that both K and B have the same units of measurement.

# Load libraries
library(dplyr)
library(tidyr)
library(ggplot2)

# Create sample data
GER <- data.frame(id = 1:40,
                  K = rnorm(40, 15, 8))
LIT <- data.frame(id = 41:90,
                  B = rnorm(50, 24, 7))

# Join datasets and reshape them to a long format
dat <-
  full_join(GER, LIT) |>
  pivot_longer(c(K, B))

# Create the plot
dat |> 
  ggplot(aes(x = name, y = value, fill = name))  
  geom_violin()  
  scale_fill_manual(values = c("deepskyblue", "aquamarine"))

Created on 2022-04-21 by the enter image description here

  •  Tags:  
  • r
  • Related