ggplot2 geom_rect在facet_grid下不能正确缩放

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

问题是: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时保持之前的缩放比例?

任何建议都非常感谢。

r ggplot2 facet facet-wrap
1个回答
1
投票

x轴范围发生变化,因为geom_rect层中的数据超出了原始图的数据。规模正在完成预期的工作。

如果你想为每个方面显示不同的矩形,那么在shade中包含facet变量会更加清晰,并且只保留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

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