为同一ggplot中使用的不同data.frames手动添加其他图例 [英] Adding an additional legend manually for different data.frames used in the same ggplot

查看:141
本文介绍了为同一ggplot中使用的不同data.frames手动添加其他图例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面的图中,我在两个不同的geom_smooth()调用中使用了两个单独的data源(datdat2),产生了黑色和红色回归线(请参见下图).

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).

是否可以手动添加另一个显示黑线称为"Between"和红线称为"Within"legend?

Is it possible to manually add another legend that shows the black line is called "Between" and red line is called "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))

推荐答案

您似乎需要第二个色标才能执行此操作.您可以使用ggnewscale软件包:

It looks like you need a second color scale to do this. You can use the ggnewscale package:

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())

这篇关于为同一ggplot中使用的不同data.frames手动添加其他图例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