Plots
  • Introduction
  • Ⅰ.load the data and install packages
    • 0.load the data and install packages
  • Ⅱ.Plots
    • 1.Box plots
    • 2.Violin plots
    • 3.Histogram plots
    • 4.Density plots
    • 5.Dot plots
    • 6.Scatter plots
    • 7.Volcano plots
    • 8.Manhattan plots
    • 9.Heatmaps
    • 10.Ballon plots
    • 11.Vennpie plots
    • Learn more
Powered by GitBook
On this page
  • 2.1 Basic violin plot
  • 2.2 Add summary statistics on a violin plot
  • 2.2.1 Add median and quartile
  • 2.2.2 Add mean and standard deviation
  • 2.3 Change violin plot fill colors

Was this helpful?

  1. Ⅱ.Plots

2.Violin plots

Previous1.Box plotsNext3.Histogram plots

Last updated 6 years ago

Was this helpful?

2.1 Basic violin plot

df$cyl <- as.factor(df$cyl)
head(df)
##                    mpg cyl    wt
## Mazda RX4         21.0   6 2.620
## Mazda RX4 Wag     21.0   6 2.875
## Datsun 710        22.8   4 2.320
## Hornet 4 Drive    21.4   6 3.215
## Hornet Sportabout 18.7   8 3.440
## Valiant           18.1   6 3.460
ggplot(df, aes(x=cyl, y=mpg)) +
    geom_violin(trim=FALSE) +
    labs(title="Plot of mpg per cyl", x="Cyl", y = "Mpg")

2.2 Add summary statistics on a violin plot

2.2.1 Add median and quartile

ggplot(df, aes(x=cyl, y=mpg)) + 
  geom_violin(trim=FALSE) +
  labs(title="Plot of mpg per cyl", x="Cyl", y = "Mpg") +
  stat_summary(fun.y=mean, geom="point", shape=23, size=2, color="red")
#or
ggplot(df, aes(x=cyl, y=mpg)) + 
  geom_violin(trim=FALSE) +
  labs(title="Plot of mpg per cyl", x="Cyl", y = "Mpg") +
  geom_boxplot(width=0.1)

2.2.2 Add mean and standard deviation

ggplot(df, aes(x=cyl, y=mpg)) + 
  geom_violin(trim=FALSE) +
  labs(title="Plot of mpg per cyl", x="Cyl", y = "Mpg") +
  stat_summary(fun.data="mean_sdl", fun.args = list(mult = 1), geom="crossbar", width=0.1 )
#or
ggplot(df, aes(x=cyl, y=mpg)) + 
  geom_violin(trim=FALSE) +
  labs(title="Plot of mpg per cyl", x="Cyl", y = "Mpg") +
  stat_summary(fun.data=mean_sdl, fun.args = list(mult = 1), geom="pointrange", color="red")

2.3 Change violin plot fill colors

ggplot(df, aes(x=cyl, y=mpg, fill=cyl)) + 
  geom_violin(trim=FALSE) +
  geom_boxplot(width=0.1, fill="white") +
  labs(title="Plot of mpg per cyl", x="Cyl", y = "Mpg") +
  scale_fill_brewer(palette="Blues") + 
  theme_classic()

Reference:

http://www.sthda.com/english/wiki/ggplot2-violin-plot-quick-start-guide-r-software-and-data-visualization