Reputation: 1944
I'm trying to make a straightforward boxplot in ggplot. I'm not sure how get a grouping variable and a color/fill variable. I've tried to gather, but that doesn't seem to work. Any thoughts?
library(tidyverse)
# Does not work
mtcars %>%
as_tibble() %>%
ggplot(aes(factor(gear),
mpg,
group = vs)) +
geom_boxplot(aes(fill = as.factor(gear)))
# Does not work either
mtcars %>%
as_tibble() %>%
select(gear, mpg, vs) %>%
gather(key, value, -vs) %>%
ggplot(aes(key,
value)) +
geom_boxplot(aes(color = vs))
Upvotes: 0
Views: 847
Reputation: 13319
Alternatively:
mtcars %>%
as_tibble() %>%
group_by(vs) %>%
ggplot(aes(factor(gear),
mpg,
fill=as.factor(gear))) +
geom_boxplot()
Upvotes: 0
Reputation: 435
I'm not sure this is your intended output (gear
as x-axis and fill
), but here's a working example:
mtcars %>%
ggplot(
aes(
x = factor(gear),
y = mpg,
color = factor(vs),
fill = factor(gear)
)
) + geom_boxplot()
I've found being explicit when declaring your aesthetic mappings can be helpful when learning ggplot2
.
Upvotes: 1