首页 文章

如何绘制变量值的比例(百分比)作为堆积条形图?

提问于
浏览
0

我有数据框,包括四列 . 有一个名为 status 的列,它具有二进制值: 01 .

在基于 hour 对数据进行分组之后,我希望在 status 列中使用 01 表示行的百分比的堆积条形图 .

在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))

但是,结果图未显示 statusstatus 值的任何条形图(并且y轴不是百分比) .

enter image description here

为什么没有绘制 0 ?怎么解决这个?

数据框为csv:https://pastebin.com/Y7CfwPbf

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

2 回答

  • 0

    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))
    

    enter image description here

    如果您希望为相同的 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))
    

    enter image description here

  • 0

    这是你要找的东西吗?

    enter image description here

    请参阅文章“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))
    

相关问题