r - 在 ggplot 中对数据进行分组之前添加 geom_smooth()

标签 r dataframe ggplot2 plot tidyverse

下面我的 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))

enter image description here

最佳答案

试试这个:

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

输出:

enter image description here

或者使用@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')

输出:

enter image description here

关于r - 在 ggplot 中对数据进行分组之前添加 geom_smooth(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64580388/

相关文章:

r - 有没有一种优雅的方法可以在 R 中按行名重新排序数据框

r - 如何使用apply分解R中data.frame中的特定列

python - 更改另一个数据帧的值

dataframe - Julia 中 DataFrame 的两列或多列的矢量化连接

r - 根据方面的存在有条件地修改ggplot主题?

r - 读取数据时出错

r - R中的autoplot函数和plot函数有什么区别

python pandas dataframe head() 什么都不显示

r - r 中的哪些投影会使城市 map 变胖?

r - ggplot - 使中位数不可见 geom_boxplot