如何使ggplot2中的变量栏宽度不重叠或有间隙 [英] How to make variable bar widths in ggplot2 not overlap or gap
问题描述
geom_bar似乎在固定宽度的条上工作得最好 - 即使条之间的空格似乎是由宽度决定的,根据很有用): p>
#pos是我们感兴趣的酒吧中心的明确公式:
#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)
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).
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?
P.s. to see the issue with gaps, try replacing 4
with 0.5
in the above code and see the outcome.
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):
# 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中的变量栏宽度不重叠或有间隙的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!