gpt4 book ai didi

r - 将特定于组的文本/数据添加到 R/ggplot2 中的分面图中

转载 作者:行者123 更新时间:2023-12-01 08:22:11 24 4
gpt4 key购买 nike

我正在比较大型基因表达实验中重复样本之间的组内相关性,其中我有多个独立的生物组 - 想法是查看是否有任何组的相关性比其他组低得多,表明潜在样本混淆或其他错误。

我正在使用 ggplot 来绘制每个重复对的表达值。我还希望能够将相关系数和 p 值添加到绘图的每个面板中,这是我通过 summarize 获得的。和 cor.test .您可以使用此代码来获得总体思路:在 exp1 中,重复项是相关的,但不是在 exp2 中.

library(tidyverse)

df <- data.frame(exp=c(rep('exp1', 100), rep('exp2', 100)), a=rnorm(200, 1000, 200))
df <- mutate(df, b=ifelse(exp=='exp1', a*rnorm(100,1,0.05), rnorm(100, 1000, 200)))
head(df)
tail(df)

df %>% ggplot(aes(x=a, y=b))+
geom_point() +
facet_wrap(~exp)

group_by(df, exp) %>%
summarize(corr=cor.test(a,b)$estimate, pval=cor.test(a,b)$p.value)

这是我通过 ggplot 生成的图,我已经手动添加了最后得到的 R 和 p 值。但是当然,如​​果我有很多样本对要分析,那么能够从 ggplot 中自动添加这些会很好。称呼。我只是不知道该怎么做。

enter image description here

最佳答案

如果出于某种原因,您想自己构建它而不是使用 ggpubr函数,您可以创建汇总数据、格式化标签并使用 geom_text 放置标签。 .

我正在格式化统计数据,以便 R 具有固定的 3 位有效数字,而 p 具有 3 位数字,回退到科学记数法。我在 summarise 中更改了这些列的名称到 R 和 p 来制作下面的标签。 reshape 为长数据并使用 unite 创建一个新列得到这个:

library(tidyverse)
...

group_by(df, exp) %>%
summarize(R = cor.test(a, b)$estimate, p = cor.test(a, b)$p.value) %>%
mutate(R = formatC(R, format = "fg", digits = 3),
p = formatC(p, format = "g", digits = 3)) %>%
gather(key = measure, value = value, -exp) %>%
unite("stat", measure, value, sep = " = ")
#> # A tibble: 4 x 2
#> exp stat
#> <chr> <chr>
#> 1 exp1 R = 0.965
#> 2 exp2 R = 0.0438
#> 3 exp1 p = 1.14e-58
#> 4 exp2 p = 0.665

然后对于每个组,我想折叠两个标签,用换行符分隔 \n .这是一个可以很好地扩展的地方——你可能有更多的汇总统计数据要显示,但这应该仍然有效。

summ <- group_by(df, exp) %>% 
summarize(R = cor.test(a, b)$estimate, p = cor.test(a, b)$p.value) %>%
mutate(R = formatC(R, format = "fg", digits = 3),
p = formatC(p, format = "g", digits = 3)) %>%
gather(key = measure, value = value, -exp) %>%
unite("stat", measure, value, sep = " = ") %>%
group_by(exp) %>%
summarise(both_stats = paste(stat, collapse = "\n"))

summ
#> # A tibble: 2 x 2
#> exp both_stats
#> <chr> <chr>
#> 1 exp1 "R = 0.965\np = 1.14e-58"
#> 2 exp2 "R = 0.0438\np = 0.665"

geom_text ,我将 x 坐标设置为 -Inf ,它得到所有 x 值的最小值,y 坐标为 Inf对于所有 y 值的最大值。这会将标签放在左上角,而不管数据中的值如何。

我不喜欢这里的一件事就是入侵 hjustvjust超出预期的 0 到 1 范围。但是 nudge_x/ nudge_y不会做任何事情,因为值被设置为无穷大。

df %>% 
ggplot(aes(x = a, y = b)) +
geom_point() +
geom_text(aes(x = -Inf, y = Inf, label = both_stats), data = summ,
hjust = -0.1, vjust = 1.1, lineheight = 1) +
facet_wrap(~ exp)



创建于 2018-11-14 由 reprex package (v0.2.1)

关于r - 将特定于组的文本/数据添加到 R/ggplot2 中的分面图中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53311214/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com