我的数据如下所示,每一行都是不同的项目:
Year <- c(2020, 2020, 2020, 2020, 2020, 2020, 2021, 2021, 2021, 2021, 2021)
Group <- c(1, 2, 1, 1, 2, 2, 1, 2, 1, 2, 2)
Type <- c(1, 0, 1, 0, 1, 0, 1, 1, 0, 0, 0)
df <- data.frame(Year, Group, Type)
我想要一个关于按组分组、然后按年份分面的类型百分比的堆积图表。
Type
按 Year
和 Group
分组的百分比。Group
和 Type
变量转换为因子。geom_bar()
函数创建绘图。完整代码:
# Data remains the same
Year <- c(2020, 2020, 2020, 2020, 2020, 2020, 2021, 2021, 2021, 2021, 2021)
Group <- c(1, 2, 1, 1, 2, 2, 1, 2, 1, 2, 2)
Type <- c(1, 0, 1, 0, 1, 0, 1, 1, 0, 0, 0)
# Step 1: Create a new percent variable counting the types
df <- data.frame(Year, Group, Type) %>%
group_by(Year, Group) %>%
count(Type) %>%
mutate(perc_type = n / sum(n)) # Percent
# Step 2: Convert variables into factors
df$Group <- as.factor(df$Group)
df$Type <- as.factor(df$Type)
# Step 3: Create the plot
df %>%
ggplot(aes(x = Group, y = perc_type, fill = Type)) +
geom_bar(stat = "identity") +
scale_y_continuous(labels = scales::percent) + # This function allows the variable to be visualized as a percent
facet_wrap(vars(Year))
希望有帮助。