Sylvia Rodriguez
Sylvia Rodriguez

Reputation: 1353

Combine groups into one group to display in boxplot (ggplot2, R)

I am using the mtcars dataset as an example and I use this code.

library(ggplot2)
library(ggsci)
ggviolin(mtcars, x="cyl", y="disp", fill="cyl", palette="jco", facet.by = "am")

To each facet, I would like to add a fourth category on the x-axis (maybe call this "6or8"), in which the 6- and 8-cylinder groups (but not the 4-cylinder group) are combined. I found this similar post, but it did not help me, because of my facets and addition of two instead of all categories.

Does anyone have a suggestion? Thank you.

Upvotes: 1

Views: 514

Answers (1)

Brandon
Brandon

Reputation: 1904

You could try this:

> newmtcars <- rbind(mtcars %>% mutate(cyl = as.character(cyl)),
+                    mtcars %>% filter(cyl %in% c(6,8)) %>% mutate(cyl = '6or8')) %>% arrange(cyl)
> ggviolin(newmtcars, x="cyl", y="disp", fill="cyl", palette="jco", facet.by = "am")

You can manually change the levels for cyl to change the ordering in the plot (if, for example, you want "6or8" to be the first/last level).

Upvotes: 1

Related Questions