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

R语言ggplot添加自定义图例及两张散点图同页排列问题求助

图例配置问题修正

你的图例不生效核心是两个映射逻辑错误:

  1. 仅给geom_smooth配置了color映射,geom_point的颜色参数写在了aes()外,不会被纳入图例生成逻辑
  2. 你配置了scale_alpha_manual但全程没有使用alpha属性做映射,该配置不会被识别生效

修正后的单图代码如下(以第一张图为例):

library(tidyverse)
library(ggpubr)
library(cowplot)

# 赋值保存为p1用于后续拼接
p1 <- ggplot(data = StandardCM1, aes(x = NitriteCon, y = Absorbance)) +
  geom_smooth(method="lm", se=FALSE, aes(color = "Regression Line"), formula = y ~ x) +
  geom_point(aes(color = "Standard Curve Mean Values"), shape = 21, size = 3, fill = "blue") +
  theme(legend.position = "right") +
  # 匹配color映射的自定义样式
  scale_color_manual(
    name = NULL,
    values = c("Standard Curve Mean Values" = "blue", "Regression Line" = "red"),
    guide = guide_legend(
      override.aes = list(
        shape = c(21, NA),
        linetype = c(0, 1)
      )
    )
  ) +
  scale_y_continuous(breaks = seq(0, 0.3, 0.05)) +
  scale_x_continuous(breaks = seq(0, 100, 10)) +
  stat_cor(label.y = 0.30, aes(label = paste(..rr.label.., ..p.label.., sep = "~`,`~"))) +
  stat_regline_equation(label.x=0, label.y=0.28) +
  ggtitle("Standard Curve") +
  xlab("Nitrite Concentration (µM)") +
  ylab("Absorbance")

第二张图仅需要将y = Absorbance替换为y = Absorbance1,修改标题后赋值为p2即可。

多图拼接报错修正

你调用plot_grid(df1, df2)报错的原因是没有将绘制好的ggplot对象赋值给对应变量,代码直接运行ggplot只会在面板输出图片,不会自动保存为对象。

完成两张图的赋值后,使用以下代码即可实现并排展示:

plot_grid(p1, p2, labels = c("A", "B"), ncol = 2, align = "h", common.legend = TRUE)

添加common.legend = TRUE参数可让两张图共用同一个图例,避免重复展示。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 05:57:02