How to Make a Violin Plot in R (ggplot2 and vioplot)

Step-by-step R code for violin plots with ggplot2's geom_violin and the base-R vioplot package.

To make a violin plot in R, use geom_violin() from ggplot2: map a grouping variable to x and a numeric variable to y, then add layers such as a narrow boxplot or jittered points on top. If you prefer base graphics, the vioplot package draws violins with one function call. This guide covers both, plus the arguments that change how the shapes are drawn.

If you only need a chart and not a script, you can paste your numbers into our free violin plot maker and download the image. No R install or signup is needed.

A basic violin plot with ggplot2

ggplot2 ships with the mpg dataset, which is handy for testing. Each car has a class (compact, SUV and so on) and a highway fuel economy value in hwy.

library(ggplot2)

ggplot(mpg, aes(x = class, y = hwy)) +
  geom_violin()

Each violin is a kernel density estimate of hwy for one class, mirrored on both sides of a vertical axis. Wide parts show values where many cars sit. Narrow parts show values that are rare. If you are new to reading the shape, our guide on how to read a violin plot walks through it.

Your grouping variable should be a factor or character column. If it is numeric, such as a dose of 0.5, 1 and 2, wrap it in factor(). Otherwise ggplot2 treats it as continuous and you get a single violin or a warning.

ggplot(ToothGrowth, aes(x = factor(dose), y = len)) +
  geom_violin()

Fill by group

Map a variable to fill to colour the violins. Mapping the same variable as x gives each group its own colour. You can then hide the legend because the axis already labels the groups.

ggplot(mpg, aes(x = class, y = hwy, fill = class)) +
  geom_violin() +
  theme(legend.position = "none")

Mapping a second variable to fill dodges the violins side by side within each x position. In ToothGrowth, supp is the supplement type:

ggplot(ToothGrowth, aes(x = factor(dose), y = len, fill = supp)) +
  geom_violin(position = position_dodge(width = 0.9))

ggplot2 has no built-in split violin, where two groups share one violin with one half each. Add-on packages fill the gap, for example see::geom_violinhalf() draws half violins. Our page on the split violin plot explains when that layout helps.

Add a boxplot inside the violin

A violin shows shape but not exact summary values. A thin boxplot layered on top adds the median and quartiles. Keep the box narrow and turn off its outlier points, since those would duplicate data you may show another way.

ggplot(mpg, aes(x = class, y = hwy)) +
  geom_violin(fill = "grey85") +
  geom_boxplot(width = 0.1, outlier.shape = NA)

When you also use fill with dodging, give the boxplot the same dodge width as the violins, or the boxes will not line up:

dodge <- position_dodge(width = 0.9)

ggplot(ToothGrowth, aes(x = factor(dose), y = len, fill = supp)) +
  geom_violin(position = dodge) +
  geom_boxplot(width = 0.1, position = dodge, outlier.shape = NA,
               show.legend = FALSE)

For a side-by-side look at what each chart shows and hides, see violin plot vs box plot.

Add jittered points

With small samples, a smooth violin can suggest more certainty than the data supports. Showing the raw points fixes that. Use geom_jitter() with a small horizontal width and no vertical jitter, so the y values stay exact.

ggplot(mpg, aes(x = class, y = hwy)) +
  geom_violin(fill = "grey90") +
  geom_jitter(width = 0.1, height = 0, size = 1, alpha = 0.5)

The ggbeeswarm package offers geom_quasirandom(), which spreads points to follow the density instead of at random. More options are in our guide to a violin plot with points.

Arguments that change the shape

trim

trim = TRUE is the default. It cuts each violin at the smallest and largest observed value, which is why the ends often look flat. Set trim = FALSE to let the density tails run past the data. Untrimmed tails look smoother but can suggest values that never occurred, such as negative weights.

scale

scale controls how violins compare in size:

  • "area" (default): every violin has the same area.
  • "count": area is in proportion to the number of observations, so small groups look small.
  • "width": every violin has the same maximum width, which makes shapes easy to compare but hides sample size.

If your groups differ a lot in size, scale = "count" is the more honest choice.

adjust and bw (bandwidth)

The smoothness of the outline comes from the kernel bandwidth. adjust multiplies the default bandwidth: values below 1 show more detail and noise, values above 1 give a smoother outline. bw sets the bandwidth rule itself, with "nrd0" as the default.

ggplot(mpg, aes(x = class, y = hwy)) +
  geom_violin(adjust = 0.5)

Bandwidth can change the story a chart tells, for example by hiding or inventing a second peak. Our violin plot bandwidth guide shows the effect.

bounds

Recent versions of ggplot2 accept bounds, the known lower and upper limits of the data. For values that cannot go below zero, bounds = c(0, Inf) stops the density from leaking past zero. Points outside the bounds are dropped with a warning.

Quantile lines: draw_quantiles vs quantiles

This is where ggplot2 versions differ, so check yours with packageVersion("ggplot2").

