我的数据框由四列组成。有一个名为object.fields = dict((field.name, getattr(obj, field.name)) for field in object._meta.fields)
的列,其二进制值为status
或0
。
根据1
对数据进行分组后,我希望堆叠的条形图表示hour
列中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)
并提出了这个解决方案:
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轴不是百分比)。
为什么没有绘制status
?怎么解决这个问题?
数据框为csv:https://pastebin.com/Y7CfwPbf
实际上,第一个链接的问题解决了我的问题,但我想知道是否有可能在没有中间步骤的情况下实现这一点,我们会创建一个新的数据帧。
答案 0 :(得分:0)
答案 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))
如果您希望为相同的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))