`ggplot2 - facet_grid`:内部刻面中没有刻度的轴

`ggplot2 - facet_grid`: Axes without ticks in interior facets

我想创建 facet_grid / facet_wrap 图,其中 x 轴在每个图表下重复,但刻度仅出现在最低图表上。

这是一个使用 facet_grid

仅显示一次 x 轴的绘图示例
ggplot(mtcars, aes(y=mpg,x=cyl)) + 
  facet_grid(am~., scales="free") + 
  geom_point() + 
  theme_classic() + 
  theme(strip.background = element_rect(colour="white", fill="white"),
        strip.text.y = element_blank())

这是一个图示例,其中 x 轴出现两次,但两次都使用 facet_wrap

ggplot(mtcars, aes(y=mpg, x=cyl)) + 
  facet_wrap(~am, ncol=1, scales="free") + 
  geom_point() + 
  theme_classic() + 
  theme(strip.background = element_rect(colour="white", fill="white"),
        strip.text.x = element_blank())

我想要与上图相同的图,但上图的 x 轴上没有刻度线。或者,如果您愿意,我想要与第一个相同的图,但在上图有一个 x 轴。

我用来获取轴线(没有刻度线)的解决方法是使用 geom_hline() 来伪造一个轴。

#make a dataframe with the y minimum for each facet
fake.axes <- data.frame(mpg = c(10, 15), #y minimum to use for axis location
                    am = c(0,1)) #facetting variable

#add an "axis" without ticks to upper graph using geom_hline()
ggplot(mtcars, aes(y=mpg,x=cyl)) + 
  facet_grid(am~., scales="free") + 
  geom_point() + 
  geom_hline(aes(yintercept = mpg), fake.axes, #dataframe with fake axes 
         linetype = c("solid", "blank")) + #line for top graph, blank for bottom graph
  theme_classic() + 
  theme(strip.background = element_rect(colour="white", fill="white"),
        strip.text.y = element_blank())


如果你没有使用 scales = "free",并且所有的轴都在同一个位置,这就更简单了,你可以跳过为每个面制作一个带有 yintercepts 的数据框,只需添加 geom_hline(yintercept = 10)(或任何你的最小值)添加到你的绘图代码中,以在每个面上添加一条轴线。

这是一个非常冗长的解决方案,但我认为仅使用通常的 ggplot 函数您无法获得想要的情节。

library(ggplot2)
library(grid)

Plot <- ggplot(mtcars, aes(y=mpg, x=cyl)) + 
  facet_wrap(~am, ncol=1, scales="free") + 
  geom_point() + 
  theme_classic() + 
  theme(strip.background = element_rect(colour="white", fill="white"),
        strip.text.x = element_blank())

关闭顶部 x 轴需要修改绘图的 gtable 对象。

Plot.build <- ggplot_gtable(ggplot_build(Plot))
axis.pos <- grep("axis-b-1-1", Plot.build$layout$name)
num.ticks <- length(Plot.build$grobs[[axis.pos]]$children[2]$axis$grobs[[1]]$y)

此步骤删除轴标签:

Plot.build$grobs[[axis.pos]]$children$axis$grobs[[2]]$children[[1]]$label <- rep("", num.ticks)

此步骤删除刻度线:

Plot.build$grobs[[axes.pos]]$children[2]$axis$grobs[[1]]$y <- rep(unit(0, units="cm"), num.ticks)

最后,绘图生成使用:

grid.draw(Plot.build)