ggplot条形图中的恒定宽度

Ali*_*Ali 7 r bar-chart ggplot2 geom-bar

如何使用多个条形图固定它们之间的条形和空间宽度,ggplot每个条形图上有不同数量的条形图?

这是一个失败的尝试:

m <- data.frame(x=1:10,y=runif(10))
ggplot(m, aes(x,y)) + geom_bar(stat="identity")
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

ggplot(m[1:3,], aes(x,y)) + geom_bar(stat="identity")
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

添加width=1geom_bar(...)没有很好的帮助.我需要第二个绘图自动具有较小的宽度和相同的条宽度和空间作为第一个.

Rol*_*and 6

编辑:

看起来OP只是想要这个:

library(gridExtra)
grid.arrange(p1,arrangeGrob(p2,widths=c(1,2),ncol=2), ncol=1)
Run Code Online (Sandbox Code Playgroud)

我不确定,是否可以传递绝对宽度geom_bar.所以,这是一个丑陋的黑客:

set.seed(42)
m <- data.frame(x=1:10,y=runif(10))
p1 <- ggplot(m, aes(x,y)) + geom_bar(stat="identity")
p2 <- ggplot(m[1:3,], aes(x,y)) + geom_bar(stat="identity")
g1 <- ggplotGrob(p1)
g2 <- ggplotGrob(p2)
Run Code Online (Sandbox Code Playgroud)

我曾经str找到正确的grob和孩子.如有必要,您可以使用更复杂的方法来概括它.

#store the old widths
old.unit <- g2$grobs[[4]]$children[[2]]$width[[1]]

#change the widths
g2$grobs[[4]]$children[[2]]$width <- rep(g1$grobs[[4]]$children[[2]]$width[[1]],
                                         length(g2$grobs[[4]]$children[[2]]$width))

#copy the attributes (units)
attributes(g2$grobs[[4]]$children[[2]]$width) <- attributes(g1$grobs[[4]]$children[[2]]$width)

#position adjustment (why are the bars justified left???)
d <- (old.unit-g2$grobs[[4]]$children[[2]]$width[[1]])/2
attributes(d) <- attributes(g2$grobs[[4]]$children[[2]]$x)
g2$grobs[[4]]$children[[2]]$x <- g2$grobs[[4]]$children[[2]]$x+d

#plot
grid.arrange(g1,g2)
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

  • `grid.arrange(p1,arrangeGrob(p2,widths = c(1,2),ncol = 2),ncol = 1)`适合你的需要?我确信它可以通过编程方式完成,但坦率地说,我没有看到你方面的任何努力,这并没有激励我. (3认同)