如何使用
ggplot
使多个条形图的条形宽度和条形之间的间距固定,每个图上的条形数量不同?
这是一次失败的尝试:
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(...)
也没有帮助。我需要自动使第二个图具有较小的宽度以及与第一个图相同的条形宽度和空格。
编辑:
看来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和child。如有必要,您可以使用更复杂的方法来概括这一点。
#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)
将其他建议包装在一个仅需要单个图表的函数中。
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)
}
我解决了类似的问题:
mywidth = .5
ggplot(m, aes(x,y)) +
geom_col(width=log(1 + length(unique(m$x))) * mywidth)
因为 geom_bar() 尝试根据 x 轴变量有多少个唯一值来调整条形宽度,所以 log() 通过随着 x 的唯一值数量的增加而快速增加来“撤消”这一点,从而“展平”累积值geom_bar() + 自定义宽度为常量值。
1+只是为了处理log(1)=0。
您可以根据需要调整mywidth的值。