gpt4 book ai didi

R: grid.arrange 边缘图到 ggplot2 "heatmap"(geom_tile)

转载 作者:行者123 更新时间:2023-12-04 10:59:48 25 4
gpt4 key购买 nike

我想在热图的顶部和右侧添加两个条形图,表示沿着热图表示的双变量分布的两个维度的边际分布。

这是一些代码:

library(gridExtra)
library(ggExtra)
library(cowplot)

# generate some data
df_hm = cbind(
expand.grid(
rows = sample(letters, 10),
cols = sample(LETTERS, 10)
),
value = rnorm(100)
)

# plot the heatmap
gg_hm = df_hm %>%
ggplot(aes(x = rows, y = cols, fill = value)) +
geom_tile() +
theme(legend.position = "bottom")

gg_rows = df_hm %>%
group_by(rows) %>%
summarize(value = mean(value)) %>%
ggplot(aes(x = rows,y = value)) +
geom_bar(stat = "identity", position = "dodge")

gg_cols = df_hm %>%
group_by(cols) %>%
summarize(value = mean(value)) %>%
ggplot(aes(x = cols, y = value))+
geom_bar(stat = "identity", position = "dodge") +
coord_flip()

gg_empty = df_hm %>%
ggplot(aes(x = cols, y = value)) +
geom_blank() +
theme(axis.text = element_blank(),
axis.title = element_blank(),
line = element_blank(),
panel.background = element_blank())

# try this with grid.arrange
grid.arrange(gg_rows, gg_empty, gg_hm, gg_cols,
ncol = 2, nrow = 2, widths = c(3, 1), heights = c(1, 3))

产生这个: enter image description here

我想要做的是移动图形以对齐,如红色箭头所示:- (1, 1) 的 y 轴应与 (2, 1) 的 y 轴对齐- (2, 1) 的 x 轴应与 (2, 2) 的 x 轴对齐

最佳答案

我尝试了 renato vitolo 接受的答案,但对齐在我的机器上不起作用。但我随后发现了一个更简单的解决方案:egg 包(在 CRAN 上可用)。 egg 提供了一个名为 ggarrangegrid.arrange 版本,它采用类似的参数但可以很好地对齐轴。在 OP 的代码中,我只需添加 library(egg)library(dplyr),然后将 grid.arrange 替换为 ggarrange(已使用 install.packages("egg") 安装了 egg)。

完整代码:

library(gridExtra)
library(cowplot)
library(egg)
library(dplyr)

# generate some data
df_hm = cbind(
expand.grid(
rows = sample(letters, 10),
cols = sample(LETTERS, 10)
),
value = rnorm(100)
)

# plot the heatmap
gg_hm = df_hm %>%
ggplot(aes(x = rows, y = cols, fill = value)) +
geom_tile() +
theme(legend.position = "bottom")

gg_rows = df_hm %>%
group_by(rows) %>%
summarize(value = mean(value)) %>%
ggplot(aes(x = rows,y = value)) +
geom_bar(stat = "identity", position = "dodge")

gg_cols = df_hm %>%
group_by(cols) %>%
summarize(value = mean(value)) %>%
ggplot(aes(x = cols, y = value))+
geom_bar(stat = "identity", position = "dodge") +
coord_flip()

gg_empty = df_hm %>%
ggplot(aes(x = cols, y = value)) +
geom_blank() +
theme(axis.text = element_blank(),
axis.title = element_blank(),
line = element_blank(),
panel.background = element_blank())

ggarrange(
gg_rows, gg_empty, gg_hm, gg_cols,
nrow = 2, ncol = 2, widths = c(3, 1), heights = c(1, 3)
)

输出:

Output

关于R: grid.arrange 边缘图到 ggplot2 "heatmap"(geom_tile),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38856309/

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