2017-08-15 177 views
2

我想制作一个反向金字塔图,其中酒吧堆叠在一起,宽度不同。ggplot2 - 不同宽度的堆叠酒吧

第一,我有堆积条形图如下代码示例

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

enter image description here

然后,我添加宽度aes所以具有较低w值将变小,同时他们仍然堆叠在彼此。但是,酒吧没有堆叠警告。

ggplot() + 
geom_bar(data=sample, 
     aes(x=x,y=y,group=group, fill=group, width=w/5), 
     stat="identity", position=position_stack()) 

enter image description here

Warning: Ignoring unknown aesthetics: width 
Warning message: 
position_stack requires non-overlapping x intervals 

任何有助于对堆叠化妆柱状图中或在不同的图表类型,可以覆盖类似的概念想法,将不胜感激。谢谢!

回答

6

这有点破解。

我将使用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)) 

所得的情节: enter image description here

3

一个相当长的版本,用丝带

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

# make factors for non-numeic items 
sample$x <- factor(sample$x) 
sample$group <- factor(sample$group) 

# calcualte cumulative sums 
sample2 <- sample %>% 
    group_by(x) %>% 
    arrange(desc(group)) %>% 
    mutate(ycum=cumsum(y)) %>% 
    ungroup() %>% 
    select(x, group, ycum, w) 

# Ffor each point, make another row lagged 
sample2lead <- sample2 %>% 
    group_by(x) %>% 
    mutate(ycum = lag(ycum, default=0), w=lag(w, default=max(sample2$w))) %>% 
    ungroup() %>% 
    select(x, group, ycum, w) 

# combine 
combined <- bind_rows(sample2, sample2lead) %>% 
    arrange(x, ycum, desc(group)) 


# plot a ribbon forming trapezoids 
ggplot() + 
    geom_ribbon(data=combined, 
      aes(x=ycum, ymin=-w/2, ymax=w/2, fill=group)) + 
    coord_flip() + 
    facet_grid(~x) 

enter image description here