【问题标题】:ggplot2 geom_rect not scale appropriately under facet_gridggplot2 geom_rect 在 facet_grid 下不能适当缩放
【发布时间】:2019-03-15 23:39:01
【问题描述】:

问题是: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")

结果是这样的:

但是如果我画了一些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")

在绘制这些geom_rect时如何保持之前的x缩放

非常感谢任何建议。

【问题讨论】:

  • 在刻面后添加几何图形(参见:stackoverflow.com/a/10673877)或绘制两个单独的图并将它们与“patchwork”包拼凑在一起(github.com/thomasp85/patchwork)。
  • 在这种情况下,顺序无关紧要。我不知道如何使用“patchwork”。
  • 这真的很容易。只需按照 github repo 上的小插曲即可。

标签: r ggplot2 facet facet-wrap


【解决方案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")

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-03-29
    • 1970-01-01
    • 1970-01-01
    • 2018-11-03
    • 1970-01-01
    • 1970-01-01
    • 2019-09-05
    • 1970-01-01
    相关资源
    最近更新 更多