![](/img/trans.png)
[英]ggplot2 facet_grid How to create different x-axis with keeping all values in each panel?
[英]How do I create a facet grid with scatterplots comparing numeric values corresponding to 5 different factors to each other in R?
我覺得我很難解釋這個,但我會盡力而為。
假設我有兩種類型的數據 plot:因子水平和“TWAS.P”值:
> final %>% select(BPcum, type, TWAS.P)
BPcum type TWAS.P
1: 910406 aoi 0.447942
2: 913192 aoi 0.343688
3: 918941 aoi 0.507661
4: 934255 aoi 0.602502
5: 963152 aoi 0.821883
---
61176: 2871588859 si 0.049800
61177: 2871696719 si 0.434000
61178: 2871742389 si 0.480000
61179: 2871747173 si 0.989000
61180: 2871747464 si 0.442000
> table(final %>% select(type))
aoi cpd dpw sc si
12244 12244 12244 12244 12204
我想創建一個圖表矩陣,例如顯示aoi
TWAS.P
值根據TWAS.P
值的每個其他“類型”的TWAS.P
值繪制。 因此,一個 plot 顯示aoi TWAS.P
值與cpd TWAS.P
值的對比,另一個顯示aoi TWAS.P
值與dpw TWAS.P
值的對比,等等。 如有必要,我希望它們在BPcum
上匹配。
我希望能夠發現每種type
的TWAS.P
值之間是否存在任何相關性。 我可以憑直覺知道我需要使用dplyr
的pivot_longer
但我不確定如何到達那里。
我能想到的最接近的是使用ggpairs
,盡管它並沒有完全達到我想要的位置:
ggpairs(
final %>% select(type, TWAS.Z),
ggplot2::aes(colour = type),
upper = list(continuous = "points", combo = "dot"),
lower = list(continuous = "points", combo = "dot")
)
如果您查看右上面板中的 plot,它與我要找的很接近。 但是,我希望每個type
的TWAS.Z
值的分面網格在每一行中相互比較,以便可以闡明任何相關性。
你有什么建議嗎?
我想出了另一種更好的方法來使用我以前使用過的舊代碼來做到這一點。 它不使用BPcum
,而是使用 ENSEMBL 基因 ID 和基因符號的組合。 我使用來自 base dcast
的 dcast 來完成此操作:
final_2 <-
select(final, geneid, genesymbol, type, TWAS.Z, TWAS.P) %>%
as.data.table()
final_2$type <- as.factor(final$type)
final_wide <-
dcast(final_2,
geneid + genesymbol ~ type,
value.var = c("TWAS.P"))
實際上,我認為您需要結合使用pivot_wider
和pivot_longer
在不同的列中分隔 x 軸(“aoi”)中所需的數據和 y 軸(其余部分)中所需的數據。 您的 dataframe 已經是長格式,但您的所有數據都在同一列中。
我是這樣做的。
library(tidyverse)
# create dataset
set.seed(100)
types <- c("aoi", "cpd", "dpw", "sc", "si")
A <- matrix(runif(5^2)*2-1, ncol=5)
Sigma <- t(A) %*% A
values <- as.vector(mvrnorm(n=2000, mu=rep(0,5), Sigma))
df.1 <- data.frame(BPcum=rep(1:2000, 5),
type=rep(types, rep(2000, 5)),
values=values)
# convert to "wide" format (each type in one column)
# note that it is important here that BPcum identifies each observation coherently (i.e., there are no duplicates)
df.wide <- df.1 %>% tidyr::pivot_wider(names_from = type, values_from=values)
# now convert back to "long", but leave aoi in its own column
df.long <- df.wide %>% dplyr::select(-BPcum) %>%
tidyr::pivot_longer(cols=-aoi)
# create plot
ggplot(df.long) + geom_point(aes(x=aoi, y=value)) +
facet_wrap(vars(name), nrow=1)
plot 的另一種方法是使用基本 R pairs
來創建散點圖矩陣。 不同之處在於您將擁有所有類型組合的散點圖。 在這種情況下,您只需要創建“寬”dataframe(並刪除BPcum
列)。
pairs(df.wide %>% select(-BPcum))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.