【问题标题】:How to create stacked bar chart如何创建堆积条形图
【发布时间】:2020-10-21 12:37:22
【问题描述】:

我希望能够创建堆积条形图,但是当我更改 stat ="identity" 时出现错误:"Error in FUN(X[[i]], ... ): 找不到对象'prop'"

这是我的代码:

    ggplot(data = wq,aes(x=WHO_Risk_Level,group=1))+
  geom_bar(aes(y=..prop..,fill=factor(..x..)),stat ="count")+
  labs(y="Percent",x="WHO Risk Level")+
  scale_y_continuous(labels = scales::percent_format())+
  guides(
    fill=FALSE
  )

【问题讨论】:

    标签: r ggplot2 tidyverse


    【解决方案1】:

    当你指定 x 作为因子时,我认为你不能堆叠它。一种先计数并绘制的方法:

    set.seed(111)
    wq = data.frame(WHO_Risk_Level=sample(c("High","Intermediate","Low"),1000,
    prob=c(0.25,0.35,0.4),replace=TRUE))
    
    library(dplyr)
    
    wq %>% 
    count(WHO_Risk_Level) %>% 
    mutate(proportion=100*n/sum(n)) %>% ggplot(aes(x=1,y=proportion,fill=WHO_Risk_Level)) + 
    geom_bar(stat="identity") +
    theme(axis.title.x=element_blank(),
            axis.text.x=element_blank(),
            axis.ticks.x=element_blank())
    

    【讨论】:

      【解决方案2】:

      我认为您需要的参数是 position = "stack"。 stat = "identity" 将使条形图成为 y 轴上事物的计数,而 stat = "bin" 将像直方图。在 geom_bar() 中尝试 position = "stack" 在我看来 position = "dodge" 是这里的默认值

      ggplot(data = wq,aes(x=WHO_Risk_Level,group=1))+
        geom_bar(aes(y=..prop..,fill=factor(..x..)),stat ="count", position = "stack")+
        labs(y="Percent",x="WHO Risk Level")+
        scale_y_continuous(labels = scales::percent_format())+
        guides(
          fill=FALSE
      

      )

      【讨论】: