如何在使用 ggplot、geom_line 和组时使用 gghighlight

How to use gghighlight when also using ggplot, geom_line and group

我不知道如何使用 geom_line 和 geom_point 来绘制我的数据,这样 gghighlight 就可以工作而无需将变量置于全局环境中

library(ggplot2)
library(gghighlight)

创建一些数据

x <- rep(1:5, 4)
y <- c(rep(1:5, 1) + rnorm(5)/5, rep(1:5, 1) + rnorm(5)/5 + 1, rep(6:10, 1) + rnorm(5)/5, rep(6:10, 1) + rnorm(5)/5 + 1)
treatment <- gl(2, 10, 20, labels=letters[1:2])
replicate <- gl(2, 5, 20, labels=letters[25:26])
d <- data.frame(x=x, y=y, treatment=treatment, replicate=replicate)
d

剧情v1如愿

v1 <- ggplot(d, aes(x=x, y=y, colour=treatment, shape = replicate, group=interaction(treatment, replicate))) + 
  geom_point(size = 3) + geom_line()
v1

gghighlight 根据需要在此处工作,但仅当变量在全局环境中时才有效

v1 + gghighlight(replicate == "y")
v1 + gghighlight(treatment == "a")

rm(replicate, treatment,x,y)

v1 + gghighlight(replicate == "y")
v1 + gghighlight(treatment == "a")

如果修改了全局变量,我会收到此错误消息

Error in `f()`:
! Aesthetics must be valid data columns. Problematic aesthetic(s): shape = replicate. 
Did you mistype the name of a data column or forget to add after_stat()?
Run `rlang::last_error()` to see where the error occurred.
Warning messages:
1: Tried to calculate with group_by(), but the calculation failed.
Falling back to ungrouped filter operation... 
2: Using `across()` in `filter()` is deprecated, use `if_any()` or `if_all()`. 
3: Tried to calculate with group_by(), but the calculation failed.
Falling back to ungrouped filter operation... 
4: Using `across()` in `filter()` is deprecated, use `if_any()` or `if_all()`. `

尝试生成绘图的其他方法

v2 <- ggplot(d, aes(x=x, y=y, colour=treatment, shape = replicate)) + 
  geom_point(size=3) + geom_line()
v2

突出显示不起作用

v2 + gghighlight(replicate == "y")
v2 + gghighlight(treatment == "a")

第三版剧情

v3 <- ggplot(d) +
  geom_point(aes(x=x, y=y, colour=treatment, shape = replicate), size = 3) +
  geom_line(aes(x=x, y=y, colour=treatment, shape = replicate))
v3

高亮出现但出错

v3 + gghighlight(replicate == "y")
v3 + gghighlight(treatment == "a")

我认为问题在于您在主 ggplot 调用中映射了 shape 美学,而不是在 geom_point 调用中指定它。 gghighlight 函数为每个图层创建一个具有所需美学值的新数据框,如果图层中存在无法识别的美学数据,则此过程无法正常工作。 geom_line 没有 shape 美学,因此在创建 geom_line 层期间未过滤绘图主数据框中的 replicate 列,因此是一个不同的过滤数据的长度。

解决方案是像这样创建情节:

v1 <- ggplot(d, aes(x, y, colour = treatment, 
                    group = interaction(treatment, replicate))) + 
  geom_point(aes(shape = replicate), size = 3) + 
  geom_line()

现在你可以做:

rm(replicate, treatment,x,y)

v1 + gghighlight(replicate == "y")

v1 + gghighlight(treatment == "a")