[英]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 的出現百分比。 我嘗試按持續時間分組,但沒有成功。
你可以做:
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.