[英]Create a stacked bar chart grouped by multiple x parameters
我在創建堆疊條形圖時遇到困難,其中 x 軸有多個分組。
df <- data.frame(random = c(1, 1, 1, 1, 1, 1, 1),
value = c("s1", "s1", "s1", "s1", "s1", "s2", "s3"),
countries = factor(c("US", "Japan", "UK", "Germany", "France", "France", "France")),
week = factor(c("week1", "week2", "week1", "week2", "week1", "week1", "week2")))
在此示例中,我嘗試按week和countries對 x 軸進行分組。 我想通過按周、國家和價值分組來顯示價值出現次數的百分比。 我希望條形圖的 output 顯示為:
我目前的代碼是:
result <- df %>% group_by_(df$countries, df$week, df$value) %>% summarise(total = n()) #get number of occurences
ggplot(result, aes(x = interaction(result[["countries"]], result[["week"]]), y = result[["total"]], fill = result[["total"]])) +
geom_bar(position = "fill", stat = "identity") +
scale_y_continuous(labels = scales::percent_format())
你能幫我解決這個邏輯嗎? 我相信 scale_y_continuous(labels = scales::percent_format()) 應該為我計算百分比。
不完全確定填充變量應該是什么。
result <- df %>%
unite("group", countries:week, sep = ", ") %>%
count(group, value) %>%
group_by(group) %>%
mutate(p = round(n / sum(n), 2))
ggplot(result, aes(x = group, y = p, fill = as.factor(value))) +
geom_bar(position = "fill", stat = "identity") +
scale_y_continuous(labels = scales::percent_format()) +
coord_flip()
編輯
如果我理解正確,請嘗試:
result <- df %>%
unite("group", countries:week, sep = ", ") %>%
count(group, value) %>%
group_by(group) %>%
mutate(p = round(n / sum(n), 2)) %>%
separate("group", c("country", "week"), sep = ", ")
ggplot(result, aes(x = week, y = p, fill = as.factor(value))) +
geom_bar(position = "fill", stat = "identity", width = 0.5) +
facet_grid(~country,scales = "free_x") +
scale_y_continuous(labels = scales::percent_format())
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.