ggplot2 Tutorial

Create clear, publication-ready charts with ggplot2

Scatter plots, bar charts, histograms, boxplots and more — plus themes, labels and exporting for reports.

ggplot2 cheat sheet Get help with your graphs

ggplot2 Density and Violin Plots in R: Complete Guide

Updated

This in-depth ggplot2 density and violin plot tutorial shows how to visualize numeric distributions in R. Learn kernel density estimation, bandwidth selection, grouped and filled density curves, bimodal distributions, violin plots, split-style comparisons, boxplot overlays, raw observations and advanced styling with practical examples and downloadable datasets.

This lesson is part of the ggplot2 tutorial. It uses the built-in mpg dataset from ggplot2 and downloadable practice datasets. Density plots and violin plots are both useful for understanding distributions, but they emphasize different visual summaries.

1. Density plots and violin plots in R: what is the difference?

A density plot displays a smooth estimate of a continuous variable's distribution. A violin plot mirrors a density shape around a central axis so that distributions can be compared across categories. In ggplot2, use geom_density() for density curves and geom_violin() for violin plots.

  • Density plot: useful for inspecting the shape, peaks, spread and skewness of one numeric variable.
  • Grouped density plot: compares distributions across categories using colour, fill or facets.
  • Violin plot: compares distribution shapes across groups in a compact category-based chart.
  • Violin with boxplot: combines density shape with median, quartiles and potential outliers.
  • Violin with raw points: reveals individual observations and helps assess whether a smooth shape is supported by the sample.
ggplot2 density plot showing a smooth kernel density estimate of a continuous participant age distribution
A kernel density curve summarizes the distribution without displaying individual histogram bins.

2. Create a basic density plot with geom_density()

Map a continuous numeric variable to x and add geom_density(). The mpg dataset includes highway fuel economy in hwy.

library(ggplot2)

ggplot(mpg, aes(x = hwy)) +
  geom_density()

Customize the line and labels to make the graph easier to interpret:

ggplot(mpg, aes(x = hwy)) +
  geom_density(
    colour = "#2878B5",
    linewidth = 1.2
  ) +
  labs(
    title = "Density plot of highway fuel economy",
    x = "Highway miles per gallon",
    y = "Density"
  ) +
  theme_minimal()

The y-axis represents probability density, not the number of cars. The total area under a standard density curve is approximately one.

3. Control density smoothing with bandwidth and adjust

A density plot uses kernel density estimation. The bandwidth controls how much smoothing is applied. A small bandwidth can produce a wavy curve that follows local variation; a large bandwidth can smooth away meaningful peaks.

Use adjust to modify automatic bandwidth

# More local detail
ggplot(mpg, aes(hwy)) +
  geom_density(adjust = 0.6)

# Standard automatic bandwidth
ggplot(mpg, aes(hwy)) +
  geom_density(adjust = 1)

# Smoother density curve
ggplot(mpg, aes(hwy)) +
  geom_density(adjust = 1.7)

Specify bandwidth directly

ggplot(mpg, aes(hwy)) +
  geom_density(
    bw = 2.5,
    colour = "#C44536",
    linewidth = 1.1
  )
Three density curves comparing narrow standard and broad bandwidth smoothing choices
Bandwidth changes the smoothness and apparent number of peaks. Choose it with the data and analytical question in mind.

Do not select a bandwidth solely to produce a preferred visual story. Compare sensible settings and, where appropriate, use subject knowledge or a documented bandwidth selection method.

4. Create filled density plots and customize colours

Use fill to colour the area below a density curve. Set alpha to control transparency and colour to style the outline.

ggplot(mpg, aes(hwy)) +
  geom_density(
    fill = "#90CAF9",
    colour = "#1565C0",
    alpha = 0.65,
    linewidth = 1
  ) +
  labs(
    title = "Filled density plot",
    x = "Highway miles per gallon",
    y = "Density"
  ) +
  theme_minimal()
Filled blue ggplot2-style density curve with a visible outline and density axis
Filled density plots make a single distribution visually prominent.

For a single fixed colour, place fill outside aes(). Mapping a variable to fill inside aes() creates a data-driven scale and usually a legend.

5. Compare density curves by group

Map a grouping variable to colour and fill to compare several distributions. The drv variable in mpg identifies drive type.

