Home > Blockchain >  add correlation coefficient and CI values in a boxplot in R
add correlation coefficient and CI values in a boxplot in R

Time:10-25

I am trying to make a boxplot with the correlation coefficient and their CI values in a boxplot in R. However when I try to add the following line of code it does not work nor gives it a error code.

boxplot(AI~Q8,
data=df6,
main="The relation between Q8 and the A",
xlab="A",
ylab="B",
col="orange",
border="brown",
stat_cor()
) 

or

boxplot(AI~Q8,
data=df6,
main="The relation between Q8 and the A",
xlab="A",
ylab="B",
col="orange",
border="brown",
)   stat_cor()

And is it also possible to get a different color for each boxplot?

This is the dataset I use

structure(list(AI = c(0.659967433444017, 0.941802575478176, 0.565824387077681, 
0.733813835498287, 0.502486567259441, 0.581214986043292, 0.190601573198807, 
0.61511194322592, 0.630316833066587, 0.513634604352834, 0.691766098799664, 
0.443331648025045, 0.475498746385683, 0.253183014637901, 0.685340877692643, 
1.07517098753888, 1.10219598244924, 0.469261733415629, 0.473732071653954, 
1.11472099520751, 1.12140547685593, 0.844644528419478, 0.741480217894283, 
0.664326042816726, 0.798610418245564, 0.184662871961999, 0.718894350907626, 
0.773529667226157, 0.65593386028412, 0.958431317152659, 0.638301596431948, 
0.844678953483002, 1.12048871720509, 1.21583405287684, 0.642731559824528, 
0.720376072993178, 0.53551579775883, 0.612011376983417, 0.281431655977777, 
1.25176573918925, 1.15328375538737, 1.20957695840318, 1.09278028083012, 
0.859636858723266, 1.20869790596587, 1.12288309438874, 0.891306451574103, 
0.552552119084953, 0.995259412720299, 1.17674596084747), Q8 = c(1L, 
1L, 1L, 1L, 1L, 1L, 1L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 
3L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 1L, 2L, 2L, 2L, 2L, 
3L, 3L, 3L, 2L, 2L, 2L, 4L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 
3L)), row.names = c(1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L, 
11L, 12L, 13L, 14L, 15L, 16L, 17L, 18L, 19L, 20L, 21L, 22L, 23L, 
24L, 25L, 26L, 27L, 28L, 29L, 30L, 31L, 33L, 34L, 36L, 37L, 38L, 
39L, 40L, 41L, 42L, 43L, 44L, 45L, 46L, 47L, 48L, 49L, 50L, 51L, 
52L), class = "data.frame")

CodePudding user response:

You can add correlation in a legend, colors may be specified as vectors.

clr <- hcl.colors(length(unique(df6$Q8)), alpha=.5)
blr <- hcl.colors(length(unique(df6$Q8)), alpha=1)

boxplot(AI ~ Q8,data=df6, main="The relation between Q8 and the A",
        xlab="A", ylab="B", col=clr, border=blr)

corr <- with(df6, cor.test(AI, Q8))[c('estimate', 'conf.int')]

legend('topleft', 
       legend=bquote(rho ==.(signif(corr[[1]], 2))~'['*.(signif(corr[[2]][1], 2))*','~.(signif(corr[[2]][2], 2))*']'),
       bty='n')

enter image description here

  • Related