R语言ggplot多元素图表(柱形/点/线)全图例配置方法问询
解决ggplot组合图表的图例显示问题
我来帮你搞定这个图例的问题!你当前的代码里,柱形的填充色、点的颜色/形状、线条的颜色都是直接在geom_*函数里硬编码的,没有通过aes()映射到类别变量,所以ggplot没法自动生成包含所有元素的图例。下面是修改后的完整代码,以及关键修改点的说明:
修改后的完整代码
library(ggplot2) library(dplyr) # 你的数据定义 d1 <- c("Uttar Pradesh", "Rajasthan","Maharashtra","Madhya Pradesh") d2 <- c(12142, 12357, 15422, 17986) d3 <- c(26571, 22123, 28119, 21177) d4 <- c(38877, 31496, 35606, 37158) d5 <- c(98145, 76275, 88596, 95433) compend6 <- data.frame(d1, d2, d3, d4, d5) colnames(compend6) <- c("Name of the State/ UT", "Deposits", "Borrowings", "Loans & Advances", "Total Liabilities") # 你的变量定义 positions <- compend6$`Name of the State/ UT` plot1_name <- "Total Liabilities" plot2_name <- "Deposits" plot3_name <- "Loans & Advances" plot4_name <- "Borrowings" # 修改后的绘图代码 gp1 <- compend6 %>% ggplot(aes(group = 1)) + # 柱形图:将fill映射到plot1_name,生成图例项 geom_bar(mapping = aes(x = `Name of the State/ UT`, y = .data[[plot1_name]], fill = plot1_name), stat = "identity", color = "Black") + # Deposits点:color映射到plot2_name,size保留数值映射 geom_point(mapping = aes(x = `Name of the State/ UT`, y = .data[[plot2_name]], size = .data[[plot2_name]], color = plot2_name)) + # Loans点:color和shape都映射到plot3_name geom_point(mapping = aes(x = `Name of the State/ UT`, y = .data[[plot3_name]], size = .data[[plot3_name]], color = plot3_name, shape = plot3_name)) + # Borrowings线:color映射到plot4_name geom_line(mapping = aes(x = `Name of the State/ UT`, y = .data[[plot4_name]], color = plot4_name), size = 2) + ylab(expression("Balance Sheet Size")) + scale_x_discrete(limits = positions) + scale_y_continuous(limits = c(0,100000)) + # 手动指定填充色,统一图例名称为"Metrics" scale_fill_manual(name = "Metrics", values = c("Total Liabilities" = "yellow")) + # 手动指定所有类别的颜色 scale_color_manual(name = "Metrics", values = c("Total Liabilities" = "yellow", "Deposits" = "Blue", "Loans & Advances" = "Red", "Borrowings" = "#218906")) + # 手动指定形状:仅Loans用方形,其他设为NA隐藏 scale_shape_manual(name = "Metrics", values = c("Total Liabilities" = NA, "Deposits" = 16, "Loans & Advances" = 15, "Borrowings" = NA)) + # 调整图例:隐藏size的图例,合并所有图例项 guides(size = "none", fill = guide_legend(order = 1), color = guide_legend(order = 1), shape = guide_legend(order = 1)) + theme(legend.position = c(0.8, 0.8)) + coord_flip() gp1
关键修改点说明
- 将视觉属性移入
aes():把fill、color、shape这些属性从geom_*的参数移到aes()里,绑定到对应的系列名称(比如fill = plot1_name)。这样ggplot会把每个系列识别为一个类别,从而生成对应的图例项。 - 统一图例名称:所有
scale_*_manual的name参数都设为"Metrics",这样ggplot会自动把填充、颜色、形状的图例合并成一个,而不是生成多个独立的图例。 - 手动指定视觉样式:通过
scale_fill_manual、scale_color_manual、scale_shape_manual为每个系列指定你想要的颜色和形状,不需要形状的系列(比如柱形和线条)设为NA即可。 - 隐藏size图例:因为你用
size来表示数值大小,不是作为类别区分,所以用guides(size = "none")把它隐藏,避免干扰主图例的展示。 - 合并图例顺序:用
guide_legend(order = 1)确保所有图例项都合并到同一个组里,显示顺序符合你的预期。
这样修改后,你就能得到包含全部4种元素的图例:黄色柱形对应Total Liabilities,蓝色实心圆点对应Deposits,红色方形对应Loans & Advances,绿色线条对应Borrowings。
内容的提问来源于stack exchange,提问作者Makarand Padhye
相关产品推荐
相关产品推荐

