这是这个问题的后续问题。OP 要求一种方法以特定距离安排地块的一部分。我认为 teunbrand 给出了一个很好的答案。
我自己的建议(用cowplot提取图例,并以所需比例将它们缝合到图上)并不完全令人满意,因为它在给定示例中只是“偶然”起作用-图例标签足够长以将图例集中到第三个绘图的视口。
较短的标签揭示了问题 - 添加 grob 时,拼凑此 grob 居中,基本上向所有侧面均等填充。
我的问题是,你知道控制这种填充行为的方法吗?
Cowplot(或任何其他 ggplot 组合包)也非常受欢迎。
library(tidyverse)
library(patchwork)
data <- midwest %>%
head(5) %>%
select(2,23:25) %>%
pivot_longer(cols=2:4,names_to="Variable", values_to="Percent") %>%
mutate(Variable=factor(Variable,
levels=c("percbelowpoverty","percchildbelowpovert","percadultpoverty"),
labels = paste0("perc", 1:3)))
p1 <-
ggplot(data=data, mapping=aes(x=county, y=Percent, fill=Variable)) +
geom_col() +
scale_fill_manual(values = c("#CF232B","#942192","#000000")) +
theme(legend.background = element_rect(fill = "grey50"))
p_legend <- cowplot::get_legend(p1)
p_main <- p1 <-
ggplot(data=data, mapping=aes(x=county, y=Percent, fill=Variable)) +
geom_col(show.legend = FALSE) +
scale_fill_manual(values = c("#CF232B","#942192","#000000"))
p_main + plot_spacer() + p_legend +
plot_layout(widths = c(12.5, 1.5, 4)) &
theme(plot.margin = margin(),
plot.background = element_rect(colour = "black"))
不太理想的结果 - 图例 grob(灰色背景)应与左侧绘图边框(黑线)对齐
由reprex 包于 2021-04-09 创建(v1.0.0)