简体   繁体   English

为同一 ggplot 中使用的不同 data.frames 手动添加额外的图例

[英]Adding an additional legend manually for different data.frames used in the same ggplot

In my plot below, I have two separate sources of data ( dat and dat2 ) used in two different geom_smooth() calls producing the black and the red regression lines ( see pic below ).在我下面的图中,我有两个单独的data源( datdat2 )用于两个不同的geom_smooth()调用,生成黑色和红色回归线(见下图)。

Is it possible to manually add another legend that shows the black line is called "Between" and red line is called "Within" ?是否可以手动添加另一个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))

在此处输入图片说明

It looks like you need a second color scale to do this.看起来您需要第二个色标来执行此操作。 You can use the ggnewscale package:您可以使用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())

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM