【问题标题】:How to plot the ratio (percentage) of values of a variable as stacked barplots?如何将变量值的比率(百分比)绘制为堆积条形图?
【发布时间】:2018-03-15 15:06:35
【问题描述】:

我有包含四列的数据框。有一个名为status 的列具有二进制值:0 或1。

根据hour 对数据进行分组后,我希望在status 列中显示具有0 和1 的行的百分比的堆叠条形图。

在 SO 中我发现了以下相关问题:

ggplot replace count with percentage in geom_bar

Show % instead of counts in charts of categorical variables

Create stacked barplot where each stack is scaled to sum to 100%

Creating a Stacked Percentage Bar Chart in R with ggplot

R stacked percentage bar plot with percentage of binary factor and labels (with ggplot)

并想出了这个解决方案:

ggplot(df4, aes(x=hour, y=status, fill=as.factor(status)) ) +
  geom_bar(stat="identity") + 
  facet_grid(status ~ .) + 
  scale_x_continuous(breaks=seq(0,25,1))

但是,结果图没有显示status 值0 的任何条形图(并且 y 轴不是百分比)。

为什么没有绘制0?如何解决?

csv 格式的数据框:https://pastebin.com/Y7CfwPbf

实际上,第一个链接问题回答了我的问题,但我想知道是否有可能在没有中间步骤的情况下实现这一点,即我们创建一个新的数据框。

【问题讨论】:

    标签: r plot ggplot2 bar-chart


    【解决方案1】:

    这是您要找的东西吗?

    参见文章“How to plot a 'percentage plot' with ggplot2”。

    代码:

    require(data.table)
    require(ggplot2)
    
    df4 <- fread("https://pastebin.com/raw/Y7CfwPbf")
    
    ggplot(df4, aes(x = hour, y = 100 * ..prop.., fill = factor(status))) +
      geom_bar() + 
      facet_grid(status ~ .) + 
      scale_x_continuous(breaks = seq(0, 25, 1))
    

    【讨论】:

    • 关闭,但条形必须堆叠起来,总和达到 100%
    • 我不知道如何在没有中间data.frame的情况下实现它。
    【解决方案2】:

    perc 可以即时创建和使用,如下所示:

      ggplot(df4 %>% group_by(status, hour) %>% 
             summarise (n = n()) %>% 
             mutate(perc = round(n / sum(n),3) * 100), 
           aes(x=hour, y=perc, fill=as.factor(perc))) +
      geom_bar(stat="identity") + 
      facet_grid(status ~ .) + 
      scale_x_continuous(breaks=seq(0,25,1)) 
    

    如果您希望为相同的hour 条保持相同的颜色,那么:

    ggplot(df4 %>% group_by(status, hour) %>% 
               summarise (n = n()) %>% 
               mutate(perc = round(n / sum(n),3) * 100), 
           aes(x=hour, y=perc,fill=as.factor(hour))) +
        geom_bar(stat="identity") + 
        facet_grid(status ~ .) + 
        scale_x_continuous(breaks=seq(0,25,1)) 
    

    【讨论】:

      猜你喜欢
      • 2019-09-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-06-08
      • 2021-12-22
      • 1970-01-01
      • 2021-05-31
      相关资源
      最近更新 更多