首页 > 解决方案 > 根据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 中的点着色?:如果女性(性别==1)的体积>100,则为红色,否则为黑色如果男性(性别==0)的体积>200(性别==0)红色,否则为黑色

太感谢了!

标签: rggplot2colorsfill

解决方案


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

推荐阅读