
如您所見,這兩個圖例之間有相當大的垂直空間,并且它們不在情節的中心。
有沒有辦法對齊兩個圖例,使它們看起來像這樣:

我不確定是否可以使用cowplot... 或者有沒有辦法使用 ggplot 的注釋來放置圖例?
uj5u.com熱心網友回復:
正如 Stefan 建議的那樣,我可能會拼湊,但在 cowplot 中,您可能需要調整圖例邊距:
theme_margin <- theme(legend.box.margin = margin(100, 10, 100, 10))
legend <- cowplot::get_legend(allPlots[[1]] theme_margin)
legend1 <- cowplot::get_legend(newPlot theme_margin)
combineLegend <- cowplot::plot_grid(
legend,
legend1,
nrow = 2)
# now make plot
cowplot::plot_grid(plotGrid,
combineLegend,
rel_widths = c(0.9, 0.11),
ncol = 2)

uj5u.com熱心網友回復:
如果您可以選擇切換到另一個軟體包,我建議您使用patchwork將您的情節粘合在一起。拼湊提供的一個功能是,使用plot_spacer您可以輕松地在圖例上方和下方添加一些空面板,以將它們“移動”到中心,從而擺脫空白空間。根據您的最終結果或最終情節的高度,您可能需要使用heights和/或widths引數:
library(cowplot)
library(ggplot2)
library(patchwork)
set.seed(123)
# create some data
dat <- NULL
for (i in 1:20) {
x <- LETTERS[1:5]
y <- paste0("var", seq(1, 5))
dat[[i]] <- expand.grid(X = x, Y = y)
dat[[i]]$Z <- runif(25, 0, 1)
}
# plotting function
plotFun <- function(data) {
ggplot(data, aes(X, Y, fill = Z))
geom_tile()
theme(
aspect.ratio = 1,
legend.justification = c(0, 1),
axis.text.x = element_blank(),
axis.ticks.x = element_blank(),
axis.text.y = element_blank(),
axis.ticks.y = element_blank()
)
labs(x = NULL, y = NULL)
}
# set up to plot on a grid
allPlots <- lapply(dat, plotFun)
allPlotsAlter <- lapply(allPlots, function(x) x theme(legend.position = "none"))
n <- length(allPlotsAlter)
nRow <- floor(sqrt(n))
plotGrid <- wrap_plots(grobs = allPlotsAlter, nrow = nRow)
# create a different type of legend
newPlot <- ggplot(iris, aes(x = Sepal.Length, y = Petal.Length, fill = Species))
geom_bar(stat = "identity")
theme(legend.justification = c(0, 1))
# get both legends and combine
legend <- cowplot::get_legend(allPlots[[1]])
legend1 <- cowplot::get_legend(newPlot)
combineLegend <- plot_spacer() legend legend1 plot_spacer() plot_layout(ncol = 1, heights = c(.5, 1, 1, .5))
wrap_elements(plotGrid) combineLegend plot_layout(widths = c(4, 1))

轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/449415.html
上一篇:在forloop中回圈不同的顏色并在RStudio中保存它們
下一篇:從requests_html匯入ModuleNotFoundError:沒有名為“requests_html”的模塊
