R ggplot2 : Barplot partial/semi stack

标签 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”级别保持“dodged”状态,而“parta”和“partb”堆叠在一起。

这是一个虚拟示例。但是,实际用途是当我想展示时 某事物的全部值(value),然后展示它如何分解为子组件。上面的例子是一个单一的分割。也许有人想要显示多个分割。见下图。

split

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

最佳答案

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

关于R ggplot2 : Barplot partial/semi stack,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37795648/

相关文章:

r - 在 ggplot2 中绘制带有指定时间段和注释事件的时间线

r - R 中的特定原因危险与多状态模型

r - ggplot2 map 上的多个站点

R 通过使用facet_wrap和数据子集的函数调用传递ggplot参数

r - 使用 dplyr 对多列求和时忽略 NA

r - ggplot2,如何移动直方图?

r - 没有开罗的ggplot unicode字符?

r - 跨平台 zip 文件创建

r - 出于教学目的,什么是真正干净清晰的 [R] 代码的好例子?

r - Levene 检验的多重比较事后检验