获取特定于 R 中每个 y 轴变量的相关趋势线和 R 值

Obtain correlation trendlines and R value specific to each y-axis variable in 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, aes(A,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。所以我不得不做一些试验和错误。也许有更好的方法来按照您需要的方式获取情节。

您的代码中的第一个问题。因为您在 geom_point 中设置了 colour 美学,所以它没有被传递给其他函数(stat_corgeom_smooth)。要解决此问题,您可以在 ggplot 函数中设置 colour 并将其传递给管道中的其他函数。

此外,我必须创建另一个 data.frame 来获取每个组中标签(label.xlabel.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_pointstat_smooth 中分别映射颜色美学,并在主要 ggplot 中使用 group 参数] 打电话。

ggplot(data2, aes(x=A, y=value, group=letter)) + geom_point(aes(colour = letter))  +
  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(aes(colour = letter), method='lm', formula = 'y ~ x') +
  coord_cartesian(clip = 'off')

请注意 coord_cartesian(clip = 'off'),这样方程式就不会在绘图区域的末尾被截断。因此,您可能需要移动图例。您还可以更改 x 轴的限制,使方程适合绘图区域。