簡體   English   中英

創建一個堆疊分組的條形圖,每個條形圖具有不同的類別?

[英]Creating a stacked-grouped barplot with different categories per bar ggplot?

我有四個變量:類別、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)
)

從技術上講,沒有辦法在 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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM