如何绘制变量作为堆叠条形图的比率(百分比)?
问题描述:
我有数据框由四列组成。有一列叫做status
,它有二进制值:0
或1
。如何绘制变量作为堆叠条形图的比率(百分比)?
基于hour
分组数据后,我希望能有代表行与0
和1
在status
列中的百分比堆叠barplots。
在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))
然而得到的情节不显示任何barplots为0
status
值(和y轴是不是百分比)。
为什么0
没有绘制?如何解决这个问题?
数据帧为csv:https://pastebin.com/Y7CfwPbf
其实,第一个链接的问题回答我的问题,但我不知道是否有可能实现这一目标,而不必在这里我们创建一个新的数据框的中间步骤。
答
这是你要找的东西吗?
请参阅文章 “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))
答
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))
接近,但酒吧必须堆叠和总结,以100% –
我不知道怎么用了中间'data.frame'去实现它。 – djhurio