[英]difficulty in using plot_grid and get_legend in R
我发现在 R 的 cowplot 中使用plot_grid()
和get_legend()
有困难
我使用下面的示例代码生成了六个图。 我想在 cowplot 中使用plot_grid()
来排列 4 行:
get_legend()
)行的相对高度 <- c(1, 4, 4, 1)
有人可以分享所需 plot 的代码吗?
library(tidyverse)
library(cowplot)
# FIRST FIVE PLOT
p1 <- list()
for (iter in 1:5)
{
# generate random points
x <- rnorm(100, mean = 0, sd = 1)
y <- rnorm(100, mean = 0, sd = 1)
# random array of 0 and 1
choice <- sample(c(0,1), replace=TRUE, size=100)
# tibble
tbl <- tibble(x, y, choice)
# plot
p1[[iter]] <- ggplot(data = tbl,
aes(x = x,
y = y,
color = choice)) +
geom_point() +
theme(legend.position = "bottom")
}
# SIXTH PLOT
# generate random points
x <- rnorm(100, mean = 5, sd = 5)
y <- rnorm(100, mean = 5, sd = 5)
# random array of 0 and 1
choice <- sample(c(0,1), replace=TRUE, size=100)
# tibble
tbl <- tibble(x, y, choice)
# plot
p2 <- ggplot(data = tbl,
aes(x = x,
y = y,
color = choice)) +
geom_point() +
theme(legend.position = "right")
title <- "Sample Plot"
# to be edited
plot_grid(p1[[1]], p1[[2]], p1[[3]],
p1[[4]], p1[[5]], p2,
nrow = 2)
看看这是否适合你:
# get title as a grob object
grob_title <- get_plot_component(p2 + ggtitle(title) +
theme(plot.title = element_text(hjust = 0.5)),
"title",
return_all = TRUE)[[2]]
plot_grid(
# row 1: center-aligned title
grob_title,
# row 2: 3 plots from list, each with legends intact
plot_grid(plotlist = p1[seq(1, 3)],
nrow = 1),
# row 3: 2 plots from list + p2, all with legend removed
plot_grid(p1[[4]] + theme(legend.position = "none"),
p1[[5]] + theme(legend.position = "none"),
p2 + theme(legend.position = "none"),
nrow = 1),
# row 4: legend from p2, lengthened (width can be adjusted) & rotated
get_legend(p2 +
theme(legend.key.width = unit(2, "cm"),
legend.position = "bottom")),
ncol = 1, rel_heights = c(1, 4, 4, 1))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.