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

A Box plot shows descriptive statistics of a continuous with a box and whispers. Five statistics of the variable, namely, the minimum and the maximum, the median, and the lower quantile and upper quantile are depicted in the plot. A violin plot shows a smoothed nonparametric violin curve of a continuous variable. Combination of a box plot and a violin plot can perfectly illustrate the statistics and distribution of a continuous both graphically and numerically.

With ggplot2 package in R, we can adapt a box plot inside a violin plot easily with function geom_boxplot() and geom_violin().The example shows that a box plot is adapt and plotted inside a violin plot.

#             www.rdatacode.com
#To plot a boxplot inside a violin plot using R
#to load library ggplot2
library(ggplot2)

#we create a data frame motor by using data frame mpg 
#with R default installation, while excluding observations
#with cyl equal 5, as there are too few observations in
#this category
motor <- mpg[mpg$cyl != 5, ]

#then we set variable cty to factor, because ggplot2 will
#use categorical variables as groupppng.
motor$cyl <- factor(motor$cyl)

#then we plot a violin plot, with a box plot inside,
#we set the size of box plot, and transparency of the 
#violin plot
ggplot(motor, aes(x=cyl, y=cty)) +
  geom_boxplot(width=0.3,
               fill="steelblue") +
  geom_violin(fill="yellow",
              alpha=0.5) +
  labs(x="Number of cyl",
       y="Driving Distance in Mile",
       title="Combination of a Violin plot and a Box plot")
Combination of a Box plot and a Violin plot

You can also learn R programming from our YouTube channel.


0 Comments

Leave a Reply

Avatar placeholder