ggplot:更改散点图中特定点的颜色

时间:2018-09-04 17:50:55

标签: r ggplot2

我正在绘制3年期间的生物年龄与时序年龄的图表,并试图绘制一个散点图,该散点图仅突出显示3年期间越过斜线的点。那有可能吗?以下是我的一些数据以及当前绘制散点图所需的代码。

head(mydata)

 SampleID       ba_baseline     ba_follow up ba_diff           age_baseline          age_followup age_diff
1      X3_0        59.03487        58.91077 -0.12409581               73.80               77.28    3.48
2      X5_0        58.96254        61.33064  2.36810749               82.71               85.45    2.74
3      X6_0        56.41316        52.37936 -4.03380246               73.14               76.95    3.81
4      X9_0        53.63238        56.31112  2.67873665               76.84               80.03    3.19

ggplot(mydata) + 
  geom_point(aes (x = mydata$age_baseline , y= mydata$ba_baseline),color="blue") + 
  geom_point (aes (x = mydata$age_followup, y = mydata$ba_followup),color="red") + 
  xlab("Age") + 
  ylab ("BA") +
  cleanup +
  geom_segment(data = mydata , aes(x=mydata$age_baseline, xend = mydata$age_followup, y=mydata$ba_baseline, yend = mydata$ba_followup), color=factor(ifelse(mydata$ba_diff < 0 ,"dark green", "blue"))) +
  geom_abline(intercept=0 , slope = 1 , linetype ="dashed", color="black")

我对R真的很陌生,我花了将近2天的时间提出了这几行代码,因此如果答案更容易理解,那将非常有帮助。

非常感谢!

dput(mydata[1:5,]
structure(list(SampleID = structure(c(19L, 32L, 41L, 49L, 2L), .Label = c("", 
"X10_0", "X11_0", "X12_0", "X13_0", "X14_0", "X15_0", "X16_0", 
"X17_0", "X19_0", "X20_0", "X23_0", "X24_0", "X25_0", "X26_0", 
"X27_0", "X28_0", "X29_0", "X3_0", "X31_0", "X35_0", "X36_0", 
"X37_0", "X38_0", "X39_0", "X40_0", "X41_0", "X42_0", "X46_0", 
"X47_0", "X48_0", "X5_0", "X50_0", "X51_0", "X52_0", "X53_0", 
"X54_0", "X55_0", "X57_0", "X59_0", "X6_0", "X61_0", "X62_0", 
"X63_0", "X66_0", "X67_0", "X68_0", "X69_0", "X9_0"), class = "factor"), 
    ba_baseline = c(59.0348664, 58.96253611, 56.41316144, 
    53.63238385, 62.64326543), ba_followup = c(58.91077059, 
    61.3306436, 52.37935898, 56.3111205, 67.33817561), ba_diff = c(-0.12409581, 
    2.368107486, -4.033802462, 2.678736655, 4.694910184), age_baseline = c(73.8, 
    82.71, 73.14, 76.84, 75), age_followup = c(77.28, 
    85.45, 76.95, 80.03, 77.97), age_diff = c(3.48, 2.74, 3.81, 
    3.19, 2.97)), row.names = c(NA, 5L), class = "data.frame")

1 个答案:

答案 0 :(得分:1)

也许,预先比较age_*baseline_*并创建一个变量,如下所示:

mydata %<>%
  mutate(baseline_toggle = ifelse(ba_baseline/age_baseline > 1, 0, 1),
         followup_toggle = ifelse(ba_followup/age_followup > 1, 0, 1),)

ggplot(df) + 
  geom_point(aes (x = age_baseline , y = ba_baseline, color = baseline_toggle) + 
  geom_point (aes (x = age_followup, y = ba_followup, colour = followup_toggle )) + 
  xlab("Age") + 
  ylab ("BA") +
  geom_abline(intercept=0 , slope = 1 , linetype ="dashed", color="black")

然后您可以根据需要对它们进行颜色编码。