[英]How to plot facets with discontinuous y-axis
我正在尝试生成一个带有不连续 y 轴的 plot 但不能让刻面标题只显示一次:
示例数据:
data(mpg)
library(ggplot2)
> ggplot(mpg, aes(displ, cty)) +
+ geom_point() +
+ facet_grid(. ~ drv)
经过大量挖掘,这似乎在ggplot2
中是不可能的,但我发现了gg.gap
package。 但是,此 package 复制了 plot 的每个段的分面标题。 假设我想要 y 轴从 22-32 中断,如下所示:
library(gg.gap)
gg.gap(plot = p,
segments = c(22, 32),
ylim = c(0, 35))
每个 plot 段都会出现分面标题,但这显然非常令人困惑且在美学上很糟糕。 对于任何人可以提供的帮助,我将不胜感激。 我难住了。
我知道如果我在基础 R 中使用 plot,这是可能的,但考虑到其他限制,我无法这样做(我需要ggplot2
提供的图形/语法。
提前致谢!
这是一个有点丑陋的解决方法。 我们的想法是将损坏部分中的 y 值设置为NA
,这样就不会在此处绘制任何点。 然后,我们在findInterval()
上设置轴的中断(负数,因为我们想保留从下到上的轴)。 最后,我们使用ggh4x::force_panelsizes()
手动调整面板的大小,将第二个面板设置为 0 高度。 完全免责声明,我写了 ggh4x,所以我有偏见。
一些细节:通过将相关主题元素设置为空白来隐藏 y 方向的条带。 此外,理想情况下,您应该计算上刻面与下刻面的比例,并将0.2
替换为该数字。
library(ggplot2)
library(ggh4x)
ggplot(mpg, aes(displ, cty)) +
geom_point(aes(y = ifelse(cty >= 22 & cty < 32, NA, cty))) +
facet_grid(-findInterval(cty, c(-Inf, 22, 32, Inf)) ~ drv,
scales = "free_y", space = "free_y") +
theme(strip.background.y = element_blank(),
strip.text.y = element_blank(),
panel.spacing.y = unit(5.5/2, "pt")) +
force_panelsizes(rows = c(0.2, 0, 1))
#> Warning: Removed 20 rows containing missing values (geom_point).
箱线图的替代方法:
您可以复制数据并操纵 position 标度来显示您想要的,而不是审查中断位。 我们依靠坐标系对数据的裁剪来裁剪图形对象。
library(ggplot2)
library(ggh4x)
ggplot(mpg, aes(class, cty)) +
geom_boxplot(data = ~ transform(., facet = 2)) +
geom_boxplot(data = ~ transform(., facet = 1)) +
facet_grid(facet ~ drv, scales = "free_y", space = "free_y") +
facetted_pos_scales(y = list(
scale_y_continuous(limits = c(32, NA), oob = scales::oob_keep, # <- keeps data
expand = c(0, 0, 0.05, 0)),
scale_y_continuous(limits= c(NA, 21), oob = scales::oob_keep,
expand = c(0.05, 0, 0, 0))
)) +
theme(strip.background.y = element_blank(),
strip.text.y = element_blank())
这是一种依赖于在 ggplot2 之前更改数据的方法,然后调整比例标签,类似于您对辅助 y 轴所做的操作。
library(dplyr)
low_max <- 22.5
high_min <- 32.5
adjust <- high_min - low_max
mpg %>%
mutate(cty2 = as.numeric(cty),
cty2 = case_when(cty < low_max ~ cty2,
cty > high_min ~ cty2 - adjust,
TRUE ~ NA_real_)) %>%
ggplot(aes(displ, cty2)) +
geom_point() +
annotate("segment", color = "white", size = 2,
x = -Inf, xend = Inf, y = low_max, yend = low_max) +
scale_y_continuous(breaks = 1:50,
label = function(x) {x + ifelse(x>=low_max, adjust, 0)}) +
facet_grid(. ~ drv)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.