我想制作一个堆积条形图,显示 4 个案例研究中变量 SARREN、SCED 和 SPROP 的百分比,并有一列显示 4 个案例的总计。
我用更长的枢轴修改了数据库,以拥有包含三个变量的一列,并设法创建了一个带有计数的堆叠条形图,但是当包含position =“fill”时,我收到消息:忽略未知的美学:位置。
任何帮助将不胜感激。我还想向每个堆叠条添加标签,其中包含每个变量的百分比,但尚未找到解决方案。如果有人能给我这方面的提示,我也将非常感激。
这是我的所有权数据库的摘录:
structure(list(SPROP = c(100L, 0L, 0L, 70L, 6L, 0L, 0L, 0L, 10L,
45L, 100L), SARREN = c(0L, 100L, 100L, 20L, 94L, 100L, 100L,
100L, 90L, 55L, 0L), SCED = c(0L, 0L, 0L, 10L, 0L, 0L, 0L, 0L,
0L, 0L, 0L), CASE = c(2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L,
2L)), row.names = 10:20, class = "data.frame")
这是我到目前为止的代码:
ownership2 <- ownership %>%
pivot_longer(names_to = "variable", values_to = "value",-CASE)%>%
group_by(variable) %>%
ownership3 <- ownership2 %>%
mutate(case1 = as.factor(CASE))
# total count
ownership3 %>%
ggplot(aes(x=case1))+
geom_bar(aes(fill=factor(variable))) +
geom_bar(aes(x="Total", fill=factor(variable)))
我认为您正在寻找类似的东西。
看看:
# Pkgs
library(tidyverse)
library(palmerpenguins)
# Toy data
toy_data <- palmerpenguins::penguins %>%
mutate(species = factor(consecutive_id(species))) %>%
select(3:5, 1) %>%
filter(if_all(everything(), \(x) !is.na(x)))
colnames(toy_data) <- c("sprop", "sarren", "sced", "case")
# Wrangling to a longer format
toy_data <- pivot_longer(toy_data, -case)
# The plot
ggplot() +
geom_col(
aes(x = case, y = value, fill = name),
toy_data,
position = "fill") +
geom_col(
aes(x = case, y = value, fill = name),
summarise(toy_data, .by = name, case = "Total", value = sum(value)),
position = "fill")
创建于 2024-04-26,使用 reprex v2.1.0