2016-06-13 97 views
2

我有一个barplot的情况,我希望一些层次被堆叠和一些躲闪。这可能吗?这是一个工作示例。R ggplot2:Barplot部分/半堆栈

library(ggplot2) 
library(reshape) 

dat <- data.frame(name=c("a","b","c","d"), 
      full=c(124,155,122,145), 
      parta=c(86,72,40,26), 
      partb=c(38,83,82,119)) 

dat1 <- reshape::melt(dat,id.vars=c("name")) 

#stack 
ggplot(dat1,aes(x=name,y=value,group=variable,fill=variable))+ 
    geom_bar(stat="identity",position="stack")+ 
    ggtitle("stack") 

#dodge 
ggplot(dat1,aes(x=name,y=value,group=variable,fill=variable))+ 
    geom_bar(stat="identity",position="dodge")+ 
    ggtitle("dodge") 

partial-stack

在上述例子中,图1和图2(左)是标准barplots。图3被修改为我正在寻找的内容。我想要'完整'级别保持'闪避',而'parta'和'partb'要堆叠在一起。

这是一个虚拟的例子。但是,实际使用是当我想显示某个东西的完整值时,然后显示如何分解成子组件。上面的例子是一个单独的分割。也许人们可能想要展示多个分割。见下图。

split

红是由一定量的蓝色和绿色的。绿色还包含一定量的黄色和粉红色。也许有更好的方法来做到这一点。

+0

如果A部分和B部分总是等于满,为什么不干脆堆A和B? – Nate

+0

确实。编辑解释更多一点。 – rmf

+1

相关:[here](http://stackoverflow.com/questions/9493159/staggered-and-stacked-geom-bar-in-the-same-figure),[here](http://stackoverflow.com/问题/ 12715635/ggplot2-bar-plot-with-stack-and-dodge)和[here](https://stat.ethz.ch/pipermail/r-help/2008-October/177932.html) – Henrik

回答

2

这是你想要的吗?我改编自@Henrik指出的链接。

# 1st layer 
g1 <- ggplot(dat1 %>% filter(variable == "full"), 
      aes(x=as.numeric(name) - 0.15, weight=value, fill=variable)) + 
    geom_bar(position="identity", width=0.3) + 
    scale_x_continuous(breaks=c(1, 2, 3, 4), labels=unique(dat1$name)) + 
    labs(x="name") 

# 2nd layer 
g1 + geom_bar(data=dat1 %>% filter(grepl("part", variable)), 
       aes(x=as.numeric(name) + 0.15, fill=variable), 
       position="stack", width=0.3) 

enter image description here