ggplot(mpg, aes(
  x = hwy,
  colour = drv,
  fill = drv
)) +
  geom_density(alpha = 0.16, linewidth = 1) +
  labs(
    title = "Highway fuel economy by drive type",
    x = "Highway miles per gallon",
    y = "Density",
    colour = "Drive type",
    fill = "Drive type"
  ) +
  theme_minimal()
Multiple coloured density curves comparing Control Program A and Program B score distributions
Overlaid density curves reveal differences in location, spread and shape.

When curves overlap heavily, transparency can help, but too many groups can make the graph difficult to read. Consider facets or a smaller set of meaningful categories.

6. Use facets for separate density plots

Faceting creates a separate panel for each group. It is often clearer than placing many filled curves on top of one another.

ggplot(mpg, aes(x = hwy)) +
  geom_density(
    fill = "#2878B5",
    alpha = 0.45,
    colour = "#1D4E89"
  ) +
  facet_wrap(~ drv) +
  labs(
    title = "Separate density plots by drive type",
    x = "Highway miles per gallon",
    y = "Density"
  ) +
  theme_minimal()

Use fixed scales for direct comparisons of density heights and ranges. Free scales can make the shape within each panel easier to inspect, but make comparisons across panels less direct.

7. Identify bimodal and multimodal distributions

A distribution with two peaks is called bimodal; one with several peaks is called multimodal. Multiple peaks can indicate subpopulations, mixtures, seasonal effects or other structure. They do not, by themselves, prove that separate populations exist.

ggplot(mpg, aes(x = hwy)) +
  geom_density(
    adjust = 0.8,
    fill = "#D8C8EA",
    colour = "#8064A2",
    linewidth = 1.2
  ) +
  labs(
    title = "Inspecting peaks in a distribution",
    x = "Highway miles per gallon",
    y = "Density"
  ) +
  theme_minimal()
Bimodal density plot with two distinct peaks illustrating a distribution with two concentrations of observations
A two-peaked density curve may motivate further investigation of subgroups or data-generating processes.

Check whether apparent peaks remain when reasonable bandwidths are used. Very small bandwidths can create artificial bumps.

8. Density polygons and cumulative distributions

For a polygon-style density display, use geom_density() with a filled area or use stat_density(geom = "area"). A cumulative density curve can be created with the after_stat(ecdf) statistic where supported by your ggplot2 version.

# Density area
ggplot(mpg, aes(hwy)) +
  stat_density(
    geom = "area",
    fill = "#A8DADC",
    alpha = 0.7
  ) +
  theme_minimal()

# Empirical cumulative distribution
ggplot(mpg, aes(hwy)) +
  stat_ecdf(
    geom = "step",
    colour = "#C44536",
    linewidth = 1
  ) +
  labs(x = "Highway miles per gallon",
       y = "Cumulative proportion") +
  theme_minimal()

An empirical cumulative distribution function (ECDF) is not a kernel density curve. It shows the proportion of observations less than or equal to each value and avoids bandwidth smoothing.

9. Create a violin plot with geom_violin()

A violin plot displays a mirrored density shape for each category. Map a categorical variable to x and a continuous variable to y.

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

Customize fill, outline and labels:

ggplot(mpg, aes(class, hwy, fill = class)) +
  geom_violin(
    colour = "grey25",
    alpha = 0.75,
    linewidth = 0.5
  ) +
  labs(
    title = "Violin plot of highway fuel economy",
    x = "Vehicle class",
    y = "Highway miles per gallon"
  ) +
  guides(fill = "none") +
  theme_minimal()
Violin plot comparing score distributions across Control Program A and Program B groups
Wider parts of a violin indicate greater estimated data density at those values.

10. Control violin width, scale and trimming

geom_violin() provides several options that affect how violin shapes are drawn.

  • width controls the maximum width of each violin.
  • scale = "area" scales violins to have comparable area.
  • scale = "count" also reflects the number of observations in each group.
  • scale = "width" gives each violin the same maximum width.
  • trim = TRUE trims the density to the range of observed data; FALSE allows the tails to extend beyond the observed range according to the density estimate.
  • adjust changes the density bandwidth multiplier.
