Jeff
Jeff

Reputation: 29

multiple violin plots in one frame possible?

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

Upvotes: 1

Views: 1289

Answers (3)

Andrea M
Andrea M

Reputation: 2491

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 reprex package (v2.0.1)

Upvotes: 1

TarJae
TarJae

Reputation: 79271

We could use par(): it puts multiple graphs in a single plot by setting some graphical parameters: See help: ?par()

Here is a fake example:

par(mfrow=c(1,2))   
p1 <- vioplot::vioplot(mtcars$mpg,las=2,main="mtcars$mpg",col="deepskyblue",notch=TRUE)
p2 <- vioplot::vioplot(mtcars$disp,las=2,main="mtcars$disp",col="aquamarine",notch=TRUE)

enter image description here

Upvotes: 0

Abdur Rohman
Abdur Rohman

Reputation: 2944

One way of doing it is by setting add = TRUE

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, add = TRUE)

Upvotes: 2

Related Questions