简体   繁体   English

facet_wrap 具有类似 facet_grid 的布局

[英]facet_wrap with layout like facet_grid

Using facet_grid wraps panels according to the factor levels in the variables provided, even if there is no data present for a given combination.使用facet_grid根据提供的变量中的因子级别包装面板,即使给定组合不存在数据。 This is the behaviour I am after.这是我所追求的行为。

Unfortunately, the y-axes scales can not be made independent on the individual panel level (see here and here ).不幸的是,y 轴比例不能在单个面板级别上独立(请参阅此处此处)。 For that, you must use facet_wrap .为此,您必须使用facet_wrap

facet_wrap , however, doesn't provide the same layout as facet_grid , and only displays the panels that have values to be plotted.但是, facet_wrap不提供与facet_grid相同的布局,并且只显示具有要绘制的值的面板。

How can I keep the facet_grid -like layout but with independent y-axis scales?如何保持facet_grid的布局但具有独立的 y 轴比例? It is okay if the panels without data are blank/void as long as they occupy the appropriate space.如果没有数据的面板是空白的,只要它们占据适当的空间就可以了。

Reproducible example:可重现的例子:

library(ggplot2)
set.seed(1)

# Generate data
test <- data.frame(x = c(rep(1, 6), rep(2, 6)), 
                   facet_1 = rep(c("A", "A", "A", "B", "B", "C"), 2),
                   facet_2 = rep(c("B", "C", "D", "C", "D", "D"), 2),
                   y = c(1e0, 1e1, 1e2, 1e3, 1e4, 1e5, rnorm(1, 1e0, 1e0*.34), rnorm(1, 1e1, 1e1*.34), rnorm(1, 1e2, 1e2*.34), rnorm(1, 1e3, 1e3*.34), rnorm(1, 1e4, 1e4*.34), rnorm(1, 1e5, 1e5*.34)))

# facet_grid - Shows blank panels B-B, B-C, and C-C. This is what I want.
#            - Does NOT scale y appropriately at the individual panel level.
ggplot(test, aes(x = x, y = y)) +
  facet_grid(facet_2 ~ facet_1, scales = "free") +
  geom_line()

facet_grid 示例

# facet_wrap - Does NOT show blank panels B-B, B-C, and C-C.
#            - Does scale y appropriately at the individual panel level.
ggplot(test, aes(x = x, y = y)) +
  facet_wrap(vars(facet_1, facet_2), scales = "free") +
  geom_line()

facet_wrap 示例

You can complete the missing combination and then plot.您可以complete缺少的组合,然后绘图。

library(ggplot2)

tidyr::complete(test, facet_1, facet_2, fill = list(x = 0, y = 0)) %>%
#Keeping them as NA would give a blank plot
#tidyr::complete(test, facet_1, facet_2) %>%
   ggplot() + aes(x = x, y = y) +
   facet_wrap(vars(facet_1, facet_2), scales = "free") +
   geom_line()

在此处输入图片说明

This would give you a warning as there is only one observation in those 3 groups.这会给您一个警告,因为在这 3 组中只有一个观察结果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM