gpt4 book ai didi

r - 使用Cowplot时减少地 block 之间的边距

转载 作者:行者123 更新时间:2023-12-04 14:55:35 31 4
gpt4 key购买 nike

我想使用Cowplot将一些图形组合在一起。但是我无法更改边距大小。我只想使用一个y轴,但是余量仍然很大,我想减小它。我使用了来自ggplot的plot.margin代码,尽管当我查看单个图时该代码有效,但将这些图合并后似乎不起作用。

我做了一些示例代码:

library(ggplot2) 
library(cowplot)

x <- c("a", "b")
y1 <- c(3,6)
y2 <- c(10,15)
data1 <- data.frame(x,y1)
data2 <- data.frame(x, y2)

ylab1 <- ylab("Very nice y values")
xlab1 <- xlab("Very nice factors")

plot1 <- ggplot(data1, aes(x=x, y = y1)) +
geom_bar(stat ="identity", position=position_dodge(), fill = "grey")+
theme(plot.margin = unit(c(0.5,0.5,0.5,0.5), "cm")) + xlab1 + ylab1
plot1

ylab2 <- ylab("")
xlab2 <- xlab("Very nice factors")

plot2 <- ggplot(data2, aes(x=x, y = y2)) +
geom_bar(stat = "identity",position=position_dodge(), fill = "grey")+
theme(plot.margin = unit(c(0.5,0.5,0.5,-0.5), "cm")) + xlab2 + ylab2
plot2

plot3 <- plot_grid(plot1, plot2, labels = c("A", "B"), align = "hv",nrow = 1, ncol = 2)

plot3 # Quite large margin between the two plots

我知道我可以通过使用构面来避免此问题,但是我的真实情节比这张图要复杂得多。

enter image description here

最佳答案

in this issue也解决了增加plot_grid中的图之间的空间。

另一个有趣的解决方案是建议的in this comment-尝试在两个图之间添加一个额外的空图并调整相对列宽:

plot4 <- plot_grid(plot1, NULL, plot2, rel_widths = c(1, 0, 1), align = "hv",
labels = c("A", "B"), nrow = 1)
plot4

enter image description here

甚至可以在o​​jit_code中尝试使用负值,从而获得更好的结果:
plot5 <- plot_grid(plot1, NULL, plot2, rel_widths = c(1, -0.1, 1), align = "hv",
labels = c("A", "B"), nrow = 1)
plot5

enter image description here

因此,请尝试调整 rel_widths(由@ J.Con回答),并通过调整 plot.margin添加一个额外的空图。

编辑2019-12-11

还要检查 rel_widths(Claus Wilke)作者的 this comment:

For those kinds of problems I would now recommend the patchwork library. It's inherently difficult with plot_grid(), due to its underlying design



因此,基于小插图 Adding Annotation and Stylecowplot的快速示例如下所示:

library(patchwork)

plot3 <- plot1 + plot2 +
plot_annotation(tag_levels = 'A') &
theme(plot.tag = element_text(size = 8))
plot3

reprex package(v0.3.0)创建于2019-12-11

关于r - 使用Cowplot时减少地 block 之间的边距,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41834093/

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