我正在使用 ggplot 制作堆疊的條形圖,但由于某種原因,盡管使用相同的標準填充了其他條形圖,但由于某些原因,它仍然保留 2 個條形圖未填充。為什么要這樣做,我該如何防止這種情況發生?
library(ggplot2)
library(dplyr)
library(scales)
#Code to replicate
data <- tibble(team = factor(c(rep("Team 1", 10), rep("Team 2", 10), rep("Team 3", 10), rep("Team 4", 10)), levels = c("Team 1", "Team 2", "Team 3", "Team 4")),
state = factor(c(rep(c("Won", "Tied",
"Rematch", "Postponed", "Forfeit",
"Lost", "Withdrew", "Ongoing",
"Undetermined", "Unknown"), 4)), levels = c("Won", "Tied",
"Rematch", "Postponed", "Forfeit",
"Lost", "Withdrew", "Ongoing",
"Undetermined", "Unknown")),
count = c(1920, 80, 241, 5, 310, 99, 2, 127, 20, 33,
48, 1, 8, 0, 11, 3, 0, 4, 3, 3,
140, 5, 8, 0, 17, 2, 0, 5, 3, 7,
477, 20, 59, 1, 106, 1, 0, 33, 7, 10))
data <- data %>%
group_by(team) %>%
mutate(percentage = round((count/sum(count, na.rm = TRUE)), 2))
data %>%
ggplot(aes(fill= state, y = percentage, x = team))
geom_col(position="stack",width = 0.4)
coord_flip()
scale_y_continuous(labels = scales::percent_format(accuracy = 1), limits = c(0, 1))
geom_text(aes(label = scales::percent(percentage, accuracy = 1)),
position = position_stack(vjust = .5),
check_overlap = TRUE )
這是它的外觀;第 3 隊和第 2 隊的浮動 75% 和 59% 分別應該是用于第 4 隊和第 1 隊的鮭魚色。我知道這不是錯字,因為我對每個隊都使用相同的標題。

uj5u.com熱心網友回復:
將位置引數更改為 fill
data %>%
ggplot(aes(fill= state, y = percentage, x = team))
geom_col(position="fill",width = 0.4)
coord_flip()
scale_y_continuous(labels = scales::percent_format(accuracy = 1), limits = c(0, 1))
geom_text(aes(label = scales::percent(percentage, accuracy = 1)),
position = position_stack(vjust = .5),
check_overlap = TRUE )
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/398471.html
