Home > Software engineering >  Rstudio Bland Altman grouped colours and shapes
Rstudio Bland Altman grouped colours and shapes

Time:04-16

I have a bland-altman plot of 16 measurements divided over 3 groups (Slice) which I want to colorcode and possibly have different shapes but somehow I cant get it working:

df <- data.frame("Slice" = c(1,1,1,1,1,1,2,2,2,2,2,2,3,3,3,3),
                 "Segments" = c(1:16),
                 "mean" = c(6,5,2,4,8,9,6,3,5,6,5,8,5,4,6,4),
                 "dif" = c(1,3,2,1,2,3,2,1,2,2,2,1,3,2,1,2))

#creat limits of agreement
    LL = mean(df$dif)-1.96*(sd(df$dif))
    UL = mean(df$dif) 1.96*(sd(df$dif))

#create BA plot
BAplot <- ggplot(df, aes(x=mean,y=dif)) 
  geom_jitter(alpha=1.0,size=18,shape="*", stroke = 1.5) 
  geom_hline(yintercept=mean(df$dif),color= "blue",size=2) 
  geom_text(aes(x = 12, y = mean(df$dif) 0.2, label = round(mean(df$dif), 1)), col = "blue", size = 7)  
  geom_hline(yintercept=0,linetype=3,size=2)  
  geom_hline(yintercept=c(UL,LL),color="black",linetype="dashed",size=2) theme_bw() 
  geom_text(aes(x = 12, y = UL 0.2, label = round(UL,1)), col = "black", size = 7)  
  geom_text(aes(x = 12, y = LL 0.2, label = round(LL,1)), col = "black", size = 7)  
  scale_x_continuous("mean",limits = c(-2,12)) 
  scale_y_continuous("diff", limits = c(-1, 5.5))

enter image description here

CodePudding user response:

To code your points by color and to have different shapes you have to map your Slice column on the color and/or shape aesthetic inside geom_jitter. As Slice is a numeric I first converted it to a factor. If you want specific colors or shape you could set your desired values using scale_color_manual and scale_shape_manual:

library(ggplot2)

ggplot(df, aes(x = mean, y = dif))  
  geom_jitter(aes(color = factor(Slice), shape = factor(Slice)), alpha = 1.0, size = 2)  
  geom_hline(yintercept = mean(df$dif), color = "blue", size = 2)  
  geom_text(aes(x = 12, y = mean(dif)   0.2, label = round(mean(dif), 1)), col = "blue", size = 7)  
  geom_hline(yintercept = 0, linetype = 3, size = 2)  
  geom_hline(yintercept = c(UL, LL), color = "black", linetype = "dashed", size = 2)  
  theme_bw()  
  geom_text(aes(x = 12, y = UL   0.2, label = round(UL, 1)), col = "black", size = 7)  
  geom_text(aes(x = 12, y = LL   0.2, label = round(LL, 1)), col = "black", size = 7)  
  scale_x_continuous("mean", limits = c(-2, 12))  
  scale_y_continuous("diff", limits = c(-1, 5.5))

  • Related