Coloring boxplot outlier points in ggplot2?

后端 未结 6 919
挽巷
挽巷 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 11:51

    If there is a need to change shape or color of the outlier points according to different factor (not the same which is used for making boxplot groups) then answer of @Dinre can be adapted.

    Color of points can be changed only if the color isn't used for boxplot themselves (you can't use two variables for colors).

    Using the data plot_Data and code from the @Dinre answer - color of outliers depend on factor carb. By adding argument outlier.shape = NA to geom_boxplot() original outliers are removed to ensure that they are not over-plotted by geom_point().

    ggplot() +
      geom_boxplot(data=plot_Data, aes(x=factor(cyl), y=mpg),outlier.shape = NA) + 
      geom_point(data=plot_Data[plot_Data$mpg > plot_Data$upper.limit | 
                                  plot_Data$mpg < plot_Data$lower.limit,], 
                 aes(x=factor(cyl), y=mpg, color=factor(carb)))
    

    enter image description here

    To change the shape of points:

    ggplot() +
      geom_boxplot(data=plot_Data, aes(x=factor(cyl), y=mpg),outlier.shape = NA) + 
      geom_point(data=plot_Data[plot_Data$mpg > plot_Data$upper.limit | 
                                  plot_Data$mpg < plot_Data$lower.limit,], 
                 aes(x=factor(cyl), y=mpg, shape=factor(carb)))
    

    enter image description here

提交回复
热议问题