Violin
Keywords
clusterings
Examples
Callouts
ggplot(mtcars, aes(x = factor(cyl), y = mpg)) +
geom_violin() +
labs(title = "Violin Plot of MPG by Cylinder Count",
x = "Number of Cylinders", y = "Miles Per Gallon (MPG)",
caption="Created by rstudiodatalab.com")
# Create a customized violin plot with additional aesthetics
ggplot(mtcars, aes(x = factor(cyl), y = mpg, fill = factor(cyl))) +
geom_violin(trim = FALSE, scale = "width", adjust = 1.5, alpha = 0.7) +
geom_boxplot(width = 0.1, fill = "white", outlier.shape = NA) +
labs(title = "Customized Violin Plot of MPG by Cylinder Count",
x = "Number of Cylinders",
y = "Miles Per Gallon (MPG)",
fill="CYL",
caption="Created by rstudiodatalab.com") +
theme_minimal()
Mean and median
# Create a violin plot with median and mean
ggplot(mtcars, aes(x = factor(cyl), y = mpg, fill = factor(cyl))) +
geom_violin(trim = FALSE, scale = "width", adjust = 1.5, alpha = 0.7) +
stat_summary(fun = median, geom = "point", shape = 23, size = 3, fill = "white") +
stat_summary(fun = mean, geom = "point", shape = 21, size = 3, fill = "red") +
labs(title = "Violin Plot of MPG by Cylinder Count with Median and Mean",
x = "Number of Cylinders",
y = "Miles Per Gallon (MPG)") +
theme_minimal()
SD
# Create a violin plot with a standard deviation
ggplot(mtcars, aes(x = factor(cyl), y = mpg, fill = factor(cyl))) +
geom_violin(trim = FALSE, scale = "width", adjust = 1.5, alpha = 0.7) +
stat_summary(fun.data = mean_sdl, fun.args = list(mult = 1), geom = "errorbar", width = 0.2) +
labs(title = "Violin Plot of MPG by Cylinder Count with Standard Deviation",
x = "Number of Cylinders",
y = "Miles Per Gallon (MPG)") +
theme_minimal()
Kernel Density Estimation
# Create a violin plot with Gaussian kernel density estimation
ggplot(mtcars, aes(x = factor(cyl), y = mpg)) +
geom_violin(kernel = "gaussian") +
labs(title = "Violin Plot with Gaussian Kernel Density Estimation",
x = "Number of Cylinders",
y = "Miles Per Gallon (MPG)")
# Create a violin plot with different bandwidths for comparison
<- ggplot(mtcars, aes(x = factor(cyl), y = mpg)) +
p1 geom_violin(adjust = 0.5) +
labs(title = "Bandwidth = 0.5")
<- ggplot(mtcars, aes(x = factor(cyl), y = mpg)) +
p2 geom_violin(adjust = 1) +
labs(title = "Bandwidth = 1")
<- ggplot(mtcars, aes(x = factor(cyl), y = mpg)) +
p3 geom_violin(adjust = 2) +
labs(title = "Bandwidth = 2")
# Arrange plots in a grid for comparison
library(gridExtra)
grid.arrange(p1, p2, p3, ncol = 3)
Dot plot
# Create a violin plot with added dot plots
ggplot(mtcars, aes(x = factor(cyl), y = mpg, fill = factor(cyl))) +
geom_violin(trim = FALSE, scale = "width", adjust = 1.5, alpha = 0.7) +
geom_dotplot(binaxis = 'y', stackdir = 'center', dotsize = 0.5) +
labs(title = "Violin Plot with Dot Plots",
x = "Number of Cylinders",
y = "Miles Per Gallon (MPG)") +
theme_minimal()