如何保留DOY配色逻辑,将绘图图例替换为实际日期?
问题解决:按DOY配色并显示实际日期图例
问题说明
需要绘制2021-2023年湖泊深度(Y轴)与温度(X轴)的时间序列数据,单月多采样日期按**Day of Year(DOY)**区分配色,但图例需显示实际采样日期。
原始代码存在的问题
Depth、Temp、DOY为字符型,会导致绘图时数值排序异常、连线逻辑错误- 图例直接显示DOY数值,不符合需求
修改后的代码(基础场景:每个DOY对应唯一日期)
library(tidyverse) # 修正数据类型:将字符型转为数值型 Temperature <- tibble(Depth = as.numeric(c('1' ,'2', '3' , '1', '2', '3')), Date = c('1/18/2021', '1/18/2021', '1/18/2021', '3/11/2021', '3/11/2021', '3/11/2021'), DOY = as.numeric(c('18', '18', '18', '70', '70', '70')), Temp = as.numeric(c('1', '2.5', '3.5', '1.2', '2.0', '2.5'))) # 建立DOY与实际日期的对应映射 date_labels <- Temperature %>% distinct(DOY, Date) %>% arrange(DOY) %>% pull(Date) %>% set_names(.$DOY) # 绘图:按DOY配色,图例显示实际日期 Temperature %>% ggplot(aes(x = Temp, y = Depth, colour = factor(DOY), group = DOY)) + geom_point() + geom_path() + scale_y_reverse(limits = c(5, 0)) + scale_x_continuous(limits = c(0, 4)) + scale_color_discrete(labels = date_labels, name = "采样日期") + theme_bw()
扩展场景:同DOY对应不同年份日期(同DOY同色)
如果存在不同年份但DOY相同的采样日期,需要让这些日期使用同一种颜色,同时图例显示实际日期,可使用以下代码:
library(tidyverse) # 构造包含同DOY不同年份的示例数据 Temperature_extended <- tibble(Depth = as.numeric(c('1' ,'2', '3' , '1', '2', '3', '1', '2', '3')), Date = c('1/18/2021', '1/18/2021', '1/18/2021', '3/11/2021', '3/11/2021', '3/11/2021', '1/18/2022', '1/18/2022', '1/18/2022'), DOY = as.numeric(c('18', '18', '18', '70', '70', '70', '18', '18', '18')), Temp = as.numeric(c('1', '2.5', '3.5', '1.2', '2.0', '2.5', '0.8', '2.2', '3.2'))) # 为每个DOY分配专属颜色 doy_colors <- scales::hue_pal()(length(unique(Temperature_extended$DOY))) %>% set_names(unique(Temperature_extended$DOY)) # 建立日期到DOY的映射 date_to_doy <- Temperature_extended %>% distinct(Date, DOY) %>% deframe() # 绘图:同DOY日期使用同色,图例显示实际日期 Temperature_extended %>% ggplot(aes(x = Temp, y = Depth, colour = Date, group = Date)) + geom_point() + geom_path() + scale_y_reverse(limits = c(5, 0)) + scale_x_continuous(limits = c(0, 4)) + scale_color_manual(values = doy_colors[date_to_doy], name = "采样日期") + theme_bw()
关键修改点
- 转换数值列类型,确保绘图逻辑正常
- 通过
scale_color_discrete或scale_color_manual替换图例标签为实际日期 - 针对不同数据场景,灵活选择颜色映射的变量(DOY或Date),同时保证配色符合DOY区分的需求
内容的提问来源于stack exchange,提问作者Daniela
相关产品推荐
相关产品推荐

