How to colour specific dots in R

Viewed 73

I want to scatter the following variables (N1 and N2)

Here is a small sample of my data.

df<-read.table (text=" N1 N2
60  19
55  77
45  35
70  66
30  47
60  26
50  55
70  96
60  67
40  56
", header=TRUE)

I want to colour circles when the differences between N1 and N2 is >20%

I calculate the difference : (N2-N1)/N1*100 to get percentages for each row. The signs of negative or positive are ignored (absolute number)

The outcome is similar to this :

enter image description here

That would be good if we could have the confidence intervals.

1 Answers

Try this using ggplot2. Compute the percentage and store the comparison you want in a logical variable that can be used for coloring the scatter plot:

library(dplyr)
library(tidyr)
library(ggplot2)
#Code
df %>%
  mutate(Perc=abs((N2-N1)/N1*100),
         Col=!Perc>20) %>%
  ggplot(aes(x=N1,y=N2,color=Col))+
  geom_point()+
  geom_smooth(method='lm',aes(group=1))+
  theme(legend.position = 'none')

Output:

enter image description here

Related