How do you use ggplot2 to create boxplots when the groupings overlap?

Viewed 34

I have a set of data which has an output variable and a set of labels. The problem that I'm facing is that the labels are not mutually exclusive. For example, lets say that I am analyzing paintings and I am looking at the price of the painting and the colors used to create it. I would have a dataset that looks like this:

Price Colors Used
10 Red, Black, Blue
12.5 Red, Green, Yellow, Black, purple
11 Blue, White
15 Red

I want to use ggplot2 to create a boxplot of price for all the rows that include "red" in the colors used, and then do the same for "Purple", "Black", etc. etc. But the problem that I run into is that GGplot2 treats each of these labels as unique if I simply write

ggplot(aes(x=colors, y=price))+
geom_boxplot()

Does anyone know of a good workaround to this?

1 Answers

You can use tidyr::separate_rows() to prepare your data:

library(tidyr)
library(ggplot2)

your_data %>%
  separate_rows(Colors.Used) %>%
  ggplot() +
    geom_boxplot(aes(x = Colors.Used, y = Price))

Result:

Result with separate_rows()

Data used:

your_data <- tibble::tribble( ~Price, ~Colors.Used, 10, "Red, Black, Blue", 12.5, "Red, Green, Yellow, Black, purple", 11, "Blue, White", 15, "Red")
Related