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

时间:2017-10-04 09:14:59

标签: r plot ggplot2 bar-chart

我的数据框由四列组成。有一个名为object.fields = dict((field.name, getattr(obj, field.name)) for field in object._meta.fields) 的列,其二进制值为status0

根据1对数据进行分组后,我希望堆叠的条形图表示hour列中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)

并提出了这个解决方案:

status

但是,结果图未显示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)) 的{​​{1}}值的任何条形图(并且y轴不是百分比)。

enter image description here

为什么没有绘制status?怎么解决这个问题?

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

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

2 个答案:

答案 0 :(得分:0)

这是你要找的东西吗?

enter image description here

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

代码:

EmployeeID

答案 1 :(得分: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