简体   繁体   中英

How to change outliers points color in geom_jitter

How to change the parameters of points (color, shape, etc.) corresponding to outliers in geom_jitter ?

There is a data

> dput(head(df, 20))
structure(list(variable = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 
1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 3L, 3L), .Label = c("W1", 
"W3", "W4", "W5", "W12", "W13", "W14"), class = "factor"), value = c(68, 
62, 174, 63, 72, 190, 73, 68, 62, 88, 81, 80, 79, 51, 73, 61, 
NA, NA, 84, 87)), row.names = c(NA, 20L), class = "data.frame")

and a code

plot <-
    ggplot(df, aes(factor(df$variable), df$value)) +
    geom_jitter(position = position_jitter(width = .1, height = 0), size = 0.7) +
    theme(legend.position = 'none') +
    theme_classic() +
    labs(x = '',
         y = '',
         title = "test")

And I get such plot.

阴谋

For same data earlier has been created boxplot with default coef = 1.5 , so I know than there are outliers in this dataset. Now I just want to create dotplot and to color outliers points in red. With geom_boxplot , this is done with the single function argument outlier.color , but there are no such arguments for geom_jitter .

You can define first your outliers using dplyr :

library(dplyr)
new_df <- df %>% group_by(variable) %>% filter(!is.na(value)) %>% 
  mutate(Outlier = ifelse(value > quantile(value, 0.75)+1.50*IQR(value),"Outlier","OK")) %>%
  mutate(Outlier = ifelse(value < quantile(value, 0.25)-1.50*IQR(value),"Outlier",Outlier))

head(new_df)
# A tibble: 6 x 3
# Groups:   variable [1]
  variable value Outlier
  <fct>    <dbl> <chr>  
1 W1          68 OK     
2 W1          62 OK     
3 W1         174 Outlier
4 W1          63 OK     
5 W1          72 OK     
6 W1         190 Outlier

and then using this new column, you can lot subset of the dataset depending of the condition Outlier :

library(ggplot2)
ggplot(subset(new_df, Outlier == "OK"), aes(x = variable, y = value))+
  geom_jitter(width = 0.1, size = 0.7)+
  geom_jitter(inherit.aes = FALSE, data = subset(new_df, Outlier == "Outlier"),
              aes(x = variable, y  = value), width = 0.1, size = 3, color = "red")+
  theme(legend.position = 'none') +
  theme_classic() +
  labs(x = '',
       y = '',
       title = "test")

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM