计算一组数据有没有相关性以及相关程度时,可以使用cor(),以及cor.test()计算显著性,如下所示,我们想计算这两种花的长度有没有相关性。
head(iris)
plot(iris$Sepal.Length,iris$Petal.Length)
cor(iris$Sepal.Length,iris$Petal.Length)
#[1] 0.8717538
cor.test(iris$Sepal.Length,iris$Petal.Length)
# Pearson's product-moment correlation
#data: iris$Sepal.Length and iris$Petal.Length
#t = 21.646, df = 148, p-value < 2.2e-16
#alternative hypothesis: true correlation is not equal to 0
#95 percent confidence interval:
# 0.8270363 0.9055080
#sample estimates:
# cor
#0.8717538
我们可以手动将计算的相关系数以及p-value加在图上,也可以直接使用ggpubr包中的stat_cor()来将散点图直接标记相关系数以及p-value。
library(ggplot2)
library(ggpubr)
ggplot(iris, aes(x=iris$Sepal.Length, y=iris$Petal.Length)) +
geom_point()+ geom_smooth(method = 'lm', se = F, color = 'red')+theme_bw()+stat_cor(data=iris, method = "spearman")