Coloring boxplot outlier points in ggplot2?

后端 未结 6 901
挽巷
挽巷 2020-12-05 11:18

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:

<
6条回答
  •  南方客
    南方客 (楼主)
    2020-12-05 12:02

    Just in case you really want to keep the boxes black:

    Another possible solution is to

    1. store in a variable whether a point is an outlier,
    2. suppress outlier plotting with outlier.color = NA, and
    3. plot only those points that are outliers and use the col 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.

提交回复
热议问题