r - 为同一ggplot中使用的不同data.frame手动添加其他图例

标签 r dataframe ggplot2 plot tidyverse

在下面的情节中,我有两个单独的data来源(datdat2),用于两个不同的geom_smooth()调用中,产生了黑色和红色回归线(请参见下图)。
是否可以手动添加另一个显示黑线的legend称为"Between"和显示红线的"Within"

library(tidyverse)

dat <- read.csv('https://raw.githubusercontent.com/rnorouzian/e/master/cw2.csv')
dat$groups <- factor(dat$groups)

dat2 <- dat %>% group_by(groups) %>% summarize(mean_x = mean(x),
                                               mean_y = mean(y),
                                               .groups = 'drop')
dat %>% 
  ggplot() +
  aes(x, y, color = groups, shape = groups)+
  geom_point(size = 2) + theme_classic()+ 
  stat_ellipse(level = .6) +
  geom_point(data = dat2, 
             mapping = aes(x = mean_x, y = mean_y,fill = factor(groups)),
             size = 4, show.legend = F,shape=21) +
  geom_smooth(data = dat2, mapping = aes(x = mean_x, y = mean_y,group=1), 
          method = "lm", se=F, color = 1, formula = 'y ~ x')+ 
  geom_smooth(aes(group = 1), 
              method = "lm", se=F, color = 2, formula = 'y ~ x')+
  scale_fill_manual(values=rep('black',3))
enter image description here

最佳答案

看来您需要第二个色标才能执行此操作。您可以使用ggnewscale包:

library(ggnewscale)

dat %>% 
  ggplot() +
  aes(x, y, color = groups, shape = groups) +
  geom_point(size = 2) + 
  theme_classic() + 
  stat_ellipse(level = .6) +
  geom_point(data = dat2, 
             mapping = aes(x = mean_x, y = mean_y),
             size = 4, show.legend = FALSE, shape = 21, fill = "black") +
  scale_color_discrete() +
  new_scale_color() +
  geom_smooth(data = dat2, 
              mapping = aes(x = mean_x, y = mean_y, group = 1, color = "black"), 
          method = "lm", se = FALSE, formula = 'y ~ x') + 
  geom_smooth(aes(group = 1, color = "red"), 
              method = "lm", se = FALSE, formula = 'y ~ x') +
  scale_color_identity(name = "", labels = c("Between", "Within"),
                       guide = guide_legend())
enter image description here

关于r - 为同一ggplot中使用的不同data.frame手动添加其他图例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64626743/

相关文章:

r - 未指定 aes() 颜色和形状时 ggplot 中的图例

R:快速乘以data.frame(或其他数据结构)中的选定行

r - R中基于行名合并数据框

r - ggplot2 中 y 刻度标签的良好 K/M/G 缩写

r - ggplot 轴标签中的 utf-8

r - 更改ggplot2中geom_point()的默认点大小?

r - 同时按总和聚合一列,按平均值聚合另一列

R比较两个数组

r - 子集数据框,其中日期在 R 中日期向量的 x 天内

python - 基于 Pandas 中另一列的增量