Skip to main content
v2026.11,986 entries · CC-BY 4.0

Violin Plot in R: geom_violin Syntax, Scaling and Overlays

Learn how to build, customize, and interpret a violin plot in R with ggplot2 geom_violin(), including scaling, smoothing bandwidths, and boxplot overlays.

Written and maintained by CASRAI Editorial Board

Published · Last updated

On this page

A violin plot r workflow provides a compact, continuous distribution visualization by mirroring a smoothed kernel density estimate across a categorical axis. By combining the summary statistics of a box plot with the full distribution profile of a density trace, an r violin plot reveals skewness, multimodality, and data clusters that standard summary metrics conceal. Whether referred to as a violinplot r script or a violin plot in r, the technique is an essential component of reproducible exploratory data analysis.

Ask CASRAI · free to tryQuestion about this guide? Ask CASRAI answers with linked sources. 2 free questions a day, no account.

Ask your first question freeSubscribe

What it is used for in research

Researchers across biomedical sciences, genomics, psychology, and ecological modeling use violin plots in r to compare continuous response variables across experimental treatments, clinical cohorts, or observational groups. While summary tables and standard bar charts reduce complex distributions to a single mean and standard error, violin plots r show the complete shape of the data. First formalized by Hintze and Nelson in 1998, the violin plot addresses a fundamental risk in exploratory data analysis: two experimental cohorts can share identical means and medians while possessing completely different underlying structures, such as bimodal sub-populations or severe skew.

Common research applications include:

  • Single-cell and Bulk RNA Sequencing: Comparing normalized gene expression values across cell types or treatment conditions, where zero-inflation and bimodal expression states frequently occur.
  • Clinical Trial Biometrics: Visualizing biomarker concentrations across patient cohorts to detect responder vs non-responder subpopulations.
  • Cognitive Psychology and Neuroscience: Displaying reaction time distributions, which typically exhibit positive skew and heavy right-side tails.
  • Environmental Field Surveys: Assessing pollutant concentrations or species abundance measurements across varying geographical sampling sites.

When not to use a violin plot: Violin plots rely on kernel density estimation, which requires adequate sample sizes to construct reliable probability density estimates. When group sample sizes fall below approximately 30 observations per group (N < 30), kernel density estimation can introduce artificial modes or smooth out meaningful discrete patterns. For small sample sizes, researchers should plot individual data points directly using a strip plot or combine raw observations with half-density shapes using a raincloud plot. Researchers working primarily in Python can implement comparable density visualizations using seaborn violin plots.

How to install or access it

In R, the standard and most flexible tool for producing violin plots is the ggplot2 package, maintained by Posit and the tidyverse team. You can install ggplot2 directly from the Comprehensive R Archive Network (CRAN) or install the complete tidyverse ecosystem.

# Install ggplot2 from official CRAN mirror
install.packages("ggplot2")

# Alternatively, install the complete tidyverse suite
install.packages("tidyverse")

# Optional: Base R violin plot package from CRAN
install.packages("vioplot")

After installation, load the library into your R session:

library(ggplot2)

Step-by-step instructions

The following reproducible workflow demonstrates how to construct, refine, and interpret a ggplot2 violin plot in R using the built-in ToothGrowth experimental dataset, which measures odontoblast cell length (len) across three vitamin C dose levels (dose).

1. Prepare and inspect the data

Ensure that the grouping variable on the x-axis is encoded as a discrete factor rather than a continuous numeric vector. If the categorical variable remains numeric, ggplot2 will attempt to compute density along a continuous scale rather than per category.

# Load built-in research dataset
data("ToothGrowth")

# Convert dose to factor for categorical grouping
ToothGrowth$dose <- factor(ToothGrowth$dose, levels = c(0.5, 1.0, 2.0))

# Verify data structure
str(ToothGrowth)

2. Create a basic ggplot violin plot

Initialize the plot using ggplot(), specify aesthetic mappings (aes(x = dose, y = len)), and add the geom_violin() geometry layer to generate a basic ggplot violin plot.

# Basic violin plot in R using ggplot2
p_basic <- ggplot(ToothGrowth, aes(x = dose, y = len)) +
  geom_violin() +
  labs(
    title = "Tooth Growth Distribution Across Vitamin C Doses",
    x = "Dose Level (mg/day)",
    y = "Odontoblast Length (microns)"
  ) +
  theme_minimal()

