如何在ggplot2中创建同时包含颜色、线型、点形状的图例
问题原因
你当前代码的问题在于使用宽格式数据分别绘制y1、y2的各个图层,所有美学属性(颜色、线型、点形状)都是硬编码的固定值,没有映射到同一个分类变量上,导致ggplot无法自动将多个维度的特征合并到同一个图例中。
解决方案
将宽格式数据转换为长格式,把y1/y2作为分类变量,将颜色、线型、点形状都统一映射到该分类变量,同时保持三个美学映射的scale名称一致,即可自动合并生成包含所有区分特征的完整图例。
完整可运行代码
# 加载依赖包 library(ggplot2) library(tidyr) # 原始数据 Conc <- c(2.5, 1.25, 0.625, 0.3125, 0.15625, 0.078, 0.039, 0) y2 <- c(1.422616667, 1.26845, 1.149133333, 0.842166667, 0.4697, 0.251566667, 0.118133333, 0.000233333) y1 <- c(1.4364, 1.342333333, 1.155216667, 0.88485, 0.502266667, 0.2673, 0.110783333, -0.000233333) sd1 <- c(0.12252713, 0.09232539, 0.046399526, 0.078883881, 0.014853518, 0.039726687, 0.012708213, 0.005837722) sd2 <- c(0.183093342, 0.122781068, 0.088565849, 0.110920994, 0.036569081, 0.02125754, 0.012588791, 0.002873616) # 构建宽格式数据框 wide_data <- data.frame(Conc, y1, y2, sd1, sd2) # 转换为长格式,把y和sd对应到同一分组变量 long_data <- pivot_longer(wide_data, cols = -Conc, names_to = c(".value", "group"), names_pattern = "(y|sd)(\\d)") # 补充分组名称前缀 long_data$group <- paste0("y", long_data$group) # 绘图 ggplot(long_data, aes(x = Conc, y = y)) + geom_line(aes(color = group, linetype = group), linewidth = 1.3) + geom_point(aes(color = group, shape = group), size = 3) + geom_errorbar(aes(ymin = y - sd, ymax = y + sd, color = group), width = 0.05) + # 统一设置三个美学映射的取值,保持name参数完全一致才会合并图例 scale_color_manual(name = "Legend", values = c("y1" = "red", "y2" = "blue")) + scale_linetype_manual(name = "Legend", values = c("y1" = "solid", "y2" = "dashed")) + scale_shape_manual(name = "Legend", values = c("y1" = 15, "y2" = 2)) + # 标签设置 labs(x = "Concentration in micg per mL", y = "Absorbance", title = "Absorbance as a function of Concentration") + # 主题设置 theme(plot.title = element_text(hjust = 0.5, face = "bold"))
内容的提问来源于stack exchange,提问作者Brian
相关产品推荐
相关产品推荐

