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

如何在ggplot2图例中添加类似geom_label_repel的标签样式

问题描述

我绘制了一张包含9条折线的物种丰富度图,已使用geom_label_repel()在每条折线末端标注对应的样方编号(Quadrat)。希望在图例中添加一个带有数字1的黑色标签框,旁边标注“样方编号”。


当前绘图效果

当前绘图效果

目标图例样式

目标图例样式

绘图数据(index)

structure(c("function (..., list = character(), package = NULL, lib.loc = NULL, ", 
"    verbose = getOption(\"verbose\"), envir = .GlobalEnv, overwrite = TRUE) ", 
"{", "    fileExt <- function(x) {", "        db <- grepl(\"\\\\.[^.]+\\\\.(gz|bz2|xz)$\", x)", 
"        ans <- sub(".*\\\\.", "", x)"), dim = c(6L, 1L), dimnames = list(
    c("1", "2", "3", "4", "5", "6"), ""), class = "noquote")

标签数据(labels_df)

structure(list(Quadrat = structure(1:9, levels = c("1", "2", 
"3", "4", "5", "6", "7", "8", "9"), class = "factor"), Year = c(2024L, 
2024L, 2024L, 2024L, 2024L, 2024L, 2024L, 2024L, 2024L), ID = c("1_24", 
"2_24", "3_24", "4_24", "5_24", "6_24", "7_24", "8_24", "9_24"
), Source = c("Beaver", "Beaver", "Beaver", "Beaver", "Beaver", 
"Beaver", "SSSI", "SSSI", "SSSI"), specNum = c(20L, 21L, 19L, 
6L, 2L, 8L, 15L, 29L, 16L), simpson = c(0.95, 0.952380952380952, 
0.947368421052632, 0.833333333333333, 0.5, 0.875, 0.933333333333333, 
0.96551724137931, 0.9375), shannon = c(2.99573227355399, 3.04452243772342, 
2.94443897916644, 1.79175946922805, 0.693147180559945, 2.07944154167984, 
2.70805020110221, 3.36729582998647, 2.77258872223978), H = c(2.99573227355399, 
3.04452243772342, 2.94443897916644, 1.79175946922805, 0.693147180559945, 
2.07944154167984, 2.70805020110221, 3.36729582998647, 2.77258872223978
), fisher = c(4294967306, 4294967306.5, 4294967305.5, 1073741869.66667, 
268435505.000009, 2147483652, 4294967303.5, 4294967310.5, 4294967304
)), class = c("tbl_df", "tbl", "data.frame"), row.names = c(NA, 
-9L))

现有绘图代码

library(ggplot2)            # 绘图包
library(ggrepel)            # 用于geom_label_repel()
library(pals)               # 折线颜色标度

specPlot <- ggplot(index, aes(x=Year, y=specNum, group=Quadrat, color=Quadrat, linetype=Source)) +
  geom_line() +
  geom_point() +
  labs(x='年份', y='物种丰富度') +
  scale_colour_manual(values = unname(kovesi.isoluminant_cgo_70_c39(n=9)), guide = "none") +
  scale_linetype_manual(name = NULL, values = c('Beaver' = 'solid', 'SSSI' = 'dashed')) +
  geom_label_repel(data=labels_df,aes(label=Quadrat),
                   direction='y',
                   segment.colour='black',
                   xlim=c(2024,2025),
                   na.rm = TRUE,
                   max.overlaps=100,
                   show.legend = FALSE) +
  theme_classic() +
  theme(legend.position='top',
        legend.direction = 'horizontal',
        text = element_text(size = 14, family = 'Calibri Light')) +
  coord_cartesian(clip='off')

解决方案

通过自定义图例条目,模拟目标中的标签框样式,修改后的代码如下:

library(ggplot2)
library(ggrepel)
library(pals)

specPlot <- ggplot(index, aes(x=Year, y=specNum, group=Quadrat, color=Quadrat, linetype=Source)) +
  geom_line() +
  geom_point() +
  labs(x='年份', y='物种丰富度') +
  scale_colour_manual(values = unname(kovesi.isoluminant_cgo_70_c39(n=9)), guide = "none") +
  scale_linetype_manual(name = NULL, values = c('Beaver' = 'solid', 'SSSI' = 'dashed')) +
  # 添加虚拟图例组,用于承载样方编号标签框
  geom_point(aes(shape = "样方编号"), color = "black", size = 0, show.legend = TRUE) +
  # 自定义形状标度,隐藏默认形状
  scale_shape_manual(name = NULL, values = 15, labels = "") +
  geom_label_repel(data=labels_df,aes(label=Quadrat),
                   direction='y',
                   segment.colour='black',
                   xlim=c(2024,2025),
                   na.rm = TRUE,
                   max.overlaps=100,
                   show.legend = FALSE) +
  theme_classic() +
  theme(
    legend.position='top',
    legend.direction = 'horizontal',
    text = element_text(size = 14, family = 'Calibri Light'),
    legend.key = element_rect(fill = NA, color = NA),
    legend.text = element_text(margin = margin(l = 5))
  ) +
  # 合并图例并自定义样方编号项的样式
  guides(
    linetype = guide_legend(order = 1),
    shape = guide_legend(
      order = 2,
      override.aes = list(
        shape = NA,
        label = "1",
        color = "black",
        fill = "white",
        size = 4,
        label.size = 0.5
      ),
      label.position = "right",
      title = NULL
    )
  ) +
  coord_cartesian(clip='off')

print(specPlot)

代码说明

  1. 通过geom_point(aes(shape = "样方编号"))创建虚拟图例组,作为自定义标签框的载体
  2. 在guides()中使用override.aes替换默认形状为带数字1的标签框,调整边框粗细、填充色等参数匹配目标样式
  3. 调整图例顺序,让线型图例在前,样方编号图例在后,保持布局一致

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.20 09:59:53