# Equal maximum widths
ggplot(mpg, aes(class, hwy)) +
  geom_violin(scale = "width")

# Widths reflect sample counts
ggplot(mpg, aes(class, hwy)) +
  geom_violin(scale = "count")

# Untrimmed density tails
ggplot(mpg, aes(class, hwy)) +
  geom_violin(trim = FALSE)

Choose the scaling method according to the question. If sample sizes differ substantially, state whether width represents density shape or group size.

11. Combine violin plots with boxplots and summary statistics

A violin plot shows distribution shape, while a boxplot adds the median and quartiles. Combining the two provides a compact distribution summary.

ggplot(mpg, aes(class, hwy, fill = class)) +
  geom_violin(trim = FALSE, alpha = 0.6) +
  geom_boxplot(
    width = 0.12,
    fill = "white",
    outlier.shape = NA
  ) +
  guides(fill = "none") +
  theme_minimal()
Violin plots with narrow embedded boxplots showing distribution density median and quartiles for three groups
The violin shows distribution shape; the overlaid boxplot shows the median and interquartile range.

You can add a mean marker with stat_summary():

ggplot(mpg, aes(class, hwy)) +
  geom_violin(fill = "#BFD7EA", alpha = 0.65) +
  stat_summary(
    fun = mean,
    geom = "point",
    shape = 23,
    size = 3,
    fill = "#E07A32"
  ) +
  theme_minimal()

12. Show individual observations on violin plots

A smooth violin shape can hide the sample size and the actual observed values. Add jittered points or a beeswarm-style layer to reveal the raw data.

ggplot(mpg, aes(class, hwy)) +
  geom_violin(
    fill = "#A8DADC",
    alpha = 0.6
  ) +
  geom_jitter(
    width = 0.12,
    alpha = 0.3,
    size = 1.3
  ) +
  theme_minimal()
Violin plots with individual jittered observations overlaid to show sample values and distribution density
Raw points help readers assess how much information supports the estimated violin shape.

For larger datasets, use ggbeeswarm to reduce point overlap:

install.packages("ggbeeswarm")
library(ggbeeswarm)

ggplot(mpg, aes(class, hwy)) +
  geom_violin(fill = "grey90") +
  geom_quasirandom(width = 0.18, alpha = 0.45) +
  theme_minimal()

13. Split and half-violin comparisons

A split violin or half-violin display can compare two subgroups within each category while saving horizontal space. The standard geom_violin() creates complete violins; for split violins, use a dedicated extension package or carefully construct mirrored density layers.

One option is gghalves, which provides half-violin and half-point geoms.

install.packages("gghalves")
library(gghalves)

ggplot(scores, aes(x = group, y = score, fill = group)) +
  gghalves::geom_half_violin(
    side = "l",
    alpha = 0.65
  ) +
  gghalves::geom_half_point(
    side = "r",
    alpha = 0.35
  ) +
  theme_minimal()
Mirrored half violin density comparison showing Control and Program B distributions on opposite sides of a central axis
Half-violin layouts can compare two distributions compactly. The example is a conceptual mirrored comparison.

Extension-package functions and arguments can vary by package version. Check the package documentation if a function is unavailable in your installation.

14. Advanced density and violin plot styling

Use facets, scales, palettes, labels and themes to make distribution plots publication-ready.

Manual group colours

ggplot(scores, aes(score, colour = group, fill = group)) +
  geom_density(alpha = 0.12, linewidth = 1) +
  scale_colour_manual(values = c(
    "Control" = "#2878B5",
    "Program A" = "#E07A32",
    "Program B" = "#2A9D8F"
  )) +
  scale_fill_manual(values = c(
    "Control" = "#2878B5",
    "Program A" = "#E07A32",
    "Program B" = "#2A9D8F"
  )) +
  theme_minimal()

Ridgeline-style distribution comparison

For many groups, overlapping density curves may become difficult to read. A ridgeline plot stacks density shapes vertically. The ggridges package provides geom_density_ridges().

install.packages("ggridges")
library(ggridges)

ggplot(scores, aes(x = score, y = group, fill = group)) +
  geom_density_ridges(alpha = 0.7, scale = 1.1) +
  guides(fill = "none") +
  theme_minimal()
Ridgeline-style stacked density visualization comparing distributions across three groups
Ridgeline plots are useful for comparing many distributions across ordered or named groups.

