基于ggplot中的条件的颜色点

时间:2021-06-21 16:35:48

标签: r ggplot2 colors fill

我有这个数据集

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))

这,产生以下情节

enter image description here

问题:

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

非常感谢!

1 个答案:

答案 0 :(得分:2)

一种方法是将 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")) +
相关问题