我想制作一个反向金字塔图形,其中条形图彼此堆叠,宽度不同.
1,我有一个堆积条形图,如下面的代码示例
library(dplyr)
library(ggplot2)
sample <- data_frame(x=c(1, 1, 1, 1, 2, 2, 2, 2),
y=c(5,10,15, 20, 10, 5, 20, 10),
w=c(1, 2, 3, 4, 1, 2, 3, 4),
group=c("a", "b", "c", "d", "a", "b", "c", "d"))
ggplot() +
geom_bar(data=sample,
aes(x=x,y=y,group=group, fill=group),
stat="identity", position=position_stack())
Run Code Online (Sandbox Code Playgroud)
然后我添加了宽度,aes因此w值较小的那个将会更小,而它们仍然相互堆叠.然而,酒吧并没有叠加警告.
ggplot() +
geom_bar(data=sample,
aes(x=x,y=y,group=group, fill=group, width=w/5),
stat="identity", position=position_stack())
Run Code Online (Sandbox Code Playgroud)
Warning: Ignoring unknown aesthetics: width
Warning message:
position_stack requires non-overlapping x intervals
Run Code Online (Sandbox Code Playgroud)
任何有助于制作条形图的帮助或者可以涵盖类似概念的不同情节类型的想法将受到高度赞赏.谢谢!
这有点像黑客.
我将使用geom_rect()而不是真正的列.因此,我需要data.frame()为矩形边界创建预先计算的位置.
df_plot <- sample %>%
arrange(desc(group)) %>% # Order so lowest 'groups' firtst
group_by(x) %>%
mutate(yc = cumsum(y), # Calculate position of "top" for every rectangle
yc2 = lag(yc, default = 0) ,# And position of "bottom"
w2 = w/5) # Small scale for width
# Plot itself
ggplot(df_plot) +
geom_rect(
aes(xmin = x - w2 / 2, xmax = x + w2 / 2,
ymin = yc, ymax = yc2,
group = group, fill=group))
Run Code Online (Sandbox Code Playgroud)