【问题标题】:Dodging geom_line() with a factor other than the group aesthetic用群体审美以外的因素避开 geom_line()
【发布时间】:2019-11-20 16:07:20
【问题描述】:

我正在尝试使用躲避的 geom_line() 制作图形,但我需要使用与 aes(group) 因素不同的因素来躲避它。

这是我的问题的演练。

首先,生成一些数据:

require(tidyverse)

treatment <- c(rep("t1", 15),
               rep("t2", 15))
sample <- c(rep("a", 5),
            rep("b", 5),
            rep("c", 5),
            rep("d", 5),
            rep("e", 5),
            rep("f", 5))

depth <- rep(1:5, 6)
set.seed(112)
values <- rnorm(30)
df <- tibble(treatment, sample, depth, values)

数据的初始绘制:

ggplot(df, aes(x = depth, y = values, color = treatment)) +
  geom_point() +
  geom_line()

这会生成一个带有无意义线条的图:

所以,我指定使用 group 美学:

ggplot(df, aes(x = depth, y = values, color = treatment)) +
  geom_point() +
  geom_line(aes(group = sample))

这会产生更好的数字。

但是,我的真实案例包含更多数据,并且处理重叠。我希望躲避治疗以更好地显示每种治疗的价值:

ggplot(df, aes(x = depth, y = values, color = treatment)) +
  geom_point(position = position_dodge(width = 0.5)) +
  geom_line(aes(group = sample), position = position_dodge(width = 0.5))

这会根据之前指定的color 美学来躲避geom_point(),但会使用已经设置为group = samplegroup 美学来躲避geom_line()

本质上,问题在于position_dodge() 似乎更倾向于使用group 美学,而我发现没有办法在不更改为geom_path() 的情况下避开这些线条。这允许我不指定group 美学来获得第二个数字,但我不喜欢使用它,因为它要求数据框完全有序(而且我还没有设法使用我的真实世界数据集使其发挥作用)。

有任何geom_line() 解决方案吗?

【问题讨论】:

  • 如果您在 geom_point 中也指定了 aes(group = sample),那应该可以解决问题。
  • @user727089,虽然它基于相同的变量躲避点和线,但它基于sample(6组)而不是treatment(2组)躲避它们。

标签: r ggplot2


【解决方案1】:

group = sample 移动到主要的ggplot 似乎可以解决问题:

require(tidyverse)
#> Loading required package: tidyverse

treatment <- c(rep("t1", 15),
               rep("t2", 15))
sample <- c(rep("a", 5),
            rep("b", 5),
            rep("c", 5),
            rep("d", 5),
            rep("e", 5),
            rep("f", 5))

depth <- rep(1:5, 6)
set.seed(112)
values <- rnorm(30)
df <- tibble(treatment, sample, depth, values)

ggplot(df, aes(x = depth, y = values, color = treatment, group = sample)) +
  geom_point(position = position_dodge(width = 0.5)) +
  geom_line(position = position_dodge(width = 0.5))

reprex package (v0.3.0) 于 2019 年 11 月 20 日创建

【讨论】:

  • 此解决方案与@user727089 的评论存在相同的问题:它基于sample 而不是treatment 进行闪避。您会注意到红色和青绿色的点没有垂直对齐。
猜你喜欢
  • 2013-04-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-03-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多