Powered by AppSignal & Oban Pro

Violin plots: geom_violin

notebooks/geom_violin.livemd

Violin plots: geom_violin

Mix.install([
  {:giggly, path: Path.join(__DIR__, "..")},
  {:kino, "~> 0.19"}
  ])

alias Giggly.Plot

mtcars = Giggly.Datasets.mtcars()

render = fn plot ->
  plot
  |> Giggly.to_svg()
  |> IO.iodata_to_binary()
  |> Kino.Image.new(:svg)
end

About this notebook

This notebook follows the examples on ggplot2's reference page for geom_violin(), which covers stat_ydensity() too, in the order the page gives them. Each example shows ggplot2's code first and then Giggly's. An example Giggly cannot draw yet keeps its ggplot2 code and names what it is waiting for, so the page is also a list of what remains.

A violin plot is a compact display of a continuous distribution, a blend of a box plot and a density plot: each group's density estimate, mirrored, drawn where a box plot would draw its box. stat_ydensity() computes the densities, and geom_violin() draws them. Giggly has Giggly.Plot.geom_violin/3 and Giggly.Plot.stat_ydensity/3, which add the same layer, take ggplot2's options as keyword options (scale:, trim:, adjust:, quantiles: and the quantile lines' look), and set violins that share a position side by side, as ggplot2 does. It has no cut_width() and no coord_transform(). A plot is described with Giggly.Plot and drawn with Giggly.to_svg/2, which returns an SVG document. The setup cell aliases Giggly.Plot, so the cells write Plot.new/2, and defines render, which draws a plot and shows it below the cell with Kino.Image. The cells draw Giggly.Datasets.mtcars/0, R's mtcars: 32 cars from the 1974 Motor Trend US magazine, which the setup cell binds to mtcars.

Violins by number of cylinders

p <- ggplot(mtcars, aes(factor(cyl), mpg))
p + geom_violin()

Giggly writes factor(cyl) as {:factor, [:cyl]}.

p = Plot.new(mtcars, %{x: {:factor, [:cyl]}, y: :mpg})

p
|> Plot.geom_violin()
|> render.()

Horizontal violins

# Orientation follows the discrete axis
ggplot(mtcars, aes(mpg, factor(cyl))) +
  geom_violin()

Giggly's violins stand along the discrete axis too, here y.

Plot.new(mtcars, %{x: :mpg, y: {:factor, [:cyl]}})
|> Plot.geom_violin()
|> render.()

Violins with jittered points

p + geom_violin() + geom_jitter(height = 0, width = 0.1)

The points are jittered by Erlang's random numbers, not R's, so they land elsewhere than ggplot2's, each within the same 0.1 of its place across and none moved up or down; nothing else in the drawing moves (geom_jitter()'s notebook says more).

p
|> Plot.geom_violin()
|> Plot.geom_jitter(height: 0, width: 0.1)
|> render.()

Scaling the widths

# Scale maximum width proportional to sample size:
p + geom_violin(scale = "count")

# Scale maximum width to 1 for all violins:
p + geom_violin(scale = "width")

By default every violin has the same area, scale = "area".

p
|> Plot.geom_violin(scale: :count)
|> render.()
p
|> Plot.geom_violin(scale: :width)
|> render.()

Untrimmed tails

# Default is to trim violins to the range of the data. To disable:
p + geom_violin(trim = FALSE)
p
|> Plot.geom_violin(trim: false)
|> render.()

A smaller bandwidth

# Use a smaller bandwidth for closer density fit (default is 1).
p + geom_violin(adjust = .5)

adjust multiplies the bandwidth the density estimate would otherwise use.

p
|> Plot.geom_violin(adjust: 0.5)
|> render.()

Mapping fill

# Add aesthetic mappings
# Note that violins are automatically dodged when any aesthetic is
# a factor
p + geom_violin(aes(fill = cyl))
p + geom_violin(aes(fill = factor(cyl)))
p + geom_violin(aes(fill = factor(vs)))
p + geom_violin(aes(fill = factor(am)))

Mapping fill to something discrete that varies within each x, as factor(vs) does, splits a violin into one for each value, dodged side by side.

p
|> Plot.geom_violin(%{fill: :cyl})
|> render.()
p
|> Plot.geom_violin(%{fill: {:factor, [:cyl]}})
|> render.()
p
|> Plot.geom_violin(%{fill: {:factor, [:vs]}})
|> render.()
p
|> Plot.geom_violin(%{fill: {:factor, [:am]}})
|> render.()

A fixed fill and colour

# Set aesthetics to fixed value
p + geom_violin(fill = "grey80", colour = "#3366FF")

"grey80" is a colour only R names, so Giggly writes it as its hex, "#CCCCCC".

p
|> Plot.geom_violin(fill: "#CCCCCC", colour: "#3366FF")
|> render.()

Quartiles

# Show quartiles
p + geom_violin(draw_quantiles = c(0.25, 0.5, 0.75))

ggplot2 has deprecated draw_quantiles, in favour of quantiles and quantile.linetype, which draw the same violins: quantiles says where the lines go, and a quantile.linetype other than blank draws them. Giggly offers those alone, as quantiles: and quantile_linetype:.

p
|> Plot.geom_violin(quantiles: [0.25, 0.5, 0.75], quantile_linetype: :solid)
|> render.()

Scale and coordinate transformations

require() loads the ggplot2movies package, and the rest of the page's examples run only where it is installed. Its movies dataset holds films from the Internet Movie Database, with their rating, number of votes, year and budget.

# Scales vs. coordinate transforms -------
if (require("ggplot2movies")) {
# Scale transformations occur before the density statistics are computed.
# Coordinate transformations occur afterwards.  Observe the effect on the
# number of outliers.
m <- ggplot(movies, aes(y = votes, x = rating, group = cut_width(rating, 0.5)))
m + geom_violin()
m +
  geom_violin() +
  scale_y_log10()
m +
  geom_violin() +
  coord_transform(y = "log10")
m +
  geom_violin() +
  scale_y_log10() + coord_transform(y = "log10")

cut_width(rating, 0.5) groups the films into bins of rating half a point wide, a violin for each.

Not in Giggly yet: a whole-column function in a mapping, such as cut_width(rating, 0.5), cut_width(), coord_transform(), and the movies dataset from the ggplot2movies package.

Violins along a continuous x

# Violin plots with continuous x:
# Use the group aesthetic to group observations in violins
ggplot(movies, aes(year, budget)) +
  geom_violin()
ggplot(movies, aes(year, budget)) +
  geom_violin(aes(group = cut_width(year, 10)), scale = "width")
}

Not in Giggly yet: a whole-column function in a mapping, such as cut_width(year, 10), cut_width(), and the movies dataset from the ggplot2movies package.