ggplot2 geom_rect在facet_grid下无法适当缩放

时间:2019-03-15 23:39:02

标签: r ggplot2 facet facet-wrap

问题是:geom_rect使用ggplot2防止facet_grid缩放

我想知道它是否是由两个数据帧中的冲突引起的,但不知道如何解决此问题。希望您能够帮助我。

示例代码如下:

library(ggplot2)
data_1 <- data.frame(x = c(seq(from = 1, to = 10, by = 1),
                           seq(from = 21, to = 50, by = 1)),
                     y = rnorm(40, mean = 3, sd = 1),
                     z = c(rep("A", 10), rep("B", 30)))

shade <- 
  data.frame(xmin = c(2, 6, 39),
             xmax = c(3, 8, 43),
             ymin = - Inf,
             ymax = Inf)

如果不使用geom_rect,我可以像这样适当地使用facet_grid进行缩放:

ggplot(data = data_1, aes(x = x, y = y)) +
  geom_bar(stat = "identity", fill = "blue") +
  facet_grid(.~z, space = "free_x", scales = "free_x")

结果是这样的:

enter image description here

但是,如果我绘制一些geom_rect,则先前显示的比例将消失,并带有如下代码和图形:

ggplot(data = data_1, aes(x = x, y = y)) +
  geom_bar(stat = "identity", fill = "blue") +
  geom_rect(data = shade, inherit.aes = FALSE,
            mapping = aes(xmin = xmin, 
                          xmax = xmax, 
                          ymin = ymin, ymax = ymax),
            fill = 'red', alpha = 0.2) +
  facet_grid(.~z, space = "free_x", scales = "free_x")

enter image description here

在绘制这些geom_rect时如何保持先前在x上的缩放比例

任何建议都将不胜感激。

1 个答案:

答案 0 :(得分:1)

x轴范围发生变化,因为geom_rect层中的数据超出了原始图的范围。秤的功能完全符合预期。

如果要为每个构面显示不同的矩形,将构面变量包含在shade中会更干净,并且仅保留xmin / xmax 在每个方面的范围内。例如:

library(dplyr)
shade2 <- shade %>%
  # add facet-specific x-axis range information from data_1
  tidyr::crossing(data_1 %>% group_by(z) %>%
                    summarise(x1 = min(x),
                              x2 = max(x)) %>%
                    ungroup) %>%

  # filter for rects within each facet's x-axis range
  group_by(z) %>%
  filter(xmin >= x1 & xmax <= x2) %>%
  ungroup()

> shade2
# A tibble: 3 x 7
   xmin  xmax  ymin  ymax z        x1    x2
  <dbl> <dbl> <dbl> <dbl> <fct> <dbl> <dbl>
1     2     3  -Inf   Inf A         1    10
2     6     8  -Inf   Inf A         1    10
3    39    43  -Inf   Inf B        21    50

图:

ggplot(data = data_1, aes(x = x, y = y)) +
  geom_col(fill = "blue") + # geom_col is equivalent to geom_bar(stat = "identity")
  geom_rect(data = shade2, inherit.aes = FALSE,
            mapping = aes(xmin = xmin, xmax = xmax, 
                          ymin = ymin, ymax = ymax),
            fill = 'red', alpha = 0.2) +
  facet_grid(.~z, space = "free_x", scales = "free_x")

result