【发布时间】:2021-12-30 18:12:05
【问题描述】:
我正在使用 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 队的鲑鱼色。我知道这不是错字,因为我为每个队使用了相同的标题。
【问题讨论】:
-
你可以删除至少 60% 的代码,让它看起来更好看(让我们更容易找到问题。代码越少,我们发现问题的速度就越快问题)
-
@tjebo,完成!感谢您查看问题和建议。
-
舍入错误似乎使 ggplot 删除了最后一列。
limits=c(0,1.1)解决了它(或类似的东西)。编辑:@TarJae 解决方案更好地解决它。
标签: r ggplot2 colors bar-chart fill