user11916948
user11916948

Reputation: 954

Group violin plot

In this vioplot I want to present A, B, C for each question next to each other, how do I accomplish this? I manage with boxplots but Im still looking for a solution for vioplot!

set.seed(3)
    id <- rep(1:5, each=3)
    trt <- rep(LETTERS[1:3],5)
    set.seed(1)
    q1 <- runif(15)
    set.seed(2)
    q2 <- runif(15)
    q3 <- runif(15)
    df <- data.frame(id,trt,q1,q2,q3)
    df
    
vioplot(df[df$trt=="A", -c(1:2)], col="red", plotCentre="line",side="both",ylim=c(-5,5), names=colnames(df[,-c(1:2)]),las=2)
vioplot(df[df$trt=="B", -c(1:2)], col="blue", plotCentre="line",side="both",ylim=c(-5,5),add=T)
vioplot(df[df$trt=="C", -c(1:2)], col="yellow", plotCentre="line",side="both",ylim=c(-5,5),add=T)
legend("topright", inset=.02, c("A", "B", "C"), fill=c("red", "blue", "yellow"))

enter image description here

With boxplot:

boxplot(df[,-c(1:2)], boxfill=NA, border=NA,xaxt="n")
a<- boxplot(df[df$trt=="A", -c(1:2)], xaxt = "n", add=TRUE, boxfill="red",
            boxwex=0.25, at=1:ncol(df[,-c(1:2)])-0.15)
name <- colnames(df[,-c(1:2)])
boxplot(df[df$trt=="B", -c(1:2)], xaxt = "n", add=TRUE, boxfill="blue",
        boxwex=0.25, at=1:ncol(df[,-c(1:2)])+0.15)
boxplot(df[df$trt=="C", -c(1:2)], xaxt = "n", add=TRUE, boxfill="yellow",
        boxwex=0.25, at=1:ncol(df[,-c(1:2)])+0.45)
legend("bottomright", inset=.02, c("A", "B", "C"), fill=c("red", "blue", "yellow"), cex=0.7)

enter image description here

Upvotes: 1

Views: 73

Answers (1)

johnjohn
johnjohn

Reputation: 892

Using ggplot, is this what you want ?

df %>% pivot_longer(cols= c('q1':'q3'), names_to = 'Q', values_to = 'Value') %>% 
  ggplot(aes(x=Q, y=Value, fill=trt)) +
  geom_violin()

Upvotes: 1

Related Questions