R语言绘图小技巧篇-添加相关系数
2021-10-18 本文已影响0人
R语言搬运工
此文内容首发于微信公众号:R语言搬运工,关注公众号浏览更多精彩内容
**原文链接

当绘制点图并添加拟合曲线的时候,往往需要将相关系数和显著性水平也加入到图片中,这时候怎么绘制是经常碰见的问题。为方便快捷的解决这个问题,使用ggpubr包stat_cor就可以实现。

首先计算相关系数,然后使用函数annotate添加:
library(ggplot2)
data(mtcars)
df <- mtcars
df$cyl <- as.factor(df$cyl)
cor.test(df$mpg,df$wt)
b <- ggplot(df, aes(x = wt, y = mpg))
# Scatter plot with regression line
b + geom_point()+ geom_smooth(method = "lm")+
annotate("text",label="Pearson:R==-0.8677~p<0.001",family="Times",
parse=T,x=3,y=30,color="black",size=4)


使用ggpubr快速添加:
ggscatter(df, x = "wt", y = "mpg",
add = "reg.line", conf.int = TRUE,
add.params = list(fill = "lightgray"),
ggtheme = theme_minimal()
)+ stat_cor(method = "pearson",
label.x = 2, label.y = 30,color='red')

将P值修改为普通计数而不是科学计数:
ggscatter(df, x = "wt", y = "mpg",
add = "reg.line", conf.int = TRUE,
add.params = list(fill = "lightgray"),
ggtheme = theme_minimal()
)+ stat_cor(method = "pearson",
label.x = 2, label.y = 30,color='red',p.accuracy = 0.001)

当含有分组变量的时候,相关系数也是通过分组进行计算的:
# Change color and shape by groups (cyl)
b + geom_point(aes(color = cyl, shape = cyl))+
geom_smooth(aes(color = cyl, fill = cyl), method = "lm") +
scale_color_manual(values =c("#00AFBB", "#E7B800", "#FC4E07"))+
scale_fill_manual(values = c("#00AFBB", "#E7B800", "#FC4E07"))

添加每个分组下的相关系数和P值:
# Remove confidence region (se = FALSE)
# Extend the regression lines: fullrange = TRUE
b + geom_point(aes(color = cyl, shape = cyl))+
geom_smooth(aes(color = cyl), method = lm,se = FALSE, fullrange = TRUE)+
scale_color_manual(values = c("#00AFBB", "#E7B800", "#FC4E07"))+
ggpubr::stat_cor(aes(color = cyl), label.x = 2.4)

增加相关系数和P值的有效数位:
b + geom_point(aes(color = cyl))+
geom_smooth(aes(color = cyl), method = lm,se = FALSE, fullrange = TRUE)+
scale_color_manual(values = c("#00AFBB", "#E7B800", "#FC4E07"))+
ggpubr::stat_cor(aes(color = cyl), method='pearson',label.x = 2.4,
r.digits = 3,p.digits = 4)

变一下主题风格:

感兴趣的可以去R里面查看一下stat_cor函数的参数,里面有设置不同相关分析方法以及R值和P值的显示效果的参数,赶紧用自己的数据试一下吧。
此文内容首发于微信公众号:R语言搬运工,关注公众号浏览更多精彩内容
精彩推荐:
R语言绘制散点图geom_point
R语言添加拟合曲线geom_smooth
R语言箱线图boxplot
R语言线图geom_line