print(p_basic)

3. Configure kernel density scaling and trimming

The default geom_violin() behavior sets trim = TRUE and scale = "area". When generating a violin plot r figure, customize these parameters according to experimental needs:

  • scale = "count": Scales violin width proportionally to the number of observations in each group, preventing readers from assuming groups have equal sample sizes.
  • scale = "width": Sets the maximum width of all violins to equal dimensions regardless of sample count or density area.
  • trim = FALSE: Extends the density estimation beyond the observed minimum and maximum values. Keep trim = TRUE if measurements have strict physical boundaries.
  • bounds = c(lower, upper): Enforces rigid support limits, preventing density traces from bleeding into impossible ranges (such as negative values).
# Customized violin plot with count scaling and bounds
p_custom <- ggplot(ToothGrowth, aes(x = dose, y = len, fill = dose)) +
  geom_violin(
    scale = "count",
    trim = TRUE,
    bounds = c(0, Inf),
    alpha = 0.6
  ) +
  labs(
    title = "Dose-Dependent Tooth Growth with Count Scaling",
    x = "Dose (mg/day)",
    y = "Length (microns)"
  ) +
  theme_classic() +
  theme(legend.position = "none")

print(p_custom)

4. Overlay an embedded box plot

A bare violin plot shows distribution shape but obscures precise quartiles and median values. Adding an embedded box plot inside each violin provides exact parametric and non-parametric reference markers. Set outlier.shape = NA in geom_boxplot() to prevent outlier points from being plotted twice when combined with point layers.

# Violin plot with embedded boxplot
p_box <- ggplot(ToothGrowth, aes(x = dose, y = len, fill = dose)) +
  geom_violin(trim = TRUE, alpha = 0.5, scale = "area") +
  geom_boxplot(
    width = 0.15,
    fill = "white",
    color = "black",
    outlier.shape = NA,
    alpha = 0.8
  ) +
  labs(
    title = "Violin Plot with Embedded Boxplot Quartiles",
    x = "Dose (mg/day)",
    y = "Length (microns)"
  ) +
  theme_minimal() +
  theme(legend.position = "none")

print(p_box)

5. Overlay jittered raw data points

For complete reporting transparency, overlay jittered raw observation points using geom_jitter(). This allows peer reviewers to evaluate sample density directly alongside the smoothed violin envelope.

# Violin plot with boxplot and jittered observations
p_jitter <- ggplot(ToothGrowth, aes(x = dose, y = len, fill = dose)) +
  geom_violin(trim = TRUE, alpha = 0.4, scale = "width") +
  geom_boxplot(width = 0.12, fill = "white", outlier.shape = NA, alpha = 0.7) +
  geom_jitter(
    position = position_jitter(width = 0.08, seed = 42),
    size = 1.8,
    alpha = 0.6,
    color = "#2c3e50"
  ) +
  labs(
    title = "Tooth Growth: Violins, Quartiles, and Individual Replicates",
    x = "Dose (mg/day)",
    y = "Length (microns)"
  ) +
  theme_classic() +
  theme(legend.position = "none")

print(p_jitter)

6. Build grouped and horizontal violin plots

To analyze factorial experimental designs (such as delivery supplement supp across doses) in a violin plot in r, map the secondary factor to the fill aesthetic. To orient the plot horizontally for easier label reading, flip the aesthetic mapping or add coord_flip().

# Grouped violin plot comparing delivery methods across doses
p_grouped <- ggplot(ToothGrowth, aes(x = dose, y = len, fill = supp)) +
  geom_violin(position = position_dodge(0.8), alpha = 0.6, trim = TRUE) +
  geom_boxplot(
    position = position_dodge(0.8),
    width = 0.15,
    outlier.shape = NA,
    alpha = 0.8
  ) +
  scale_fill_manual(
    name = "Supplement",
    values = c("OJ" = "#e67e22", "VC" = "#2980b9"),
    labels = c("Orange Juice", "Ascorbic Acid")
  ) +
  labs(
    title = "Grouped Violin Plot: Vitamin C Delivery and Dose Effect",
    x = "Dose (mg/day)",
    y = "Odontoblast Length (microns)"
  ) +
  theme_minimal()

