在R中更改geom_segment的颜色

时间:2018-08-28 14:40:34

标签: r ggplot2

您好,我是R新手,他们一直在尝试绘制散点图并将其与2组数据进行比较(基准线和后续数据)。 这些是我当前的代码:

ggplot(data) + 
  geom_point(aes (x = data$x_baseline , y= data$y_baseline, color = "red")) + 
  geom_point (aes (x = data$x_followup, y = data$y_followup, color = "blue")) + 
  xlab("X") + 
  ylab ("Y") +
  geom_segment(data = data , aes(x=data$x_baseline, xend = data$x_followup, y=data$y_baseline, yend = data$y_followup))

我有这样的东西:

sample data plot

我如何更改线条的颜色,以便使其值增加时呈绿色,而如果值减小则呈蓝色?

感谢堆!

head(data)
ID y_baseline y_followup y_diff x_baseline x_followup x_diff
1     X3_0        59.03487        58.91077  -0.1240958             73.80               77.28    3.48
2     X5_0        58.96254        61.33064   2.3681075               82.71               85.45    2.74
3     X6_0        56.41316        52.37936  -4.0338025               73.14               76.95    3.81
4     X9_0        53.63238        56.31112   2.6787367               76.84               80.03    3.19
5    X10_0        62.64327        67.33818   4.6949102               75.00               77.97    2.97
6    X11_0        61.68968        61.03282  -0.6568605               76.94               79.92    2.98

1 个答案:

答案 0 :(得分:1)

您可以尝试一下。它对我有用:

library(ggplot2)

 data <- data.frame(row.names=paste0('row',1:20))
 data$x_baseline <- sample(1:20)
 data$x_followup <- sample(1:20)
 data$y_baseline <- sample(1:20)
 data$y_followup <- sample(1:20)


 data$lineColor <- factor(ifelse(data$x_followup - data$x_baseline < 0,'increase','decrease'))

 ggplot(data) + 
  geom_point(aes (x = data$x_baseline , y= data$y_baseline), color = "red") + 
  geom_point (aes (x = data$x_followup, y = data$y_followup), color = "blue") + 
  xlab("X") + 
  ylab ("Y") +
  geom_segment(data = data , aes(x=data$x_baseline, xend = data$x_followup, y=data$y_baseline, yend = data$y_followup, color=data$lineColor))

我将color='red'移到了aes()的{​​{1}}部分之外 并在数据中创建了一个名为lineColor的新变量(因子),该变量用于通过在geom_points()

中添加color=data$lineColor来为行着色

或者,您可以在不添加新列的情况下执行以下操作: geom_segment()改为geom_segment