2013-08-25 56 views
4

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

这是一个失败的尝试:

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

enter image description here

ggplot(m[1:3,], aes(x,y)) + geom_bar(stat="identity") 

enter image description here

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

回答

4

编辑:

看样子OP只是希望这样的:

library(gridExtra) 
grid.arrange(p1,arrangeGrob(p2,widths=c(1,2),ncol=2), ncol=1) 

我不知道,如果可能的话绝对宽度传递给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) 

我用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) 

enter image description here

+0

谢谢,有没有反正只是为了缩小图的宽度 - 使酒吧的宽度和空间不变? – Ali

+0

我不完全确定你想要达到什么。也许调整比例限制? – Roland

+0

我已经更新了这个问题。我需要酒吧宽度和酒吧之间的空格是相同的两个情节(所以第二个情节的宽度约为自动第一.3)。如何调整规模限制可以帮助我实现目标?你有个例子吗? – Ali

0

裹在仅需要一个单一的图表的功能的其他建议。

fixedWidth <- function(graph, width=0.1) { 
    g2 <- graph 

    #store the old widths 
    old.unit <- g2$grobs[[4]]$children[[2]]$width[[1]] 
    original.attibutes <- attributes(g2$grobs[[4]]$children[[2]]$width) 

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

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

    #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 

    return(g2) 
}