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

时间:2021-11-03 13:24:58

geom_bar seems to work best when it has fixed width bars - even the spaces between bars seem to be determined by width, according to the documentation. When you have variable widths, however, it does not respond as I would expect, leading to overlaps or gaps between the different bars (as shown here).

geom_bar似乎在具有固定宽度的条形时工作得最好——根据文档,即使条形之间的空格似乎也是由宽度决定的。但是,当你有可变宽度时,它不会像我预期的那样响应,导致不同的条之间的重叠或间隙(如图所示)。

To see what I mean, please try this very simple reproducible example:

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

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

What I really want is for the different bars to be just touching, but not overlapping, like in a histogram.

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

I've tried adding position= "stack", "dodge", and "fill, but none work. Does the solution lie in geom_histogram or am I just not using geom_bar correctly?

我试过添加位置=“堆栈”、“减淡”和“填充”,但都不行。解决方案是在geom_histogram中还是我没有正确地使用geom_bar ?

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

P.s. to see the issue with gaps, try replacing 4 with 0.5 in the above code and see the outcome.

注意:如果要查看有差距的问题,请尝试用上面代码中的0.5替换4,并查看结果。

2 个解决方案

#1


14  

Seems that there isn't any straightforward solution, so we should treat x-axis as continuous in terms of w and manually compute required positions for ticks and bar centers (this is useful):

似乎没有任何直接的解,所以我们应该把x轴当作连续的w,手工计算蜱和棒中心所需的位置(这很有用):

# 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中的可变宽度不重叠或间隙

#2


1  

You can now do this with the mekko package: https://cran.r-project.org/web/packages/mekko/vignettes/mekko-vignette.html

您现在可以使用mekko包来实现这一点:https://cran.r project.org/web/packages/mekko/vignettes/mekko-vignette.html

#1


14  

Seems that there isn't any straightforward solution, so we should treat x-axis as continuous in terms of w and manually compute required positions for ticks and bar centers (this is useful):

似乎没有任何直接的解,所以我们应该把x轴当作连续的w,手工计算蜱和棒中心所需的位置(这很有用):

# 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中的可变宽度不重叠或间隙

#2


1  

You can now do this with the mekko package: https://cran.r-project.org/web/packages/mekko/vignettes/mekko-vignette.html

您现在可以使用mekko包来实现这一点:https://cran.r project.org/web/packages/mekko/vignettes/mekko-vignette.html