ggplot散点图加相关系数

计算一组数据有没有相关性以及相关程度时,可以使用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")
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容