I'm trying to make a plot with horizontal boxplots in ggplot2, which you can only do by using coord_flip(). I'm also trying to space the boxplots vertically to group certain sets together. I have read that faceting is recommended for this kind of thing, but this is incompatible with coord_flip(), as we can see here: ggplot2: boxplot with facet_grid and free scale. So I'm wondering if it's possible to use blank levels in order to create blank spaces. Here's what I've managed to do so far:
d <- diamonds
library("ggplot2")
levels(d$cut) <- list(A="Fair", B="Good", "-", C="Very Good", D="Ideal", E="Premium")
p = ggplot(d, aes(x=cut, y=depth))
p +
geom_boxplot(color="black", size=0.2) +
theme_bw() +
scale_x_discrete(breaks = c("A", "B", "-", "C", "D", "E"), drop=FALSE) +
coord_flip()
ph = 2.75
pw = 4
ggsave("plot.png", height=ph, width=pw)
As you can see, if I create a blank level with "-" in it and include it in scale_x_discrete(), then somehow I get a blank row. The problem is I can only add one space. Does anyone have any ideas on how to add spaces between these horizontal box plots?
In ggplot2, till now the only way to make a plot horizontal is to use flip the axis using coord_flip(). With ggplot2 version 3.3. 0, we can easily flip axis and make horizontal boxplot or horizontal barplot without using coord_flip().
Adding error bars (whiskers) with stat_boxplot The default box plot in ggplot doesn't add the error bar lines, but you can add them with stat_boxplot , setting geom = "errorbar" . Note that you can change its width with width .
Because boxplots do not have error bars. A boxplot is just a graphical representation of five numbers: Minimum, Q1 (1st quartile), Median, Q3 (3rd quartile), and Maximum.
Here's one way that will let you add more blank levels:
d <- diamonds
levels(d$cut) <- list(A="Fair", B="Good", " "="space1", C="Very Good", D="Ideal", " "="space2", E="Premium")
ggplot(d, aes(x=cut, y=depth)) +
geom_boxplot(color="black", size=0.2) +
theme_bw() +
scale_x_discrete(breaks = c("A", "B", " ", "C", "D", " ", "E"), drop=FALSE) +
coord_flip()
This will leave tick marks on the spacers as well, though:
Removing all ticks is simple by adding:
+ theme(axis.ticks.y = element_line(linetype=0))
But if you want to remove the tick marks only for the spacers, at least one way (I'm sure there others) is to do it with a custom function:
f <- function(x) {
x[!x %in% c("A", "B", "C", "D", "E")] <- NA
x
}
ggplot(d, aes(x=cut, y=depth)) +
geom_boxplot(color="black", size=0.2) +
theme_bw() +
scale_x_discrete(breaks=f, drop=FALSE) +
coord_flip()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With