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

如何使用ggplot将图例说明文字置于图例下方,兼容cowplot绘制场景

实现ggplot图例文字位于标识下方的两种方案

方案1:cowplot手动绘制(优先推荐)

你要求的文字下方带对应线型下划线的效果可以直接通过ggdraw叠加线段和文字实现,先隐藏原图表的图例,再手动添加图例元素:

library(cowplot)
library(ggplot2)
library(ggtext)

# 隐藏原ggplot自带图例
PlotLine_nolegend <- PlotLine + theme(legend.position = "none")

# 拼接时手动添加图例
Ausgabe <- ggdraw() +
  # 叠加原折线图
  draw_plot(PlotLine_nolegend, width = 0.6, height = 0.18, x = 0.345, y = 0.094) +
  # 绘制两条对应线型的下划线
  draw_line(x = c(0.4, 0.47), y = c(0.07, 0.07), color = "#ff9a00", size = 1.25, linetype = "solid") +
  draw_line(x = c(0.52, 0.59), y = c(0.07, 0.07), color = "#ff9a00", size = 1.25, linetype = "dotted") +
  # 在线段上方添加对应文字
  draw_text(Nutzer1, x = 0.435, y = 0.085, size = 8, color = "#ff9a00") +
  draw_text(Nutzer2, x = 0.555, y = 0.085, size = 8, color = "#ff9a00")

代码中的x、y位置参数可以根据你实际输出的画布尺寸微调,即可对齐到理想位置。

方案2:原生ggplot图例参数调整

如果不需要手动绘制,也可以直接调整图例的内置参数实现效果,修改原PlotLine的theme配置即可:

colors <- c("#ff9a00","#ff9a00")

PlotLine <- ggplot(pp, aes(x, y, color = id, linetype = id))+
  geom_path(size=1.25) +
  scale_x_datetime(date_labels = "%Y", breaks = scales::pretty_breaks(n = 3), expand = expansion(mult = c(0.02, 0.03)))+
  scale_color_manual(labels = unique(c(Nutzer1, Nutzer2)),
                     values = colors)+
  scale_linetype_manual(labels = unique(c(Nutzer1, Nutzer2)),
                        values=c("solid","dotted"))+
  xlab("")+
  ylab("")+
  theme(
    axis.text.x = element_text(size= 10, colour = "black", margin = margin(t = 10, b = -5)),
    axis.text.y = element_blank(),
    legend.direction = "horizontal",
    legend.text = element_text(size = 8, color = "#ff9a00", margin = margin(t = 3)), # 文字上方加间距
    legend.key.width = unit(1.5, "cm"), # 调整图例键宽度匹配文字长度
    legend.key.height = unit(0.2, "cm"),
    legend.position = "bottom",
    legend.margin = margin(t = -10) # 调整图例和图表主体的间距
  )+
  labs(color=NULL, linetype=NULL)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 14:09:01