print(p_grouped)

Output and how to read it

Interpreting a violin plot ggplot2 visualization requires evaluating both the external density contour and any internal summary statistics:

  • Violin Width and Contour: The horizontal width of the violin at any given y-axis value represents the relative probability density of data at that measurement value. Bulges indicate modes (frequently occurring values), while narrow necks indicate intervals where few observations fall. Multiple distinct bulges signify a multimodal distribution, which points to distinct subpopulations or mixed experimental responses.
  • Embedded Box Plot Elements: The internal white or shaded box displays the interquartile range (IQR, extending from the 25th percentile Q1 to the 75th percentile Q3). The bold line inside the box marks the median (50th percentile). Whiskers extend to the most extreme data points within 1.5 × IQR of the hinges.
  • Symmetry vs Skewness: An asymmetric violin silhouette indicates skewness in the observed variable. Longer upper tails indicate positive skew, while heavier lower contours indicate negative skew.
  • Density vs Binned Frequencies: Unlike a discrete histogram that groups data into fixed width bins, a violin plot applies continuous kernel smoothing. Researchers comparing multiple series across time or conditions can also evaluate density shifts using ridgeline plots.
  • Scale Interpretation: When generated with scale = "count", the total surface area of each violin reflects the sample size of that respective cohort. When using scale = "area", all violins occupy equal visual area regardless of sample size differences.

Troubleshooting

When compiling a violinplot r workflow or custom ggplot2 violin plot, researchers frequently encounter syntax warnings and rendering discrepancies. The checklist below addresses the most common issues based on official ggplot2 documentation:

1. Deprecation warning for draw_quantiles

Symptom: Warning: The `draw_quantiles` argument of `geom_violin()` is deprecated as of ggplot2 4.0.0. Please use the `quantile.linetype` argument instead.
Fix: In modern ggplot2, replace draw_quantiles = c(0.25, 0.5, 0.75) with the new quantile styling parameters (quantiles = c(0.25, 0.5, 0.75), quantile.linetype = "dashed", quantile.colour = "black"), or overlay geom_boxplot(width = 0.1) which provides standard quartile markers.

2. Outlier observations plotted twice

Symptom: Outlier points appear darker or duplicated on top of jittered points.
Fix: When combining geom_boxplot() with geom_jitter(), set outlier.shape = NA in geom_boxplot(). If omitted, ggplot2 draws outlier points once as part of the boxplot geometry and a second time as part of the jitter layer.

3. Density tails extending into impossible negative values

Symptom: Biological measurements (e.g. cell counts, concentrations, reaction times) display tails reaching below zero.
Fix: By default, Gaussian kernel density estimation extends into tails. Ensure trim = TRUE is active to clip the density trace at the minimum and maximum observed data points. Alternatively, supply explicit support boundaries via bounds = c(0, Inf) in geom_violin().

4. Error: stat_ydensity requires an x or y aesthetic

Symptom: Error: stat_ydensity requires the following missing aesthetics: x or y or unseparated violins.
Fix: If your x-variable is stored as a continuous numeric column (e.g. dose: 0.5, 1, 2), convert it to a discrete factor with as.factor(x) or specify aes(group = x) within ggplot().

5. Over-smoothing hides meaningful multi-modal peaks

Symptom: The violin appears completely smooth, masking known sub-population clusters.
Fix: The smoothing bandwidth is controlled by the adjust parameter (which multiplies the default Silverman bandwidth). Reduce the bandwidth multiplier to geom_violin(adjust = 0.5) to resolve fine multi-modal detail, or increase to adjust = 1.5 if sampling noise creates artificial modes.

Free alternatives

While ggplot2::geom_violin is the predominant implementation for generating a violin plot in r, researchers can select from several open-source libraries depending on visualization goals and graphic engine constraints.

