ggplot2: why are side-by-side boxplots not being plotted?

Viewed 68
set.seed(3)
df <- data.frame(lambda = c(rep(0, 6), rep(1, 6), rep(1.5, 6)),
                 approach = rep(c(rep("A", 3), rep("B", 3)), 3),
                 value = rnorm(18, 0, 1))

ggplot(data = df, aes(x = lambda, y = value)) + geom_boxplot(aes(fill = approach))

enter image description here

I want to plot 3 sets of boxplots at lambda = 0, 1, and 1.5, respectively. Within each set are 2 boxplots, one corresponds to approach A and the other to approach B. However, the current code is only plotting two boxplots, whereas I'm looking for a total of six.

1 Answers

I think you want "lambda" to be a factor, e.g.

library(tidyverse)
set.seed(3)
df <- data.frame(lambda = c(rep(0, 6), rep(1, 6), rep(1.5, 6)),
                 approach = rep(c(rep("A", 3), rep("B", 3)), 3),
                 value = rnorm(18, 0, 1))

ggplot(data = df, aes(x = factor(lambda), y = value)) +
  geom_boxplot(aes(fill = approach))

example_1.png

Related