繁体   English   中英

我可以使用ggplot为R中的百分比制作分组条形图吗?

[英]Can I making a grouped barplot for percentages in R using ggplot?

这听起来像是一个流行的情节,但我真的试图在没有任何解决方案的情况下弄清楚它! 我可以制作一个图表来显示每个持续时间内每个阻塞车道的出现百分比吗? 我的数据是

data<- structure(list(Lanes.Cleared.Duration = c(48, 55, 20, 38, 22, 
32, 52, 21, 39, 14, 69, 13, 14, 13, 25), Blocked.Lanes = c(1L, 
2L, 1L, 2L, 5L, 3L, 3L, 1L, 3L, 2L, 2L, 2L, 2L, 3L, 1L), Durations = structure(c(3L, 
3L, 2L, 3L, 2L, 3L, 3L, 2L, 3L, 2L, 4L, 2L, 2L, 2L, 2L), .Label = c("<10", 
"<30", "<60", "<90", "<120", ">120"), class = "factor")), row.names = c(NA, 
-15L), na.action = structure(c(`17` = 17L, `26` = 26L, `28` = 28L, 
`103` = 103L, `146` = 146L, `166` = 166L, `199` = 199L, `327` = 327L, 
`368` = 368L, `381` = 381L, `431` = 431L, `454` = 454L, `462` = 462L, 
`532` = 532L, `554` = 554L, `703` = 703L, `729` = 729L, `768` = 768L, 
`769` = 769L, `785` = 785L, `970` = 970L, `1043` = 1043L, `1047` = 1047L, 
`1048` = 1048L, `1081` = 1081L, `1125` = 1125L), class = "omit"), class = "data.frame") 

我尝试了以下代码,它给了我实际持续时间而不是百分比。 这是我的代码。

data %>% 
  ggplot(aes(fill=factor(Blocked.Lanes), y=Lanes.Cleared.Duration, x=Durations)) + 
  geom_bar(position="dodge", stat="identity")

我的结果应该显示每个 Duration 内每个 Blocked lane 的出现百分比。 我尝试按持续时间分组,但没有成功。

不是很优雅,但您可以先按持续时间和封锁车道进行统计,然后再按分组持续时间计算百分比。

df1 <- data %>% group_by(Durations, Blocked.Lanes) %>% tally() 

df1 <- df1 %>% ungroup %>% group_by(Durations) %>% mutate(perc = n/sum(n))

ggplot(df1, aes(fill=factor(Blocked.Lanes), y=perc, x=Durations)) + 
  geom_bar(position="dodge", stat="identity")

在此处输入图像描述

你可以做:

library(tidyverse)

data %>%
  count(Durations, Blocked.Lanes) %>%
  group_by(Durations) %>%
  mutate(n = prop.table(n) * 100) %>%
  ggplot(aes(fill = factor(Blocked.Lanes),  y = n, x = Durations)) +
  geom_bar(position = "dodge", stat = "identity") +
  ylab("Percentage of Blocked Lane") +
  guides(fill = guide_legend(title = "Blocked Lane"))

输出

在此处输入图像描述

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM