ggplot barplots中的恒定宽度 [英] Constant width in ggplot barplots

查看:121
本文介绍了ggplot barplots中的恒定宽度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用ggplot使多个条形图的条形和它们之间的间隔固定,并且每个图上的条形数量不同?

How to make the width of bars and spaces between them fixed for several barplots using ggplot, having different number of bars on each plot?

这是失败的尝试:

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

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

width=1添加到geom_bar(...)也无济于事.我需要自动绘制第二个图,以使其宽度小于第一个图,并且条的宽度和间距与第一个图相同.

Adding width=1 to geom_bar(...) doesn't help as well. I need the second plot automatically to have less width and the same bar width and spaces as the first one.

推荐答案

OP似乎只是想这样做:

It appears the OP simply wants this:

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


我不确定是否可以将绝对宽度传递给geom_bar.因此,这是一个丑陋的骇客:


I am not sure, if it's possible to pass absolute widths to geom_bar. So, here is an ugly hack:

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和孩子.如有必要,您可以使用更复杂的方法对此进行概括.

I used str to find the correct grob and child. You could use more sophisticated methods to generalize this if necessary.

#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)

这篇关于ggplot barplots中的恒定宽度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