我有一个条形图的情况,我希望一些级别被堆叠,一些级别被躲避。这可能吗?这是一个工作示例。
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")
在上面的示例中,图 1 和图 2(从左开始)是标准条形图。图3已修改为我想要的内容。我希望“full”级别保持“dodged”状态,而“parta”和“partb”堆叠在一起。
这是一个虚拟示例。但是,实际用途是当我想展示时 某事物的全部值(value),然后展示它如何分解为子组件。上面的例子是一个单一的分割。也许有人想要显示多个分割。见下图。
红色是由一定量的蓝色和绿色组成的。绿色又由一定量的黄色和粉色组成。也许有更好的方法来做到这一点。
最佳答案
这是你想要的吗?我改编自@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)
关于R ggplot2 : Barplot partial/semi stack,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37795648/