How can I color the outlier points in ggplot2? I want them to be the same color as the boxplot itself. colour=
is not enough to do this.
Example:
<
Just in case you really want to keep the boxes black:
Another possible solution is to
outlier.color = NA
, andcol
aesthetic in this call to geom_point()
Step 1: Define a function to determine whether a point is an outlier:
is.outlier <- function (x) {
x < quantile(x, .25) - 1.5 * IQR(x) |
x > quantile(x, .75) + 1.5 * IQR(x)
}
Step 2: Group data and calculate outliers with this function for the groups
diamonds %>% group_by(cut) %>%
mutate(outlier.p = is.outlier(price)) %>%
ungroup() -> diamonds
Step 3: Create plot
ggplot(diamonds, aes(x = cut, y = price, fill = cut)) +
geom_boxplot(outlier.color = NA) +
geom_point(data = diamonds[diamonds$outlier.p,], aes(col = cut))
Please note that you have to subset your dataset in the geom_point()
call (last line) lest all points are plotted.