如何解决获取特定于 R 中每个 y 轴变量的相关趋势线和 R 值
我想绘制变量 B、C、D(y 轴)与 A(x 轴)的相关性,以获得与此类似的图:
如何获得绘制在对数缩放 y 轴上的每个变量的特定相关趋势线和 R 值? 到目前为止,我已经获得了以下内容:
A = c(3984,5307,3907,3848,4024,6930,6217,6206,5976,4043)
B = c(18117,16512,17891,17783,12643,12864,10997,12946,12325,12594)
C = c(9403,9375,7142,6659,8660,9072,7965,8444,6467,6245)
D = c(443,564,541,525,503,682,563,584,639,413)
data = data.frame(A,B,C,D)
data2<- melt(data,id.vars = 'A',variable.name = 'letter')
ggplot(data2,aes(A,value)) + geom_point(aes(colour = letter)) + scale_y_continuous(trans='sqrt') + stat_smooth(method=lm) + stat_cor(aes(color = letter),label.x = 3)
ggplot(data2,value)) + geom_point(aes(colour = letter)) + stat_cor(method = "pearson",label.x = 4000,label.y = 1.9) + stat_smooth(method=lm) + facet_wrap(letter~ .)
解决方法
我之前没有使用过 stat_cor
。所以我不得不做一些试验和错误。也许有更好的方法可以按照您需要的方式获得情节。
您的代码中的第一个问题。因为您在 colour
中设置了 geom_point
美学,所以它没有被传递给其他函数(stat_cor
和 geom_smooth
)。要解决此问题,您可以在 colour
函数中设置 ggplot
,然后将其传递给管道中的其他函数。
此外,我必须创建另一个 data.frame 来获取每个组中标签(label.x
和 label.y
)的位置。在这种情况下它有效,但我认为它不适用于所有情况(例如,如果线交叉)。无论如何,您需要或多或少地手动设置位置,使用类似于我所做的方法。
# for each letter,get x and y values for x == max(x)
df.pos.labels <- data2 %>% group_by(letter) %>% slice_max(A) %>%
mutate(value=sqrt(value))
ggplot(data2,aes(x=A,y=value,colour=letter)) + geom_point() +
scale_y_continuous(trans='sqrt') +
ggpubr::stat_cor(method = "pearson",hjust=0.5,vjust=0,label.x = df.pos.labels$A,label.y=df.pos.labels$value) +
stat_smooth(method='lm',formula = 'y ~ x') +
coord_cartesian(clip = 'off')
这会创建将颜色映射到组的线条和方程。如果你希望你的方程都是相同的颜色(例如黑色),你可以分别映射 geom_point
和 stat_smooth
中的颜色美学,并在主 {{1} 中使用 group
参数} 调用。
ggplot
注意 ggplot(data2,group=letter)) + geom_point(aes(colour = letter)) +
scale_y_continuous(trans='sqrt') +
ggpubr::stat_cor(method = "pearson",label.y=df.pos.labels$value) +
stat_smooth(aes(colour = letter),method='lm',formula = 'y ~ x') +
coord_cartesian(clip = 'off')
,这样方程就不会在绘图区域的末端被剪掉。因此,您可能需要移动图例。您还可以更改 x 轴的限制,以便方程适合绘图区域。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。