在ggplot2中创建具有总频率和百分比的堆叠条形图,可以按照以下步骤进行:
library(ggplot2)
library(dplyr)
# 假设数据集名为df,包含两个变量:类别(category)和频率(frequency)
df_summary <- df %>%
group_by(category) %>%
summarise(total_frequency = sum(frequency),
percentage = total_frequency / sum(total_frequency) * 100)
ggplot(df, aes(x = category, y = frequency, fill = category)) +
geom_bar(stat = "identity") +
geom_text(aes(label = frequency), vjust = -0.5) +
labs(x = "类别", y = "频率") +
scale_fill_manual(values = c("#E69F00", "#56B4E9", "#009E73", "#F0E442", "#0072B2", "#D55E00", "#CC79A7")) +
theme_minimal()
ggplot(df_summary, aes(x = category, y = total_frequency, fill = category)) +
geom_bar(stat = "identity") +
geom_text(aes(label = paste0(total_frequency, " (", round(percentage, 1), "%)")), vjust = -0.5) +
labs(x = "类别", y = "频率") +
scale_fill_manual(values = c("#E69F00", "#56B4E9", "#009E73", "#F0E442", "#0072B2", "#D55E00", "#CC79A7")) +
theme_minimal()
这样就可以在ggplot2中创建具有总频率和百分比的堆叠条形图了。根据实际情况,可以调整颜色、标签位置等图形属性。腾讯云相关产品和产品介绍链接地址可以根据具体需求进行选择和添加。
领取专属 10元无门槛券
手把手带您无忧上云