根据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
并查看结果。
似乎没有任何简单的解决方案,因此我们应该将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)
您现在可以使用mekko
包执行此操作:https://cran.r-project.org/web/packages/mekko/vignettes/mekko-vignette.html