Use meaningful axis labels, a clear legend and an appropriate scale. Avoid excessive transparency or too many overlapping groups.

15. Download density and violin plot practice datasets

Use these fictional datasets to practise density estimation, bandwidth selection, violin plots and group comparisons. They are demonstration data, not real participant, employee or student records.

ages <- read.csv("participant_ages.csv")

ggplot(ages, aes(participant_age)) +
  geom_density(
    fill = "#90CAF9",
    alpha = 0.6,
    adjust = 1
  ) +
  theme_minimal()

Compare scores by group:

scores <- read.csv("group_scores.csv")

ggplot(scores, aes(group, score, fill = group)) +
  geom_violin(trim = FALSE) +
  geom_boxplot(width = 0.12, fill = "white",
               outlier.shape = NA) +
  guides(fill = "none") +
  theme_minimal()

16. Interactive density and violin distribution explorer

Change the distribution and smoothing level to see how the estimated density curve responds. This browser-based teaching illustration uses a fixed set of example observations; use R and ggplot2 for statistical analysis.

17. Common mistakes and practice exercises

Common density plot mistakes

  • Interpreting density as count: density is a probability density scale, not a frequency count.
  • Choosing an extreme bandwidth: too little smoothing can create artificial bumps; too much can hide structure.
  • Overlapping too many groups: use facets or ridgeline plots when the legend and curves become crowded.
  • Comparing unequal samples without context: density curves emphasize distribution shape, not group sample size.

Common violin plot mistakes

  • Ignoring sample size: a smooth violin can look convincing even when based on few observations. Overlay raw points where useful.
  • Misreading violin width: width represents estimated density, not the number of observations unless the scaling is configured to reflect count.
  • Over-interpreting tails: density estimates near the data boundaries can be sensitive to bandwidth and trimming.
  • Using too many groups: use facets or a more focused comparison to maintain readability.

Practice exercises

  1. Create a density plot of mpg$hwy and label both axes.
  2. Compare adjust = 0.6, 1 and 1.7. Describe how the number and location of peaks appear to change.
  3. Use drv to compare density curves by vehicle drive type.
  4. Create a faceted density plot with one panel per drive type.
  5. Use geom_violin() to compare highway fuel economy across vehicle classes.
  6. Overlay a narrow boxplot and jittered points on a violin plot.
  7. Compare scale = "area", "count" and "width" for the same grouped data.
  8. Use the bimodal practice dataset to investigate whether two peaks remain under several reasonable bandwidths.
  9. Create a ridgeline plot using ggridges for the department and level data.

Continue learning ggplot2

Density plots and violin plots complement histograms and boxplots. Explore the other lessons in the ggplot2 tutorial to learn more ways to visualize and compare distributions.

ggplot2 FAQ

What does geom_density() show in ggplot2?

geom_density() estimates a continuous distribution using kernel density estimation and displays the estimated probability density as a smooth curve.

What is a violin plot in ggplot2?

A violin plot uses a mirrored density shape to show the distribution of a numeric variable across one or more categories.

What is the difference between a density plot and a histogram?

A histogram groups observations into bins and displays counts or density. A density plot displays a smoothed kernel estimate of the distribution.

How do I change the smoothing of a ggplot2 density plot?

Use bw to set a bandwidth directly or adjust to multiply the automatically selected bandwidth. Smaller bandwidths show more local detail; larger bandwidths create smoother curves.

How do I compare density plots by group?

Map a categorical variable to colour and fill inside aes(), then add geom_density() with transparency or facet the groups into separate panels.

How do I create a violin plot with ggplot2?

Map a category to x and a numeric variable to y, then add geom_violin(), for example ggplot(mpg, aes(class, hwy)) + geom_violin().

How do I combine a violin plot and boxplot?

Add geom_violin() followed by a narrow geom_boxplot() layer. The violin displays distribution shape while the boxplot shows quartiles and median.

What do width and scale mean in geom_violin()?

width controls the overall violin width. The scale argument controls how widths are scaled across groups; common choices include area, count and width.

Are violin plots suitable for small samples?

They can be drawn for small samples, but the estimated density may be unstable or misleading. Overlay individual observations and interpret the shape cautiously.