You need to enable JavaScript to run this app. 使用多geom绘图时如何通过directlabels添加对应标签
优惠活动
大模型
产品
解决方案
定价
更多

使用多geom绘图时如何通过directlabels添加对应标签

多geom折线图使用directlabels添加右端标签的问题

我在使用多个geom绘制折线图时,无法通过directlabels在折线右端添加对应标签,示例代码如下:

#load packages
library(dplyr)
library(ggplot2)
library(tidyr)
library(directlabels)

#create data
set.seed(1)
test <- tibble(year = as.factor(rep(1990:2000, 4)), 
     label = rep(replicate(4, paste0(sample(letters, 20), collapse = "")), each =11), #create long random labels
     value = rnorm(44))
test[which(test$year==2000),]$value <- seq(0,0.1, length.out = 4) # make final values very similar

average <- test %>% 
     group_by(year) %>% 
     summarize(value = mean(value)) %>% 
     bind_cols(label = "average")

#draw plot
ggplot(test, aes(x = year, y = value, group = label, color = label)) +
  geom_line() +
  geom_smooth(data = average,
              mapping = aes(x = year, y = value, group = label, color = label),
              inherit.aes = F, col = "black") +
  geom_dl(aes(label = label,
              color = label), 
          method = list(dl.combine("last.bumpup"))) +
  theme(legend.position = "none")

运行上述代码得到的图表如下:
折线图示例

我现在需要在geom_smooth折线的右端添加一个黑色的“average”标签,目前尝试的方法存在两个问题:

  • 单独创建的标签会和其他标签重叠
  • 标签无法显示为黑色

尝试的代码如下:

ggplot(test, aes(x = year, y = value, group = label, color = label)) +
  geom_line() +
  geom_smooth(data = average,
              mapping = aes(x = year, y = value, group = label, color = label),
              inherit.aes = F, col = "black") +
  geom_dl(aes(label = label,
              color = label), 
          method = list(dl.combine("last.bumpup"))) +
  geom_dl(data = average,
          mapping = aes(label = label,
              color = label), 
          method = list(dl.combine("last.bumpup"))) +
  theme(legend.position = "none")

运行上述代码得到的图表如下:
折线图示例2

需求总结

为geom_smooth生成的折线添加与其折线同色、且不与其他标签重叠的标签。

注意事项

无法使用stat_summary方法实现需求,实际数据中的平均值是提前加权计算得到的,没有保留对应的权重参数,无法通过原始数据点计算平均值,只能使用数据框中已提供的平均值数据。

补充说明

实际使用的数据中标签长度更长(10-30个字符),且部分标签在最大年份对应的y值非常接近,因此使用了带bumpup参数的directlabels,若标签没有互斥避让效果,大概率会出现重叠问题。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 18:36:03