gghighlight 不能与 ggplot 分面一起使用

问题描述 投票:0回答:1

我正在使用 ggplot 和 gghighlight。我有一个包含 2 个连续变量和 2 个因子的数据框,我希望创建一个多面图,然后使用 gghighlight 突出显示某些变量范围。

library(ggplot2)
library(gghighlight)

n = 50
x = runif(n)
slope = sample(c(2,4), n, replace = TRUE)
intercept = sample(c(0, 0.5), n, replace = TRUE)
y <- slope * x + intercept

df <- data.frame(x = x, y = y, slope = slope, intercept = intercept)
df$slope <- as.factor(df$slope) 
df$intercept <- as.factor(df$intercept)

当我创建下面的第一个示例图时,突出显示有效,但问题是我看不到我想要的深灰色的未突出显示的变量

ggplot(df, aes(x, y)) +
  gghighlight(y < 1.5, unhighlighted_params = list(colour = "darkgrey")) +
  geom_line(aes(group = interaction(slope, intercept), colour = slope)) +
  geom_point(aes(shape = intercept, colour = slope)) +
  facet_wrap(~ slope)

当我向下移动 gghighlight 线时

ggplot(df, aes(x, y)) +
  geom_line(aes(group = interaction(slope, intercept), colour = slope)) +
  geom_point(aes(shape = intercept, colour = slope)) +
  gghighlight(y < 1.5, unhighlighted_params = list(colour = "darkgrey")) +
  facet_wrap(~ slope)

未突出显示的数据以深灰色显示,但向上我也获得了每个方面显示的所有数据。任何建议将不胜感激。

ggplot2 facet-wrap gghighlight
1个回答
0
投票

使用选项

calculate_per_facet = TRUE
:

library(ggplot2)
library(gghighlight)

n = 50
x = runif(n)
slope = sample(c(2,4), n, replace = TRUE)
intercept = sample(c(0, 0.5), n, replace = TRUE)
y <- slope * x + intercept

df <- data.frame(x = x, y = y, slope = slope, intercept = intercept)
df$slope <- as.factor(df$slope) 
df$intercept <- as.factor(df$intercept)

ggplot(df, aes(x, y)) +
  geom_line(aes(group = interaction(slope, intercept), colour = slope)) +
  geom_point(aes(shape = intercept, colour = slope)) +
  gghighlight(y < 1.5, unhighlighted_params = list(colour = "darkgrey"), 
              calculate_per_facet = TRUE
              ) +
  facet_wrap(~ slope)

创建于 2024-05-04,使用 reprex v2.1.0

© www.soinside.com 2019 - 2024. All rights reserved.