创建每个条形ggplot具有不同类别的堆叠分组条形图?

时间:2020-05-28 16:05:56

标签: r ggplot2

我有四个变量:类别,x,y和z。 X轴应该是类别,每个类别应该有两个条,第一个条是x堆叠在z的顶部,第二条是y堆叠在z的顶部。看起来应该像链接了here的图像(z为蓝色):

sampledata <- data.frame(
  categories = c("2017", "2018", "2019", "2020"),
  x = c(2, 3, 0, 4),
  y = c(0, 2, 1, 4),
  z = c(1, 0 ,2 ,3)
)

1 个答案:

答案 0 :(得分:1)

从技术上讲,无法在geom_bar中直接组合堆叠样式和躲避样式。但是也许您可以做到这一点:

#Your data frame
sampledata <- data.frame(
  categories = c("2017", "2018", "2019", "2020"),
  x = c(2, 3, 0, 4),
  y = c(0, 2, 1, 4),
  z = c(1, 0 ,2 ,3)
)
#Reshape into tidy data
library(tidyverse)
sampledata2<-sampledata %>% 
  gather('x','y','z',key='variable',value='value')%>%
  mutate(group=ifelse(variable=='y','b','a')) #group into 2 groups (xz and yz)
sampledata2[13:16,]<-sampledata2[9:12,]
sampledata2[13:16,4]<-c('b','b','b','b')
sampledataA<-sampledata2 %>% 
  filter(group=='a')
sampledataB<-sampledata2 %>% 
  filter(group=='b')
#plot
barwidth=0.30
ggplot()+
#geom_bar for x and z
  geom_bar(data=sampledataA,
          mapping=aes(fill=variable,y=value,x=categories),
          position="stack", 
          stat="identity",
          width=barwidth)+
#geom_bar for y and z
geom_bar(data=sampledataB,
          mapping=aes(x=as.numeric(categories)+barwidth+0.1,fill=variable,y=value),
          position="stack", 
          stat="identity",
          width=barwidth)

更多信息(如果无效):https://community.rstudio.com/t/ggplot-position-dodge-with-position-stack/16425