ggplot2 4.0.0 and later: draw_quantiles is deprecated. The stat now computes quantiles through the quantiles argument, which defaults to the 25th, 50th and 75th percentiles. The lines are hidden by default because quantile.linetype is 0. Set it to a visible line type to show them:

# ggplot2 4.0.0 or later
ggplot(mpg, aes(x = class, y = hwy)) +
  geom_violin(quantile.linetype = 1)

# choose your own quantiles and styling
ggplot(mpg, aes(x = class, y = hwy)) +
  geom_violin(quantiles = c(0.1, 0.5, 0.9),
              quantile.linetype = "dashed",
              quantile.colour = "grey30")

ggplot2 3.5.x and earlier: use draw_quantiles. It still runs in 4.0 but gives a deprecation warning.

# ggplot2 3.5.x and earlier
ggplot(mpg, aes(x = class, y = hwy)) +
  geom_violin(draw_quantiles = c(0.25, 0.5, 0.75))

The older draw_quantiles lines were estimated from the density curve, so they could differ a little from the quartiles a boxplot shows. If exact figures matter, check them with quantile() or overlay a boxplot.

Horizontal violins and finishing touches

To draw violins horizontally, swap the mappings so the numeric variable is on x and the group is on y. ggplot2 works out the orientation. coord_flip() also works. Long category names are easier to read this way.

ggplot(mpg, aes(x = hwy, y = reorder(class, hwy, FUN = median))) +
  geom_violin(fill = "#9ecae1") +
  labs(x = "Highway miles per gallon", y = NULL) +
  theme_minimal()

ggsave("violin.png", width = 7, height = 5, dpi = 300)

reorder() sorts the groups by median, which often makes comparisons faster than alphabetical order.

Base R: the vioplot package

Base R has no violin function, but the vioplot package on CRAN adds one. It draws a violin with a small boxplot and median marker inside by default.

install.packages("vioplot")
library(vioplot)

# one vector per group
vioplot(mtcars$mpg[mtcars$cyl == 4],
        mtcars$mpg[mtcars$cyl == 6],
        mtcars$mpg[mtcars$cyl == 8],
        names = c("4 cyl", "6 cyl", "8 cyl"),
        col = "lightblue")

# formula interface in current versions
vioplot(len ~ dose, data = ToothGrowth, col = "lightgreen")

vioplot suits quick looks and scripts that already use base graphics. For layered charts, facets and themes, ggplot2 is the more flexible choice.

Common problems

  • One violin instead of several: the x variable is numeric. Wrap it in factor().
  • A group shows as a flat line or vanishes: it has too few points to estimate a density, or all its values are identical.
  • Boxplots drift away from the violins: the two layers use different dodge widths. Share one position_dodge() object.
  • Deprecation warning about draw_quantiles: you are on ggplot2 4.0 or later. Switch to quantile.linetype.

For the ideas behind density, bandwidth and when a violin is the right chart, see the complete violin plot guide. To compare results without code, make a violin plot online from the same numbers.

FAQ

Which R function makes a violin plot?

geom_violin() in ggplot2 is the most common choice. In base graphics, vioplot() from the vioplot package does the same job.

Why are the ends of my violins flat?

By default, trim = TRUE cuts the density at the minimum and maximum of the data. Set trim = FALSE to draw the full tails.

Is draw_quantiles still supported?

It is deprecated from ggplot2 4.0.0. It still works but warns. Use quantile.linetype and, if needed, quantiles instead.

How do I make violin size reflect sample size?

Use geom_violin(scale = "count"). Each violin’s area then grows with the number of observations in that group.

Can I make a violin plot without R?

Yes. Paste your values into the online violin plot tool, pick a style and download the chart.

Adrian Lee
Adrian Lee

Adrian Lee is the Data Visualization Specialist and Statistical Analyst at ViolinPlot. Based in Boston, Massachusetts, Adrian utilizes a robust background in statistics and data science to create compelling and insightful visualizations that help interpret complex data.

With extensive experience in data analysis and visualization techniques, Adrian specializes in developing violin plots and other advanced graphical representations to convey statistical information effectively. Adrian’s expertise includes statistical modeling, data interpretation, and the creation of interactive visualizations.

At ViolinPlot, Adrian is responsible for transforming raw data into visual narratives that are both informative and engaging.

By employing state-of-the-art visualization tools and statistical methods, Adrian ensures that the visual representations are accurate, clear, and valuable for decision-making processes.

Adrian’s dedication to enhancing data comprehension through visual tools has established ViolinPlot. As a leading resource for data visualization and statistical analysis.

Articles: 89

Ready to Unlock Deeper Data Insights?

Transform complex datasets into clear, interactive visualizations with Violin Plot. Start exploring data distributions in a way that empowers insight and drives smarter decisions.

LEARN MOre
100% satisfaction guaranteed
McAfee SECURE
ssl-secured
verisign-secured
BEST-PRICE-GUARANTEED-free-trust-badge
guaranteed-safe-checkout-1