Library / Tool Environment Syntax Style Key Capabilities Best Research Use Case
ggplot2 (geom_violin) R (CRAN) Grammar of Graphics Full aesthetic mapping, count scaling, quantile styling, facet integration Standard multi-group exploratory data analysis and publication figures
vioplot R (CRAN) Base R Graphics Lightweight, no tidyverse dependencies, native base plotting integration Base graphics pipelines, minimal scripting environments, lightweight workflows
gghalves / ggdist R (CRAN) ggplot2 Extension Half-violin shapes, slab intervals, raincloud plot composition Publishing figures that pair half-density curves directly with raw data points
ggridges R (CRAN) ggplot2 Extension Ridge density traces along a continuous or categorical timeline Visualizing distribution evolution across longitudinal time points or continuous scales
lattice (bwplot) R (Base recommended) Trellis Graphics Panel conditioning, multi-panel formula syntax via panel.violin High-throughput panel conditioning across multi-dimensional experimental factors
Seaborn (sns.violinplot) Python (PyPI) Matplotlib wrapper Split violins for binary conditions, inner quartile options, Hue grouping Python-based computational biology, data science, and PyData analytical stacks

FAQ

What is the difference between a violin plot and a box plot?

A box plot displays five summary statistics: the minimum, first quartile (Q1), median, third quartile (Q3), and maximum, along with potential outlier points. A violin plot includes these summary statistics but adds a mirrored kernel density estimate on both sides. This reveals distribution shape, multimodality, and skewness that box plots conceal.

When should researchers avoid using a violin plot in R?

Violin plots should be avoided when sample sizes are small (typically fewer than 30 observations per group, N < 30). Kernel density estimators require sufficient data points to estimate local probability density accurately; with small samples, density estimates can introduce misleading artificial modes. In small cohorts, a strip plot with jittered points or a raincloud plot is more appropriate; in base R, stripchart() in base R draws the jittered version.

What does scale = “count” do in geom_violin?

By default, scale = "area" gives all violins the same total area, making groups look identical in sample size. Setting scale = "count" scales each violin’s maximum area proportionally to the number of observations in that group, visually conveying cohort size differences.

Why do the tails of my violin plot extend past my minimum and maximum values?

This occurs when trim = FALSE or when the default Gaussian smoothing kernel calculates probability density beyond the observed data range. To restrict the violin strictly to observed data limits, set trim = TRUE (the ggplot2 default) or define explicit cutoff limits using bounds = c(min, max).

How do I rotate a violin plot horizontally in R?

In modern ggplot2, you can create a horizontal violin plot by swapping the aesthetic mappings (assigning the numeric response to x and the categorical grouping to y). Alternatively, add coord_flip() to any existing vertical violin plot.

How do I prevent outliers from appearing twice when adding a boxplot to a violin plot?

When overlaying geom_boxplot() on top of geom_violin() with jittered points, set outlier.shape = NA in geom_boxplot(). This suppresses the boxplot’s default outlier markers so individual points are only drawn once by the jitter layer.

Sources

All specifications, syntax arguments, and methodological rules cited in this guide were verified against official documentation and foundational literature:

Follow CASRAI

Research-administration guidance, standards updates and independent tool reviews.

Ask CASRAI · free to try

Ask about Violin Plot in R: geom_violin Syntax, Scaling and Overlays

2 free questions a day, no account.

An AI assistant for research: funder rules, compliance, methods and publishing. It links the sources behind its answers and labels answers that come from a web search.

Answers draw on CASRAI's guides and dictionary plus the federal and funder documents we index: Federal Register, Grants.gov, Regulations.gov and UKRI.

Works on this site and inside Claude, Cursor and the AI tools you already use.

Everything CASRAI publishes — this page, the dictionary, the guides and the news — stays open to read, with no account and no card.

Referenced across the research world

University of Cambridge logoColumbia University logoCrossref logoUniversity of Edinburgh logoHarvard University logoUniversity of Oxford logoPrinceton University logoStanford School of Medicine logoUniversity College London logoORCID logoUniversity of Cambridge logoColumbia University logoCrossref logoUniversity of Edinburgh logoHarvard University logoUniversity of Oxford logoPrinceton University logoStanford School of Medicine logoUniversity College London logoORCID logo
  • University of Cambridge logo
  • Columbia University logo
  • Crossref logo
  • University of Edinburgh logo
  • Harvard University logo
  • University of Oxford logo
  • Princeton University logo
  • Stanford School of Medicine logo
  • University College London logo
  • ORCID logo

View CASRAI adoption →