facet_wrap 布局类似于 facet_grid
facet_wrap with layout like facet_grid
使用 facet_grid
根据提供的变量中的因子水平包装面板,即使给定组合没有数据。这就是我追求的行为。
不幸的是,y 轴刻度不能独立于单个面板级别(参见 here and here)。为此,您必须使用 facet_wrap
.
然而,facet_wrap
不提供与 facet_grid
相同的布局,并且仅显示具有要绘制的值的面板。
如何保持类似 facet_grid
的布局但具有独立的 y 轴刻度?没有数据的面板如果是blank/void也没关系,只要占据合适的space.
可重现的例子:
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_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()
你可以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()
这会给你一个警告,因为这 3 个组中只有一个观察值。
使用 facet_grid
根据提供的变量中的因子水平包装面板,即使给定组合没有数据。这就是我追求的行为。
不幸的是,y 轴刻度不能独立于单个面板级别(参见 here and here)。为此,您必须使用 facet_wrap
.
facet_wrap
不提供与 facet_grid
相同的布局,并且仅显示具有要绘制的值的面板。
如何保持类似 facet_grid
的布局但具有独立的 y 轴刻度?没有数据的面板如果是blank/void也没关系,只要占据合适的space.
可重现的例子:
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_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()
你可以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()
这会给你一个警告,因为这 3 个组中只有一个观察值。