【问题标题】:Add 2 additional lines to a ggplot将 2 行添加到 ggplot
【发布时间】:2021-02-11 01:26:21
【问题描述】:

我已经成功地在下面绘制了我的dat。但是,我想做以下数据转换:dat %>% group_by(groups) %>% mutate(x.cm = mean(x), x.cwc = x-x.cm) 然后在我当前的绘图中添加 2 行:

  1. geom_smooth() 使用 x.cm 作为 x
  2. geom_smooth() 使用 x.cwc 作为 x

有没有办法做到这一点?

p.s: 是否也可以在绘图上将 3 个 unique(x.cm) 值显示为 3 颗星? (见下图

library(tidyverse)

dat <- read.csv('https://raw.githubusercontent.com/rnorouzian/e/master/cw.csv')

  dat %>% group_by(groups) %>% ggplot() +
  aes(x, y, color = groups, shape = groups)+
  geom_point(size = 2) + theme_classic()+ 
  stat_ellipse()

# Now do the transformation:
dat %>% group_by(groups) %>% mutate(x.cm = mean(x), x.cwc = x-x.cm)

【问题讨论】:

  • 试试这个,考虑到你有不同的措施:dat %&gt;% group_by(groups) %&gt;% mutate(x.cm = mean(x), x.cwc = x-x.cm) %&gt;% pivot_longer(-c(y,groups)) %&gt;% ggplot(aes(value, y, color = factor(groups), shape = factor(groups))) + geom_point(size = 2) + theme_classic()+ geom_smooth(formula = y~x,se=F)+ stat_ellipse()+facet_wrap(.~name)

标签: r dataframe ggplot2 plot tidyverse


【解决方案1】:

我不确定您问题的第二部分对我是否有意义。但从描述中,一种方法是简单地添加一个级别,您可以在其中更改数据和aes 参数,就像我在下面的示例中所做的那样(使用mtcars 作为示例数据)

# Load libraries and data
library(tidyverse)
library(ggplot2)
data(mtcars)

mtcars %>% ggplot(aes(x = hp, y = mpg)) + 
  geom_point(aes(col = factor(cyl))) + 
  stat_ellipse(aes(col = factor(cyl))) + 
  # Add line for ellipsis center
  geom_line(data = mtcars %>% group_by(cyl) %>% summarize(mean_x = mean(hp),
                                                          mean_y = mean(mpg),
                                                          .groups = 'drop'),
            mapping = aes(x = mean_x, y = mean_y)) + 
  geom_point(data = mtcars %>% group_by(cyl) %>% summarize(mean_x = mean(hp),
                                                           mean_y = mean(mpg),
                                                           .groups = 'drop'), 
             mapping = aes(x = mean_x, y = mean_y)) +
  # Add smooth for.. what? I don't understand this part of the question.
  geom_smooth(data = mtcars %>% group_by(cyl) %>% mutate(x_val = hp - mean(hp)) %>% ungroup(),
              mapping = aes(x = x_val, y = mpg))

现在应该很清楚哪一部分对我来说没有意义。为什么/第二条路径(geom_smooth)是什么意思?在平滑器上移动 x 轴对我来说毫无意义。我还冒昧地更改了第一部分的定义,而是将均值的单点(圆心)添加到图中并使用 geom_line 连接。

【讨论】:

  • 问题更多的是“要平滑什么”。在您的问题中,您正在平滑“x - mean(x)”。由于它在相同的视觉效果中,它将为变量x 添加一个平滑,但平均移除(按组),因此平滑将移向零。如果您正在寻找的只是省略号中心的平滑,只需复制geom_linegeom_point 中的数据并将其更改为“geom_smooth”(相当于对中心进行平滑处理,而不是平均删除点)。 :-)
  • 我同意ggplot2 是多余的(不过我喜欢视觉化)。 data(mtcars) 只是一个好习惯,让那些可能刚刚开始使用 R 的人明白这一点,以明确我不是凭空拉出数据集。 :-)
  • 奥利弗,我得出的结论是我应该分块解决我的问题,现在我接受了你的解决方案(谢谢!)但我会问一些后续问题。
猜你喜欢
  • 2021-03-02
  • 1970-01-01
  • 2022-01-12
  • 2018-07-19
  • 2013-04-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-10-17
相关资源
最近更新 更多