首页 > 解决方案 > ggplot中没有填充次要点

问题描述

下面的情节有两个问题。首先,我怎样才能让我的 3 个黑点没有填充?其次,我怎样才能拥有geom_smooth()这 3 个黑点?

我为两者都尝试了一些东西,但都没有成功。

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() +
  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 = NA, ### No fill 
           size = 4, color = 1, show.legend = F) +
  geom_smooth(data = dat2, mapping = aes(x = mean_x, y = mean_y), 
method = "lm", se=F, color = 1, formula = 'y ~ x')  ## geom_smooth doesn't show

在此处输入图像描述

标签: rdataframeggplot2plottidyverse

解决方案


试试这个非填充点:

library(tidyverse)
#Code
dat %>% group_by(groups) %>% 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), 
              method = "lm", se=F, color = 1, formula = 'y ~ x')  ## geom_smooth doesn't show

输出:

在此处输入图像描述

为了顺利尝试这个:

#Code 2
dat %>% group_by(groups) %>% 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')+
  scale_fill_manual(values=rep('black',3))

输出:

在此处输入图像描述

试试这个保持相同的形状:

#Code 3
dat %>% group_by(groups) %>% 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,color = factor(groups)),
             size = 4, show.legend = F,color='black') +
  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))

输出:

在此处输入图像描述


推荐阅读