Home > Mobile >  How to color points in ggplot 2 based on confidence interval R
How to color points in ggplot 2 based on confidence interval R

Time:12-14

I have 2 confidence intervals, one for my x variable and one for my y variable.

Let's say my data is:

x<-c(1,2,3,4,2,4)
y<-c(10,20,30,40,10,20)
df <- data.frame(x,y)

confidence interval for x: 2-3

confidence interval for y: 20-30

Ideally, I would like to be able to create a scatter plot of the points with 4 different colors: color 1: within both x and y confidence intervals color 2: within x confidence interval but not within y color 3: within y confidence interval but not within x color 4: outside of both confidence intervals

I thought about creating a new column which does these operations and basing the colors off that, but I feel like there should be a better way.

CodePudding user response:

Whats about plotting the confidence bands instead of coloring the points?

x<-c(1,2,3,4,2,4)
y<-c(10,20,30,40,10,20)

df <- data.frame(x,y)
df_conf = data.frame(xmin = c(-Inf, 2), xmax = c(Inf, 3), ymin=c(20, -Inf), ymax=c(30, Inf), fill = c("blue","orange"))

ggplot(df, aes(x, y))   
  geom_rect(data=df_conf, aes(xmin=xmin, xmax=xmax,ymin= ymin, ymax=ymax, fill=fill), 
            alpha=0.3, inherit.aes = F, show.legend = F)  
  geom_point() 

enter image description here

  • Related