如何基于两个不同DataFrame使用ggplot绘制折线图?
问题描述
我有两个DataFrame:decils_general:
structure(list(grup_CNAE_Red = c("Total", "Total", "Total", "Total", "Total", "Total", "Total", "Total", "Total", "Total"), variable = structure(1:10, levels = c("decil1_inflacio", "decil2_inflacio", "decil3_inflacio", "decil4_inflacio", "decil5_inflacio", "decil6_inflacio", "decil7_inflacio", "decil8_inflacio", "decil9_inflacio", "decil10_inflacio"), class = "factor"), value = c(9.3, 8.9, 8.6, 8.4, 8.4, 8.4, 8.2, 8.1, 8.2, 7.8)), row.names = c(NA, -10L), class = "data.frame")
以及decils_primera:
structure(list(grup_despesa_DGAPE = c("Total", "Total", "Total", "Total", "Total", "Total", "Total", "Total", "Total", "Total" ), variable = structure(1:10, levels = c("decil1_inflacio", "decil2_inflacio", "decil3_inflacio", "decil4_inflacio", "decil5_inflacio", "decil6_inflacio", "decil7_inflacio", "decil8_inflacio", "decil9_inflacio", "decil10_inflacio" ), class = "factor"), value = c(5.8, 5.7, 5.6, 5.3, 5, 4.9, 4.8, 4.4, 4.4, 3.9)), row.names = c(NA, -10L), class = "data.frame")
我想绘制一张折线图,以variable为X轴、value为Y轴,样式为两条折线分别对应两个数据集(带清晰标识)。尝试了以下代码但未成功:
plot_decils_general_primera <- ggplot() + geom_line(data = decils_general, aes(x=variable, y=value)) + geom_line(data = decils_primera, aes(x=variable, y=value))
解决方案
代码未生效的核心原因:
- X轴的
variable是因子类型,绘制折线图时未明确分组映射,导致线条无法正确连接和区分 - 两个数据集分开绘制时缺少统一的分组标识,不利于图例生成和样式美化
推荐方案:合并数据集为长格式绘制
这种方式更符合ggplot的语法逻辑,便于后续调整:
整理数据
library(tidyverse) # 给数据集添加分组标签 decils_general <- decils_general %>% mutate(group = "总体通胀") decils_primera <- decils_primera %>% mutate(group = "第一类支出通胀") # 合并两个数据集,并提取分位数编号优化X轴显示 combined_data <- bind_rows(decils_general, decils_primera) %>% mutate(decil = as.integer(str_extract(variable, "\\d+")))绘制折线图
plot_decils <- ggplot(combined_data, aes(x = decil, y = value, color = group, group = group)) + geom_line(linewidth = 1) + geom_point(size = 2) + # 添加数据点匹配目标样式 scale_x_continuous(breaks = 1:10, labels = paste0("Decil ", 1:10)) + scale_y_continuous(limits = c(3, 10)) + labs( x = "收入分位数", y = "通胀率(%)", title = "不同收入分位数的通胀对比", color = "类别" ) + theme_minimal() + theme( plot.title = element_text(hjust = 0.5, size = 14, face = "bold"), axis.title = element_text(size = 12), legend.position = "top" ) print(plot_decils)
替代方案:不合并数据集直接绘制
如果不想合并数据,可直接给每条折线指定分组和样式:
plot_decils <- ggplot() + geom_line(data = decils_general, aes(x = variable, y = value, group = 1), color = "#1f77b4", linewidth = 1) + geom_line(data = decils_primera, aes(x = variable, y = value, group = 1), color = "#ff7f0e", linewidth = 1) + geom_point(data = decils_general, aes(x = variable, y = value), color = "#1f77b4", size = 2) + geom_point(data = decils_primera, aes(x = variable, y = value), color = "#ff7f0e", size = 2) + scale_x_discrete(labels = paste0("Decil ", 1:10)) + labs( x = "收入分位数", y = "通胀率(%)", title = "不同收入分位数的通胀对比" ) + theme_minimal() + theme(plot.title = element_text(hjust = 0.5))
内容的提问来源于stack exchange,提问作者Maria
相关产品推荐
相关产品推荐

