如何在ggplot中为数据框不同列指定名称和颜色生成对应图例
ggplot多数值列生成图例解决方案
ggplot的图例默认基于映射到color、shape等美学属性的分类变量的不同取值自动生成,要为三个独立数值列生成对应图例,可通过以下两种方案实现:
方案1:宽表转长表(推荐)
该方案符合ggplot的设计逻辑,后续修改扩展性更强
- 第一步:加载依赖包,完成宽表转长表操作
library(tidyverse) # 将宽格式数据转为长格式 df_long <- df %>% pivot_longer( cols = c(ewmValues, ewmValues2, ewmValues3), names_to = "指标类型", values_to = "数值" )
- 第二步:绘图时将
color映射到新生成的指标类型列,自动生成图例
ggplot(df_long, aes(x = ewmSlots, y = 数值, color = 指标类型)) + geom_line(linewidth = 1) + # 可替换为其他geom类型 # 自定义各系列颜色和图例标签 scale_color_manual( values = c("ewmValues" = "#1f77b4", "ewmValues2" = "#ff7f0e", "ewmValues3" = "#2ca02c"), labels = c("ewmValues" = "系列1", "ewmValues2" = "系列2", "ewmValues3" = "系列3") ) + labs(color = "系列名称") # 自定义图例标题
方案2:不转换表结构直接绘图
如果不想调整原数据结构,可手动为每个geom指定颜色映射逻辑
ggplot(df, aes(x = ewmSlots)) + geom_line(aes(y = ewmValues, color = "ewmValues"), linewidth = 1) + geom_line(aes(y = ewmValues2, color = "ewmValues2"), linewidth = 1) + geom_line(aes(y = ewmValues3, color = "ewmValues3"), linewidth = 1) + scale_color_manual( name = "系列名称", values = c("ewmValues" = "#1f77b4", "ewmValues2" = "#ff7f0e", "ewmValues3" = "#2ca02c"), labels = c("系列1", "系列2", "系列3") )
内容的提问来源于stack exchange,提问作者Shadow
相关产品推荐
相关产品推荐

