如何使用aggregate函数输出的两个独立dataframe绘制堆叠柱状图
首先合并两份聚合后的数据集,再用ggplot2绘制堆叠柱状图即可,完整实现代码如下:
1. 数据预处理
# 重命名数据框列名,简化后续操作 colnames(Outright_owners) <- c("State", "owned_outright") colnames(Mortgage_owners) <- c("State", "owned_mortgage") # 合并两份数据 library(dplyr) owner_data <- inner_join(Outright_owners, Mortgage_owners, by = "State") # 转换为长格式适配ggplot绘图规则 library(tidyr) owner_data_long <- pivot_longer(owner_data, cols = -State, names_to = "ownership_type", values_to = "household_count")
2. 绘制堆叠柱状图
library(ggplot2) ggplot(owner_data_long, aes(x = State, y = household_count, fill = ownership_type)) + geom_col(position = "stack") + labs(x = "州/领地", y = "家庭户数", fill = "房屋持有类型", title = "澳大利亚各州房屋持有情况统计") + # 调整x轴标签角度避免重叠 theme(axis.text.x = element_text(angle = 45, hjust = 1)) + # 自定义配色,可按需调整 scale_fill_manual(values = c("owned_outright" = "#2E5984", "owned_mortgage" = "#78A6D3"), labels = c("全款持有", "贷款持有"))
如果不想使用tidyverse系列包,也可以用R基础绘图函数实现:
# 构造绘图矩阵 plot_mat <- rbind(Outright_owners[,2], Mortgage_owners[,2]) colnames(plot_mat) <- Outright_owners[,1] rownames(plot_mat) <- c("全款持有", "贷款持有") # 绘制堆叠柱状图 barplot(plot_mat, col = c("#2E5984", "#78A6D3"), xlab = "州/领地", ylab = "家庭户数", main = "澳大利亚各州房屋持有情况统计", las = 2, legend.text = rownames(plot_mat), args.legend = list(x = "topright"))
内容的提问来源于stack exchange,提问作者Pranav Sundaram
相关产品推荐
相关产品推荐

