基于 ggplot 中条件的颜色点

Colour dots based on conditions in ggplot

我有这个数据集

a <- data.frame(PatientID = c("0002" ,"0004", "0005", "0006" ,"0009" ,"0010" ,"0018", "0019" ,"0020" ,"0027", "0039" ,"0041" ,"0042", "0043" ,"0044" ,"0045", "0046", "0047" ,"0048" ,"0049", "0055"),
                   volume = c( 200 , 100 , 243 , 99 , 275, 675  ,345 , 234 , 333  ,444,  123 , 274 , 442 , 456  ,666 , 567 , 355 , 623 , 105 , 677  ,876), 
                   Status= c("New" , "Old" , "New" , "New" , "Old", "New"  ,"Old" , "New" , "Old" , "New" , "New" ,"New"  ,"Old" , "New" ,"New"  ,"Old" , "New" , "Old" , "New" , "Old" ,"Old"),
                   sex = c( 1 , 1 , 1 , 1 , 0, 0  ,0 , 0 , 0  ,1 , 1 , 1  , 0 , 0  ,1 , 1 , 1 , 1  , 1 , 1  ,1), stringsAsFactors = F)

和这段代码

color <- c("#00B7EB","#EE2A7B")                
ggplot(a, aes(y = a$volume, x = a$Status, fill = a$Status)) +
  geom_boxplot() +
  geom_point(alpha=0.4) +
  scale_fill_manual(values=color) +
  labs(x='', y='Volume') +
  theme_classic() +
  theme( text = element_text( size = 15))

这将产生以下情节

问题:

根据以下条件,我该怎么做才能为这个 ggplot 中的点着色?: 如果女性音量 >100 (sex==1) 红色,否则黑色 如果男性音量 >200 (sex==0) 红色,否则黑色

非常感谢!

一种方法是根据您的条件设置 geom_point 的颜色美感:

geom_point(alpha=0.4, aes(colour = (sex == 1 & volume > 100) | (sex == 0 & volume > 200))) +

然后使用scale_colour_manual将颜色设置为红色和黑色:

scale_colour_manual(values = c("black", "red")) +