首页 > 解决方案 > 创建一个堆叠分组的条形图,每个条形图具有不同的类别?

问题描述

我有四个变量:类别、x、y 和 z。X 轴应该是类别,每个类别应该有两个条,第一个是 x 堆叠在 z 之上,第二个是 y 堆叠在 z 之上。它应该看起来像此处链接的图像(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)
)

标签: rggplot2

解决方案


从技术上讲,没有办法在 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


推荐阅读