在R的ggplot2中按温度异常用红蓝渐变填充两条线间区域
实现气温异常值的渐变填充效果
需求说明
基于当年月均温与历史月均温数据,在ggplot2中填充两条曲线间的区域:
- 当年气温高于历史时(正异常)填充红色,异常值越高颜色越深
- 当年气温低于历史时(负异常)填充蓝色,异常值越低颜色越深
数据准备
df <- data.frame( month = c("01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12"), tmean = c(20, 22, 20, 28, 30, 32, 34, 33, 30, 27, 24, 18), tmean_ref = c(18, 20, 23, 27, 29, 31, 33, 32, 29, 26, 22, 19), tano = c(2, 2, -3, 1, 1, 1, 1, 1, 1, 1, 2, -1), tano_label = c("+2", "+2", "-3", "+1", "+1", "+1", "+1", "+1", "+1", "+1", "+2", "-1") ) # 将月份转为有序因子,确保x轴按自然顺序排列 df$month <- factor(df$month, levels = c("01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12"))
完整代码实现
library(ggplot2) library(ggrepel) ggplot(data = df, aes(x = month, group = 1)) + # 填充两条曲线间的区域,映射填充色为异常值tano geom_ribbon(aes(ymin = pmin(tmean, tmean_ref), ymax = pmax(tmean, tmean_ref), fill = tano), alpha = 0.6) + # 设置渐变配色:负异常蓝色,正异常红色,中间白色 scale_fill_gradient2(low = "#1a75ff", mid = "white", high = "#ff4d4d", midpoint = 0, name = "气温异常值(℃)") + # 当年气温实线 geom_line(aes(y = tmean), linewidth = 0.85, lineend = "round", na.rm = TRUE) + # 历史气温虚线 geom_line(aes(y = tmean_ref), linetype = "longdash", na.rm = TRUE) + # 当年气温数据点 geom_point(aes(y = tmean), na.rm = TRUE) + # 异常值标签 geom_label_repel(aes(y = tmean, label = tano_label), segment.color = NA, na.rm = TRUE) + # 调整主题与标签 labs(x = "月份", y = "平均气温(℃)", title = "当年与历史月均温对比及气温异常") + theme_minimal()
代码关键说明
geom_ribbon:通过ymin和ymax分别取两条气温线的最小值和最大值,实现区域填充;将fill映射到tano(气温异常值),为渐变效果提供依据scale_fill_gradient2:自定义三色渐变配色,以0为中点区分正负异常,同时设置颜色名称用于图例- 调整月份为有序因子:避免x轴月份按字符排序出现混乱
内容的提问来源于stack exchange,提问作者piblo95
相关产品推荐
相关产品推荐

