下面我的 ggplot 效果很好。但是,我想知道如何在按 group_by(groups)
对我的 dat
进行分组之前添加一条回归线,即是整个 dat
上的 geom_smooth()
(见下图)?
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 %>% group_by(groups) %>% ggplot() + ## @@ BEFORE group_by(group) can I add a geom_smooth()
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')+
scale_fill_manual(values=rep('black',3))
最佳答案
试试这个:
library(tidyverse)
#Code
dat %>% group_by(groups) %>% ggplot() + ## @@ BEFORE group_by(group) can I add a geom_smooth()
aes(x, y, color = groups, shape = groups)+
geom_point(size = 2) + theme_classic()+
geom_smooth(formula = "y~x",aes(group=1),se=F,color='black')+
stat_ellipse(level = .6) +
geom_point(data = dat2,
mapping = aes(x = mean_x, y = mean_y,color = factor(groups)),
size = 4, show.legend = F) +
geom_smooth(data = dat2, mapping = aes(x = mean_x, y = mean_y,group=1),
method = "lm", se=F, color = 1, formula = 'y ~ x')
输出:
或者使用@stefan概念(这很棒):
#Code 2
dat %>% group_by(groups) %>% ggplot() + ## @@ BEFORE group_by(group) can I add a geom_smooth()
aes(x, y, color = groups, shape = groups)+
geom_point(size = 2) + theme_classic()+
geom_smooth(method='lm',formula = "y~x",aes(group=1),se=F,color='black')+
stat_ellipse(level = .6) +
geom_point(data = dat2,
mapping = aes(x = mean_x, y = mean_y,color = factor(groups)),
size = 4, show.legend = F) +
geom_smooth(data = dat2, mapping = aes(x = mean_x, y = mean_y,group=1),
method = "lm", se=F, color = 1, formula = 'y ~ x')
输出:
关于r - 在 ggplot 中对数据进行分组之前添加 geom_smooth(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64580388/