# Data Visualization using GGPlot2

## GGPlot Violin Plot A Violin Plot is used to visualize the distribution of the data and its probability density.

This chart is a combination of a Box plot and a Density Plot that is rotated and placed on each side, to display the distribution shape of the data.

Typically, violin plots will include a marker for the median of the data and a box indicating the interquartile range, as in standard boxplots.

A Violin Plot shows more information than a Box Plot. For example, in a violin plot, you can see whether the distribution of the data is bimodal or multimodal.

This article describes how to create and customize violin plots using the ggplot2 R package.

Contents:

#### Related Book

GGPlot2 Essentials for Great Data Visualization in R

## Key R functions

Key function:

• geom_violin(): Creates violin plots. Key arguments:
• color, size, linetype: Border line color, size and type
• fill: Areas fill color
• trim: logical value. If TRUE (default), trim the tails of the violins to the range of the data. If FALSE, don’t trim the tails.
• stat_summary(): Adds summary statistics (mean, median, …) on the violin plots.

## Data preparation

• Demo dataset: ToothGrowth
• Continuous variable: len (tooth length). Used on y-axis
• Grouping variable: dose (dose levels of vitamin C: 0.5, 1, and 2 mg/day). Used on x-axis.

First, convert the variable dose from a numeric to a discrete factor variable:

data("ToothGrowth")
ToothGrowth$dose <- as.factor(ToothGrowth$dose)
head(ToothGrowth, 4)
##    len supp dose
## 1  4.2   VC  0.5
## 2 11.5   VC  0.5
## 3  7.3   VC  0.5
## 4  5.8   VC  0.5

Load the ggplot2 package and set the default theme to theme_classic() with the legend at the top of the plot:

library(ggplot2)
theme_set(
theme_classic() +
theme(legend.position = "top")
)

## Basic violin plots

We start by initiating a plot named e, then we’ll add layers. The following R code creates Violin Plots combined with summary statistics (mean +/- SD) and Box Plots.

Create basic violin plots with summary statistics:

# Initiate a ggplot
e <- ggplot(ToothGrowth, aes(x = dose, y = len))

# Add mean points +/- SD
# Use geom = "pointrange" or geom = "crossbar"
e + geom_violin(trim = FALSE) +
stat_summary(
fun.data = "mean_sdl",  fun.args = list(mult = 1),
geom = "pointrange", color = "black"
)

# Combine with box plot to add median and quartiles
# Change fill color by groups, remove legend
e + geom_violin(aes(fill = dose), trim = FALSE) +
geom_boxplot(width = 0.2)+
scale_fill_manual(values = c("#00AFBB", "#E7B800", "#FC4E07"))+
theme(legend.position = "none") The function mean_sdl is used for adding mean and standard deviation. It computes the mean plus or minus a constant times the standard deviation. In the R code above, the constant is specified using the argument mult (mult = 1). By default mult = 2. The mean +/- SD can be added as a crossbar or a pointrange.

## Create a Violin Plot with multiple groups

Two different grouping variables are used: dose on x-axis and supp as line color (legend variable).

The space between the grouped plots is adjusted using the function position_dodge().

e + geom_violin(aes(color = supp), trim = FALSE, position = position_dodge(0.9) ) +
geom_boxplot(aes(color = supp), width = 0.15, position = position_dodge(0.9)) +
scale_color_manual(values = c("#00AFBB", "#E7B800")) ## Conclusion

This article describes how to create a Violin Plot using the ggplot2 package.
{"ft_lang_label":"__label__en","ft_lang_prob":0.64508384,"math_prob":0.9769414,"size":3425,"snap":"2019-51-2020-05","text_gpt3_token_len":918,"char_repetition_ratio":0.107863195,"word_repetition_ratio":0.010791367,"special_character_ratio":0.26569343,"punctuation_ratio":0.14352573,"nsfw_num_words":0,"has_unicode_error":false,"math_prob_llama3":0.99491066,"pos_list":[0,1,2,3,4,5,6,7,8,9,10],"im_url_duplicate_count":[null,1,null,5,null,5,null,5,null,null,null],"WARC_HEADER":"{\"WARC-Type\":\"response\",\"WARC-Date\":\"2019-12-07T19:05:11Z\",\"WARC-Record-ID\":\"<urn:uuid:05146e34-9014-42ba-b76a-649d1240ab50>\",\"Content-Length\":\"76930\",\"Content-Type\":\"application/http; msgtype=response\",\"WARC-Warcinfo-ID\":\"<urn:uuid:148eb2bd-f523-4059-ba7a-360c0900b4a3>\",\"WARC-Concurrent-To\":\"<urn:uuid:23211356-1eb5-4974-af8b-1bd6e6d0399e>\",\"WARC-IP-Address\":\"188.130.25.102\",\"WARC-Target-URI\":\"https://www.datanovia.com/en/lessons/ggplot-violin-plot/\",\"WARC-Payload-Digest\":\"sha1:KEJRVOM4MVET5LTFCKELEBTWVKTX3OY2\",\"WARC-Block-Digest\":\"sha1:DHEAMPOVO6DWJFM4KTGA2R3ZZHZPYZYM\",\"WARC-Identified-Payload-Type\":\"text/html\",\"warc_filename\":\"/cc_download/warc_2019/CC-MAIN-2019-51/CC-MAIN-2019-51_segments_1575540501887.27_warc_CC-MAIN-20191207183439-20191207211439-00472.warc.gz\"}"}