1

Hi guys im new to R and have been trying to draw and compare a scatter plot with 2 sets of data (base line and follow up). these are my current codes:

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

I got something like this:

sample data plot

how do i change the colours of the line so that if it's an increasing value it's green and if it's a decreasing value it will be blue?

Thanks heaps!

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
RLave
  • 8,144
  • 3
  • 21
  • 37
Jes
  • 11
  • 1
  • 4

1 Answers1

1

You can try this. It works for me:

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

I moved the color='red' outside the aes() part for the geom_points() And made a new variable (factor), named lineColor in your data that is used to color the lines by adding color=data$lineColor in geom_segment()

Alternatively, you can do it without adding a new column, and adding: color=factor(ifelse(data$x_diff < 0,'decreasing','increasing')) to geom_segment instead

P1storius
  • 917
  • 5
  • 12