R ggplot2:Barplot部分/半堆栈

时间:2016-06-13 17:20:39

标签: r ggplot2

我有一个条形图情况,我想要一些层次叠加,一些要被躲避。这可能吗?这是一个有效的例子。

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(左起)是标准的条形图。图3被修改为我正在寻找的东西。我希望将'full'等级保持'躲避'而将'parta'和'partb'叠加在一起。

这是一个虚拟的例子。但是,实际使用是我想展示的时候 某物的全部值,然后显示它如何分裂成子组件。上面的示例是单个拆分。也许人们可能希望展示多个分裂。见下图。

split

红色由一定量的蓝色和绿色组成。绿色进一步由一定量的黄色和粉红色组成。也许有更好的方法来做到这一点。

1 个答案:

答案 0 :(得分:3)

这是你想要的吗?我改编自@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