Become a better data scientist

Sign up to our newsletter

No thanks

Violin plot in ggplot2

By Data Tricks, 19 March 2019

Violin plots are similar to box plots, with the additional benefit of showing a kernel density distribution.

library(ggplot2)
set.seed(135)
#Create some simulated data
data <- data.frame(Value = round(rnorm(n=100000, mean=100, sd=20),0),
                   Category = sample(c(1:2),100000,replace=TRUE))
data$Category <- as.character(data$Category)
#Set parameters for a theme in ggplot2
theme <- theme(panel.grid.major = element_blank(),
               panel.grid.minor = element_blank(),
               panel.background = element_blank(),
               axis.line.x = element_line(color="#919191", size = 0.1),
               axis.line.y = element_line(color="#919191", size = 0.1))
#Basic violin plot
gg <- ggplot(data, aes(x = Category, y = Value))
gg <- gg + geom_violin(aes(fill=Category))
gg <- gg + theme
print(gg)

Tags: ,

Leave a Reply

Your email address will not be published. Required fields are marked *

Please note that your first comment on this site will be moderated, after which you will be able to comment freely.