我想使用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
Run Code Online (Sandbox Code Playgroud)
我知道我可以通过使用facet来避免这个问题,但是我的真实情节比这个图更复杂.
Val*_*tin 11
一个额外有趣的解决方案是此评论中建议的解决方案- 尝试在两个图之间添加一个额外的空图并调整相对列宽:
plot4 <- plot_grid(plot1, NULL, plot2, rel_widths = c(1, 0, 1), align = "hv",
labels = c("A", "B"), nrow = 1)
plot4
Run Code Online (Sandbox Code Playgroud)
甚至可以在 中尝试负值rel_widths,这会产生更好的结果:
plot5 <- plot_grid(plot1, NULL, plot2, rel_widths = c(1, -0.1, 1), align = "hv",
labels = c("A", "B"), nrow = 1)
plot5
Run Code Online (Sandbox Code Playgroud)
因此,尝试组合调整plot.margin(如@J.Con 所回答)并通过调整rel_widths.
编辑 2019-12-11
另请查看(Claus Wilke)作者的评论cowplot:
对于这些类型的问题,我现在会推荐
patchwork图书馆。plot_grid()由于其底层设计,它本质上是困难的
因此,patchwork基于他们的小插图添加注释和样式的快速示例如下所示:
plot4 <- plot_grid(plot1, NULL, plot2, rel_widths = c(1, 0, 1), align = "hv",
labels = c("A", "B"), nrow = 1)
plot4
Run Code Online (Sandbox Code Playgroud)

由reprex 包(v0.3.0)于 2019 年 12 月 11 日创建
你的plot.margins 实际上是在和你作对。将它们设置为零以填充该空白区域。
plot1 <- ggplot(data1, aes(x=x, y = y1)) +
geom_bar(stat ="identity", position=position_dodge(), fill = "grey")+
theme(plot.margin = unit(c(0,0,0,0), "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,0,0,0), "cm")) + xlab2 + ylab2
plot2
plot3 <- plot_grid(plot1, plot2, labels = c("A", "B"), align = "hv",nrow = 1, ncol = 2)
plot3
Run Code Online (Sandbox Code Playgroud)