如何为ggplot绘制的柱状折线图添加自定义温度图例
ggplot 柱状/折线图添加自定义图例解决方案
核心问题
你之前的代码没有为颜色映射提供明确的分组标识,导致ggplot无法生成图例。以下是两种可行的解决方法:
方法一:整理数据为长格式(推荐)
将温度数据转换为长格式,统一处理两个温度系列,代码更简洁易维护:
library(tidyverse) # 预处理数据:转换月份为指定顺序的因子,将温度列转成长格式 Weather_data_long <- Weather_data_R %>% mutate(Month = factor(Month, level = c('Dec','Jan','Feb','Mar','Apr',"May",'Jun','Jul','Aug'))) %>% pivot_longer( cols = c(`Max temp-avg`, `Min temp-avg`), names_to = "Temp_Type", values_to = "Temperature" ) %>% mutate(Temperature_scaled = Temperature * 10) # 适配右侧Y轴刻度 # 绘图 ggplot(Weather_data_long, aes(x = Month)) + geom_col(aes(y = `Rainfall (mm)`), fill = "grey", color = "black") + # 统一映射颜色到Temp_Type分组 geom_point(aes(y = Temperature_scaled, color = Temp_Type)) + geom_path(aes(y = Temperature_scaled, color = Temp_Type, group = Temp_Type), size = 0.7) + # 自定义颜色与图例标题 scale_color_manual( values = c("Max temp-avg" = "red", "Min temp-avg" = "green"), name = "Temperature" ) + scale_y_continuous(sec.axis = sec_axis(~./10, name = "Temperature (ᵒC)")) + xlab("Month") + theme_classic()
关键说明:
pivot_longer将宽格式的温度列合并为Temp_Type(分组标识)和Temperature(数值)两列,让ggplot能自动识别图例分组geom_path中指定group = Temp_Type,确保每个温度系列的线条正确连接scale_color_manual直接定义分组对应的颜色,并设置图例标题为"Temperature"
方法二:直接修改原有代码
如果不想调整数据格式,可在原有代码基础上为每个温度系列添加明确的分组标识:
ggplot(Weather_data_R, aes(x=factor(Month, level=c('Dec','Jan','Feb','Mar','Apr',"May",'Jun','Jul','Aug')))) + geom_col(aes(y=`Rainfall (mm)`), fill= "grey", color = "black") + # 把颜色值替换为分组名称,放入aes中 geom_point(aes(y=`Max temp-avg`*10, color = "Max")) + geom_path(aes(y=`Max temp-avg`*10, color = "Max"), group=1, size = 0.7) + geom_point(aes(y=`Min temp-avg`*10, color = "Min")) + geom_path(aes(y=`Min temp-avg`*10, color = "Min"), group=1, size = 0.7) + # 映射分组名称到对应颜色,设置图例标题 scale_color_manual( values = c("Max" = "red", "Min" = "green"), name = "Temperature" ) + scale_y_continuous(sec.axis = sec_axis(~./10, name = "Temperature (ᵒC)")) + xlab("Month") + theme_classic()
关键说明:
- 将原代码中
colour = "red"改为color = "Max"并放入aes()内,让ggplot将"Max"视为一个分组,同理处理"Min" - 通过
scale_color_manual将分组名称映射到指定颜色,同时设置图例标题
内容的提问来源于stack exchange,提问作者Erik
相关产品推荐
相关产品推荐

