这个问题是这个问题的后续问题。 OP要求一种在特定距离内排列剧情部分的方法。我认为Teunbrand给出了一个很好的答案。 我自己的建议(用牛皮纸提取传奇,并以期望的比例缝合它们到一个地块上)并不完全令人满意,因为它在给定的示例中仅“偶然地”起作用 - 传说标签足够长,足以将传说grob集中到第三个情节的视口中。 the缩短标签揭示了问题 - 添加一个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"))
不是那么想要的结果 - 传奇人物(带有灰色背景)应与左图边框(黑线)对齐
由Reprex软件包(V1.0.0)在2021-04-09创建
update
通过将传说理由设置为ggplot2 >= 3.5.0
,可以更轻松地实现所需的结果。另请注意,由于版本中的
"left"
S指南系统的变化,我切换到ggplot2
提取传说:
>= 3.5.0
用Rreprexv2.1.1
于2025-03-16创建原始答案就我而言,问题不在一边。看看传奇的布局
cowplot::get_plot_component
我们看到它由5行和5列组成,传说将放置在中心的小区中:library(patchwork)
library(ggplot2)
packageVersion("ggplot2")
#> [1] '3.5.1'
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"),
legend.justification.right = "left"
)
p_legend <- cowplot::get_plot_component(p1, "guide-box-right")
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")
)
因此,当添加传奇时,patchwork
gtable
布局所需的。
一个控制传说定位或填充的选项是通过p_legend <- cowplot::get_legend(p1)
p_legend
#> TableGrob (5 x 5) "guide-box": 2 grobs
#> z cells name
#> 99_a788e923bf245af3853cee162f5f8bc9 1 (3-3,3-3) guides
#> 0 (2-4,2-4) legend.box.background
#> grob
#> 99_a788e923bf245af3853cee162f5f8bc9 gtable[layout]
#> zeroGrob[NULL]
gtable::gtable_show_layout(p_legend)
挤压第一列,如果需要,通过添加带有所需量的填充量的新列来添加一些填充物,可以通过
patchwork
gtable