We provide effective and economically affordable training courses for R and Python, Click here for more details and course registration !

Violin plot is quite similar as boxplot, in the sense that it shows the range of the data. And at the same time a violin plot illustrates the data distribution shape with a density curve on both sides of the central pillar. The follow image shows several typical violin plots of variable ‘price’ with respect to different values of variable ‘cut’.

Violin plots

Plotting violin plots with R can be conducted by applying geom_violin() function with ggplot() function from ggplot2 package. The basic form of the structure is

ggplot( dataframe, aes( x, y, fill, color)) + geom_violin()

Where

x and y represent the variable for x-axis and y-axis, and fill and color are used for color options.

The following code example shows plotting a simple violin plot for variable ‘cut’ and ‘price’ from data frame ‘diamonds’ in ggplot2 package.

#load ggplot2 package
library(ggplot2)

# Basic violin plot
# diamonds dataframe being used here

ggplot(diamonds, aes(x=cut, y=price)) +
  geom_violin()
A simple violin plot

Next example show plotting violin plots by setting the contour color of the density curves, with respect to different values of ‘cut’.

#load ggplot2 package
library(ggplot2)

# Contour-colored violin plots
# diamonds dataframe being used here
ggplot(diamonds, aes(x=cut, y=price, color=cut)) +
  geom_violin()
Contour-colored violin plots

You can also fill the violin with different colors when plotting violin plots, see the following code example.

#load ggplot2 package
library(ggplot2)

# Color-filled violin plots
# diamonds dataframe being used here

ggplot(diamonds, aes(x=cut, y=price, fill=cut)) +
  geom_violin()

Color-filled violin plots

We can also show mean value location for each violin plot by setting a red point in the violin.

#load ggplot2 package
library(ggplot2)

# violin plots with mean value points
# diamonds dataframe being used here

ggplot(diamonds, aes(x=cut, y=price)) +
  geom_violin()+
  stat_summary(fun.y="mean", geom="point", size=2, color="red")
Violin plots with mean value points

Violin plots can also be plotted horizontally.

#load ggplot2 package
library(ggplot2)

# violin plots show horizontally
# diamonds dataframe being used here

ggplot(diamonds, aes(x=cut, y=price)) +
  geom_violin()+
  coord_flip()
Horizontal violin plots

You can also watch full video of R tutorials from our YouTube channel.