如何在ggplot2中将多组解决方案的成本效益权衡图合并到同一画布?
在ggplot2中整合多个解决方案的成本效益权衡图
推荐方法:合并数据集并分组映射
这种方法更贴合ggplot2的设计逻辑,通过统一数据框和分组变量管理不同方案,扩展性更强。
步骤1:给数据集添加方案标识并合并
library(ggplot2) # 为每个数据集添加方案区分列 data_test = data.frame(x = c(100,102,103), y1 = c(30, 15, 30), y2 = c(30, 80, 30), solution = "方案1") data_test2 = data.frame(x = c(106,112,120), y1 = c(20, 3, 20), y2 = c(20, 76, 20), solution = "方案2") # 合并两个数据集 combined_data = rbind(data_test, data_test2)
步骤2:绘制整合后的图表
ggplot(combined_data, aes(x = x, group = solution)) + # 绘制上下边界线,用颜色区分方案 geom_line(aes(y = y1, colour = solution), linewidth = 1) + geom_line(aes(y = y2, colour = solution), linewidth = 1) + # 绘制填充区域,设置透明度避免遮挡 geom_ribbon(aes(ymin = y1, ymax = y2, fill = solution), alpha = 0.5) + # 绘制方案1的参考线段 geom_segment(data = subset(combined_data, solution == "方案1"), aes(x = 100, y = 30, xend = 103, yend = 30), colour = "blue", linetype = "dashed") + geom_segment(data = subset(combined_data, solution == "方案1"), aes(x = 102, y = 15, xend = 102, yend = 80), colour = "blue", linetype = "dashed") + # 绘制方案2的参考线段 geom_segment(data = subset(combined_data, solution == "方案2"), aes(x = 106, y = 20, xend = 120, yend = 20), colour = "red", linetype = "dashed") + geom_segment(data = subset(combined_data, solution == "方案2"), aes(x = 112, y = 3, xend = 112, yend = 76), colour = "red", linetype = "dashed") + # 自定义图例和样式 labs(title = "多解决方案成本效益权衡", x = "成本", y = "效益", colour = "解决方案", fill = "解决方案") + scale_colour_manual(values = c("方案1" = "blue", "方案2" = "red")) + scale_fill_manual(values = c("方案1" = "#1b98e0", "方案2" = "#e01b98")) + theme_minimal()
备选方法:直接添加第二个数据集的图层
如果不想合并数据,可以在原有图表基础上,为每个图层指定第二个数据集:
library(ggplot2) # 原方案数据 data_test = data.frame(x = c(100,102,103), y1 = c(30, 15, 30), y2 = c(30, 80, 30)) # 第二个方案数据 data_test2 = data.frame(x = c(106,112,120), y1 = c(20, 3, 20), y2 = c(20, 76, 20)) # 绘制基础图表(方案1) ggp = ggplot(data_test, aes(x = x)) + geom_line(aes(y = y1, colour = "方案1")) + geom_line(aes(y = y2, colour = "方案1")) + geom_ribbon(aes(ymin = y1, ymax = y2), fill = "#1b98e0", alpha = 0.5) + geom_segment(aes(x = 100, y = 30, xend = 103, yend = 30), colour = "blue") + geom_segment(aes(x = 102, y = 15, xend = 102, yend = 80), colour = "blue") # 添加方案2的所有图层 ggp + geom_line(data = data_test2, aes(x = x, y = y1, colour = "方案2")) + geom_line(data = data_test2, aes(x = x, y = y2, colour = "方案2")) + geom_ribbon(data = data_test2, aes(x = x, ymin = y1, ymax = y2), fill = "#e01b98", alpha = 0.5) + geom_segment(data = data_test2, aes(x = 106, y = 20, xend = 120, yend = 20), colour = "red") + geom_segment(data = data_test2, aes(x = 112, y = 3, xend = 112, yend = 76), colour = "red") + # 统一颜色映射 scale_colour_manual(values = c("方案1" = "blue", "方案2" = "red")) + labs(colour = "解决方案", title = "多解决方案成本效益权衡", x = "成本", y = "效益") + theme_minimal()
关键说明
- 合并数据集的方法更适合后续添加更多方案,只需给新数据集加
solution列再合并即可。 - 使用
subset()或直接指定data参数,可确保每个图层只调用对应方案的数据。 - 设置
alpha参数让填充区域透明,避免遮挡其他方案内容。
内容的提问来源于stack exchange,提问作者Katie G
相关产品推荐
相关产品推荐

