如何使ggplot2中的可变条宽度不重叠或间隙

问题描述 投票:11回答:2

根据documentation的说法,当geom_bar有固定的宽度条时,它似乎效果最好 - 甚至条形之间的空格似乎也是由宽度决定的。但是,当你有可变宽度时,它没有像我预期的那样响应,导致不同条之间的重叠或间隙(如图所示here)。

要了解我的意思,请尝试这个非常简单的可重复示例:

x <- c("a","b","c")
w <- c(1.2, 1.3, 4) # variable widths
y <- c(9, 10, 6) # variable heights

ggplot() + 
geom_bar(aes(x = x, y = y, width = w, fill=x), 
 stat="identity", position= "stack")

我真正想要的是不同的条形图只是触摸,但不重叠,就像在直方图中一样。

我试过添加position= "stack""dodge""fill,但都没有用。解决方案是在geom_histogram还是我没有正确使用geom_bar

附:要查看间隙问题,请尝试在上面的代码中用4替换0.5并查看结果。

r ggplot2 histogram geom-bar
2个回答
14
投票

似乎没有任何简单的解决方案,因此我们应该将q轴视为连续的w并手动计算蜱和条形中心所需的位置(this是有用的):

# pos is an explicit formula for bar centers that we are interested in:
#        last + half(previous_width) + half(current_width)
pos <- 0.5 * (cumsum(w) + cumsum(c(0, w[-length(w)])))
ggplot() + 
  geom_bar(aes(x = pos, width = w, y = y, fill = x), stat = "identity") + 
  scale_x_continuous(labels = x, breaks = pos)


1
投票
© www.soinside.com 2019 - 2024. All rights reserved.