这是一个有点丑陋的解决方法。想法是将损坏部分中的 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).
箱线图的替代方法:
您可以复制数据并操纵位置比例来显示您想要的,而不是审查中断的位。我们依靠坐标系对数据的裁剪来裁剪图形对象。
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())