【问题标题】:How to make variable bar widths in ggplot2 not overlap or gap如何使ggplot2中的可变条宽不重叠或间隙
【发布时间】:2014-01-08 09:58:45
【问题描述】:

geom_bar 似乎在具有固定宽度的条时效果最好 - 根据documentation,即使条之间的空间似乎也是由宽度决定的。但是,当您有可变宽度时,它不会像我预期的那样响应,从而导致不同条形之间的重叠或间隙(如图所示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


    【解决方案1】:

    似乎没有任何直接的解决方案,因此我们应该将 x 轴视为连续的 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)
    

    【讨论】:

    • 这解决了问题,非常感谢。也许 ggplot2 开发人员可以考虑将其添加为位置选项?
    • @RobinLovelace,没问题。也许,你可以尝试ask 一个。
    • 感谢您的建议。我做了这个github.com/hadley/ggplot2/issues/890,但在ggplot问题页面上看不到这个。似乎已被删除 - 有什么想法吗?
    • @RobinLovelace,对我来说似乎很好。如果他们认为应该添加此功能,我相信它将被移至“功能”。
    • 这样的事情使用scale_x_discrete不是更容易吗?
    【解决方案2】:

    您现在可以使用mekko 包执行此操作:https://cran.r-project.org/web/packages/mekko/vignettes/mekko-vignette.html

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-10-04
      • 2019-10-31
      • 2021-11-01
      • 1970-01-01
      • 2021-05-17
      相关资源
      最近更新 更多