我有数据框,包括四列 . 有一个名为 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
的 status
值的任何条形图(并且y轴不是百分比) .
为什么没有绘制 0
?怎么解决这个?
数据框为csv:https://pastebin.com/Y7CfwPbf
实际上,第一个链接的问题解决了我的问题,但我想知道是否有可能在没有中间步骤的情况下实现这一点,我们创建一个新的数据帧 .
2 回答
perc
可以动态创建和使用,如下所示:如果您希望为相同的
hour
条保持相同的颜色,则:这是你要找的东西吗?
请参阅文章“How to plot a 'percentage plot' with ggplot2” .
代码: