简体   繁体   中英

Correlation plot between two variables with line and person r value in graph - seeking alternate example

Would just like some clarity here and a different example if someone has one. Initially I wanted to use this example because it has the graph, the mean line, and the r value all presented in the graph: http://www.sthda.com/english/wiki/correlation-test-between-two-variables-in-r

However, I'm using r studio server and creating a shiny app. Library ggpubr will simply not install. I've tried several ways to get this library to install.

So, does anyone have an alternate example that might work?

Cheers ~!

How about this:

library(ggplot2)
data(mtcars)

r <- round(cor(mtcars$wt, mtcars$mpg), 2)
p <- cor.test(mtcars$wt, mtcars$mpg)$p.value
ggplot(mtcars, aes(y=wt, x=mpg)) + 
  geom_point() + 
  geom_smooth(method="lm", col="black") + 
  annotate("text", x=20, y=4.5, label=paste0("r = ", r), hjust=0) +
  annotate("text", x=20, y=4.25, label=paste0("p = ", round(p, 3)), hjust=0) +
  theme_classic() 
  

在此处输入图像描述

You could use the geom_smooth function from ggplot2 and implement the correlation coefficient aswell as the p-value as follows:

library(ggplot2)
my_data <- mtcars
cor_coefs <- cor.test(my_data$mpg, my_data$wt)
ggplot(data = my_data, aes(x = mpg, y = wt)) + 
  geom_point() +
  geom_smooth(method=lm , color="red", fill="#69b3a2", se=TRUE) +
  annotate("text", x = 30, y = 4, label = paste0("R: ", round(cor_coefs$estimate, 2))) +
  annotate("text", x = 30, y = 3.5, label = paste0("p-value: ", round(cor_coefs$p.value, 10)))

cor_coefs safes the correlation test and you can use it to get the desired values. With annotate from ggplot2 , you need to specify the x and y position of your text. You could implement that dynamically based on your needs (since you have not provided any data).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM