user552231
user552231

Reputation: 1135

Change x-axis in violin plot in R

I am trying to change the values in the x-axis of vioplot. I used a suggestion and wrote:

library(vioplot)  
labels=c(10,20,30)  
x1=c(1,2,3,4)  
x2=c(5,6,7,8,9,10)  
x3=c(11,12,13,14,15,16)  
x=list(x1,x2,x3)  
do.call(what = vioplot, args = x)  
axis(side=1,at=1:length(labels),labels=labels)  

But it seems that the values in the a-axis are added to 1-2-3 which I don't want to be presented.

thank you

Upvotes: 1

Views: 3177

Answers (1)

Sathish
Sathish

Reputation: 12723

You have your data in list() format, so it has to be converted to data frame. Then melt the data frame by stacking the values on top of each other.

Using geom_violin we create the kernel density plot and with geom_boxplot, we create boxplot on top of kernel density plot. The width of the boxplot is controlled using width.

library('ggplot2')
library('reshape2')
df <- data.frame( lapply(x, function(y) {length(y) <- max(lengths(x)); y}))  # create data frame from list of x
colnames(df) <- as.character(labels)  # change column names to labels
df <- melt(df)                        # melt data frame
df <- df[ !is.na(df$value), ]         # remove NA
ggplot(data = df ) + 
  geom_violin(aes(x = variable, y = value, fill = variable )) +   # kernel density plot
  geom_boxplot(aes(x = variable, y = value ), width = 0.1) +   # box plot
  xlab( " labels " ) +   # x axis title
  ylab( " values " )     # y axis title

enter image description here

trim = FALSE

ggplot(data = df ) + 
  geom_violin(aes(x = variable, y = value, fill = variable ), trim = FALSE ) +   # kernel density plot
  geom_boxplot(aes(x = variable, y = value ), width = 0.1) +   # box plot
  xlab( " labels " ) +   # x axis title
  ylab( " values " )     # y axis title

enter image description here

Data:

labels=c(10,20,30)  
x1=c(1,2,3,4)  
x2=c(5,6,7,8,9,10)  
x3=c(11,12,13,14,15,16)  
x=list(x1,x2,x3) 

Upvotes: 1

Related Questions