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

时间:2018-01-11 23:12:27

标签: r plot ggplot2 graph facet-grid

我想创建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())

enter image description here

以下是使用facet_wrap

两次出现两次x轴的情节示例
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())

enter image description here

我想要与上面的图相同的图,但没有上图的x轴上的刻度。或者如果您愿意,我希望绘制与第一个相同的绘图,但在上图中使用x轴。

2 个答案:

答案 0 :(得分:3)

这是一个非常详细的解决方案,但我不认为你可以使用通常的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)

enter image description here

答案 1 :(得分:1)

我用来获取轴线(没有刻度线)的解决方法是使用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())

enter image description here
如果您还没有使用scales = "free",并且所有轴都在同一位置,这甚至更简单,您可以跳过为每个构面创建一个带有yintercepts的数据框,只需添加 geom_hline(yintercept = 10)(或者你的最小值是)你的绘图代码在每个面上添加一条轴线。