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

如何在R的ggplot中修改图例标题且避免图例拆分?

ggplot图例标题修改:合并colour与fill图例并自定义标题

你遇到的问题是:在ggplot中同时将colour和fill映射到media变量后,修改图例标题时两个图例被拆分。这是因为如果只修改其中一个美学属性的标题,ggplot会将它们识别为独立的图例组,导致拆分。

解决方法

核心思路是让colour和fill的图例标题保持完全一致,ggplot就会自动合并两者的图例。以下是三种可行的实现方式:

方法1:通过labs()同时设置标题

直接在labs()里为colour和fill指定相同的自定义标题:

p2 <- lf_data |> subset(grepl("^.+(gfp)$", media)) |>
  ggplot(aes(time, gfp, colour = media, fill = media)) +
  geom_smooth(method = "loess", span = 0.2) +
  labs(
    title = "GFP time series of species and media",
    y = "GFP [RFU]",
    x = "Time (h)",
    colour = "自定义图例标题",  # 与fill标题一致
    fill = "自定义图例标题"
  ) +
  theme(
    text = element_text(size = 15),
    legend.position = "bottom"
  )

方法2:通过guides()统一配置图例

使用guides()为两个美学属性的图例设置相同标题:

p2 <- lf_data |> subset(grepl("^.+(gfp)$", media)) |>
  ggplot(aes(time, gfp, colour = media, fill = media)) +
  geom_smooth(method = "loess", span = 0.2) +
  labs(
    title = "GFP time series of species and media",
    y = "GFP [RFU]",
    x = "Time (h)"
  ) +
  guides(
    colour = guide_legend(title = "自定义图例标题"),
    fill = guide_legend(title = "自定义图例标题")
  ) +
  theme(
    text = element_text(size = 15),
    legend.position = "bottom"
  )

方法3:修改scale的名称

直接修改对应颜色和填充的scale名称,保持一致:

p2 <- lf_data |> subset(grepl("^.+(gfp)$", media)) |>
  ggplot(aes(time, gfp, colour = media, fill = media)) +
  geom_smooth(method = "loess", span = 0.2) +
  scale_colour_discrete(name = "自定义图例标题") +
  scale_fill_discrete(name = "自定义图例标题") +
  labs(
    title = "GFP time series of species and media",
    y = "GFP [RFU]",
    x = "Time (h)"
  ) +
  theme(
    text = element_text(size = 15),
    legend.position = "bottom"
  )

以上三种方法都能实现自定义图例标题且保持图例合并的效果,你可以根据自己的习惯选择其中一种。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 05:30:44