9

I'm trying to create a ggplot and add results of a correlation test I have done. Something along the lines of:

p+annotate("text",x=12.5,y=15.25,label=c(cor.test$estimate,cor.test$p.value))

I keep getting error messages no matter what I try. Any ideas?

B.Shermeister
  • 507
  • 2
  • 6
  • 17
  • Not a solution to your issue, but have you seen the packages corrplot/ggcorr – Vlo Feb 16 '18 at 16:26
  • What are your errors exactly? If you show us some more code (example data and full plotting function), maybe someone finds a solution. – Linus Feb 16 '18 at 16:30
  • I have, though I already have a plot and just need to add annotations. Would like to link them to a corr test results directly – B.Shermeister Feb 16 '18 at 16:33
  • 'iriscor<-cor.test(iris$Sepal.Length,iris$Sepal.Width) ggplot(iris)+ geom_point(aes(Sepal.Length,Sepal.Width,color=Species))+ labs(title="Sepal",y="Width",x=expression(paste(bold("Length"))),col="Species")+ theme(legend.position = "none")+ theme(axis.title = element_text(face = "bold"))+ theme(axis.text = element_text(face = "bold"))+ annotate("text",x=12.5,y=15.25,label=c(iriscor$estimate,iriscor$p.value),parse=TRUE) ' – B.Shermeister Feb 16 '18 at 16:43
  • Related: [Adding Regression Line Equation and R2 on graph](https://stackoverflow.com/questions/7549694/adding-regression-line-equation-and-r2-on-graph) – Henrik Feb 16 '18 at 16:47

2 Answers2

20

I have actually managed to add stat details to the plot by using stat_cor() from the package ggpubr

library(ggpubr)
p+stat_cor(method="pearson")
B.Shermeister
  • 507
  • 2
  • 6
  • 17
4

There is a package in development that can do this for you (ggstatsplot is on CRAN).

Here is an example of how to create correlation plot:

    ggstatsplot::ggscatterstats(data = iris, x = Sepal.Length, y = Sepal.Width)

This will produce a plot that looks like the following (you can similarly get results from Spearman's rho (type = 'spearman') or robust correlation test (type = 'robust')):

enter image description here

Check out the documentation of the function for more.

Community
  • 1
  • 1
Indrajeet Patil
  • 4,673
  • 2
  • 20
  • 51
  • 1
    @B.Shermeister Has this question been answered to your liking? If yes, please accept the answer (stackoverflow.com/help/someone-answers) so that this thread will be closed. – Indrajeet Patil Feb 17 '18 at 22:11
  • 1
    I am trying to create a `ggplot` that will show the result of a ttest (or corr test) on the plot. I am now using the line `annotate("text",x=1,y=10,label='atop(bold("P-value = 0.286"))',cex=7,parse=TRUE)`. The only problem is that I have to change the value manually each time. I would like to insert `ttest$p.value` instead of the number in the label – B.Shermeister May 03 '18 at 18:35
  • @B.Shermeister use ```label='atop(bold(paste("P-value = ", ttest$p.value))))``` – Farid Huseynov Dec 04 '22 at 10:22