【问题标题】:Why geom_rect looking different across facets?为什么 geom_rect 在各个方面看起来不同?
【发布时间】:2020-11-25 22:58:04
【问题描述】:

我正在尝试为同样被刻面的情节的不同象限着色。我注意到geom_rect 参数中的颜色在各个方面看起来不同。我希望这是一个例子:

# Load tidyverse
library(tidyverse)

# Make some fake data
set.seed(5)
dat <- tibble(
  y = rnorm(10, 0, 1),
  ub = y + .2,
  lb = y - .2,
  x = sample(1:7, size=10, replace=TRUE),
  z = sample(c("one", "two", "three"), size=10, replace=TRUE),
)

# Plot
dat %>% 
  ggplot(aes(x = x, y = y)) +
  geom_rect(data=NULL, aes(xmin=4, xmax=Inf, ymin=0, ymax=-Inf), fill="yellow", color = "white", alpha = .05) +
  geom_rect(data=NULL, aes(xmin=-Inf, xmax=4, ymin=Inf, ymax=0), fill="yellow", color = "white", alpha = .05) +
  geom_rect(data=NULL, aes(xmin=-Inf, xmax=4, ymin=-Inf, ymax=0), fill="red", color = "white", alpha = .05) +
  geom_rect(data=NULL, aes(xmin=4, xmax=Inf, ymin=0, ymax=Inf), fill="springgreen", color = "white", alpha = .05) +
  geom_point(position= position_dodge2(width = .6)) +
  geom_errorbar(aes(ymin = lb, ymax = ub, width = .6), position= position_dodge2(width = .6, preserve = "single")) +
  facet_grid(~ z) +
  theme_classic()

谁能向我解释为什么geom_rect 框在某些方面比其他方面更亮?我该如何解决这个问题?

【问题讨论】:

    标签: r ggplot2 facet


    【解决方案1】:

    这里发生的是geom_rect 每次调用时都会将矩形重叠在一起。如果对构面进行排序,您会发现第二个比第一个不透明,第三个比第二个不透明。

    解决办法是用annotate代替geom_rect

    dat %>% 
      mutate(z = factor(z, levels = c("one", "two", "three"))) %>% 
      ggplot(aes(x = x, y = y)) +
      annotate("rect", xmin=4, xmax=Inf, ymin=0, ymax=-Inf, fill="yellow", color = "white", alpha = .05) +
      annotate("rect", xmin=-Inf, xmax=4, ymin=Inf, ymax=0, fill="yellow", color = "white", alpha = .05) +
      annotate("rect", xmin=-Inf, xmax=4, ymin=-Inf, ymax=0, fill="red", color = "white", alpha = .05) +
      annotate("rect", xmin=4, xmax=Inf, ymin=0, ymax=Inf, fill="springgreen", color = "white", alpha = .05) +
      geom_point(position= position_dodge2(width = .6)) +
      geom_errorbar(aes(ymin = lb, ymax = ub, width = .6), position= position_dodge2(width = .6, preserve = "single")) +
      facet_grid(~ z) +
      theme_classic()
    

    结果:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-04-28
      • 2018-07-03
      • 1970-01-01
      • 2012-09-10
      相关资源
      最近更新 更多