Elio Campitelli
Elio Campitelli

Reputation: 1476

Remove axis text from one facet

I'm trying to display three time series using facet_grid() and in order to save space, I'm reducing panel spacing between them. The problem is that their vertical axis overlap so I want to move it to the right only on the plot in the middle.

Since this seem impossible in ggplot2, what I'm trying to do is to render every axis and then remove it editing the gtable but so far I was not successful.

This is a minimal example:

library(ggplot2)

set.seed(123)
df <- data.frame(expand.grid(x = 1:150, type = letters[1:3]))
df$y <- df$x*0.016 + rnorm(150, sd = .5)

ggplot(df, aes(x, y)) + geom_line() +
    facet_grid(type~.) + 
    theme(panel.spacing.y = unit(-3, "lines"), strip.text = element_blank()) +
    scale_y_continuous(sec.axis = dup_axis(name = ""), name = "y")

Which produces this:

Produced plot

And I want to delete each axis text to get to this:

Plot made with gimp

Thanks!

Upvotes: 3

Views: 585

Answers (1)

Elio Campitelli
Elio Campitelli

Reputation: 1476

The solution was to assign a nullGrob() to the relevant elements of the gTable.

gt <- ggplotGrob(g)
t <- gt[["grobs"]][[8]][["children"]][[2]]

# Found those grobs by looking around the table. 
gt[["grobs"]][[8]][["children"]][[2]] <- nullGrob()
gt[["grobs"]][[10]][["children"]][[2]] <- nullGrob()
gt[["grobs"]][[12]][["children"]][[2]] <- nullGrob()

grid.newpage()
grid.draw(gt)

good plot

Upvotes: 5

Related Questions