You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为ggplot图例中各站点添加对应颜色的平均值虚线

需求描述

使用ggplot绘制5个站点各3个数据点,按站点对线条和点进行颜色编码;同时绘制各站点的平均值,颜色与对应站点匹配但线条为虚线,希望在图例中每个站点的实线下方添加对应颜色的虚线(代表该站点平均值)。

数据

chl_no_est <- structure(list(sample_date = structure(c(1683763200, 1683763200, 
1683676800, 1683676800, 1683676800, 1689206400, 1689206400, 1689120000, 
1689120000, 1689120000, 1694649600, 1694649600, 1694563200, 1694649600, 
1694563200), tzone = "America/Los_Angeles", class = c("POSIXct", 
"POSIXt")), event = c("May 2023", "May 2023", "May 2023", "May 2023", 
"May 2023", "July 2023", "July 2023", "July 2023", "July 2023", 
"July 2023", "September 2023", "September 2023", "September 2023", 
"September 2023", "September 2023"), station_name = c("TMDL-R1", 
"TMDL-R2", "TMDL-CL", "TMDL-R3", "TMDL-R4", "TMDL-R1", "TMDL-R2", 
"TMDL-CL", "TMDL-R3", "TMDL-R4", "TMDL-R1", "TMDL-R2", "TMDL-CL", 
"TMDL-R3", "TMDL-R4"), var = c("Chlorophyll a", "Chlorophyll a", 
"Chlorophyll a", "Chlorophyll a", "Chlorophyll a", "Chlorophyll a", 
"Chlorophyll a", "Chlorophyll a", "Chlorophyll a", "Chlorophyll a", 
"Chlorophyll a", "Chlorophyll a", "Chlorophyll a", "Chlorophyll a", 
"Chlorophyll a"), result = c(8.86, 41.3, 8.01, 10.5, 112, 53.2, 
81.7, 61.9, 74.5, 103, 108, 53.3, 10.6, 27.8, 24.4), mean_var = c(56.6866666666667, 
58.7666666666667, 26.8366666666667, 37.6, 79.8, 56.6866666666667, 
58.7666666666667, 26.8366666666667, 37.6, 79.8, 56.6866666666667, 
58.7666666666667, 26.8366666666667, 37.6, 79.8)), class = c("grouped_df", 
"tbl_df", "tbl", "data.frame"), row.names = c(NA, -15L), groups = structure(list(
    station_name = c("TMDL-CL", "TMDL-R1", "TMDL-R2", "TMDL-R3", 
    "TMDL-R4"), .rows = structure(list(c(3L, 8L, 13L), c(1L, 
    6L, 11L), c(2L, 7L, 12L), c(4L, 9L, 14L), c(5L, 10L, 15L)), ptype = integer(0), class = c("vctrs_list_of", 
    "vctrs_vctr", "list"))), class = c("tbl_df", "tbl", "data.frame"
), row.names = c(NA, -5L), .drop = TRUE))


dry_season_1year_events <- data.frame(event = c("May 2023", "June 2023", "July 2023", "August 2023", "September 2023"))

解决方案

要实现图例中每个站点同时显示实线(原始数据)和虚线(平均值),可以通过自定义图例的外观来完成,以下是修改后的完整代码:

library(ggplot2)
library(dplyr)

# 预处理数据
annotation_mean_chl <- chl_no_est %>% 
  select(event, station_name, result) %>% 
  group_by(station_name) %>% 
  mutate(avg_result = mean(result))

chl_no_est$event <- factor(chl_no_est$event, levels = dry_season_1year_events$event)

annotation_chl <- data.frame(
  x = c("May 2023"),
  y = c(158),
  label = c("Target Seasonal Average: 150 mg/m2")
)

# 自定义图例:为每个站点添加对应颜色的虚线
custom_legend <- guide_legend(
  override.aes = list(
    linetype = rep(c(1, 2), each = length(unique(chl_no_est$station_name))),
    size = rep(0.8, 10)
  ),
  nrow = 2,
  byrow = FALSE
)

ggplot() +
  # 绘制原始数据的线和点
  geom_line(data = chl_no_est, aes(x = event, y = result, color = station_name, group = station_name), size = 0.8) +
  geom_point(data = chl_no_est, aes(x = event, y = result, color = station_name, group = station_name)) +
  # 绘制平均值虚线
  geom_line(data = annotation_mean_chl, aes(x=event, y=avg_result, color = station_name, group = station_name), linetype=2, size=0.8) +
  # 目标水平线
  geom_hline(yintercept = 150, linetype = "solid", color = "black", size = 0.7) +
  # 标注文本
  geom_text(data = annotation_chl, aes(x=x, y=y, label=label), nudge_x = 0.1) +
  # 颜色标尺与自定义图例
  scale_color_viridis(discrete = TRUE, name = NULL, guide = custom_legend) +
  # 主题设置
  theme_classic() +
  theme(
    plot.title = element_text(hjust = 0.5),
    axis.title.x = element_blank(),
    legend.position = "bottom",
    legend.box = "horizontal",
    panel.grid.major.y = element_line(size=.01, color="grey60"),
    legend.key.height = unit(1, "cm") # 调整图例高度以容纳两行线条
  ) +
  labs(y="Chlorophyll a (mg/m2)") +
  scale_y_continuous(limits = c(0, 200), breaks = seq(0, 200, by = 20), expand = c(0,0))

关键说明

  • 自定义图例逻辑:通过guide_legend的override.aes参数,为每个站点指定两种线型(实线1、虚线2),并设置nrow=2让实线和虚线上下排列。
  • 图例高度调整:增加legend.key.height确保图例有足够空间显示两行线条,避免重叠。
  • 图层顺序:保持原始数据图层在前,平均值虚线图层在后,不影响绘图的视觉呈现。

内容的提问来源于stack exchange,提问作者user24243499

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.24 10:14:53