Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ggplot2 facet wrap: y-axis scale on the first row only

Tags:

r

ggplot2

facet

Is it possible to add a y-axis to a facet wrap, but only for the first row, as shown in the screenshot?

Code for my plot:

library(ggplot2)

mydf <- read.csv('https://dl.dropboxusercontent.com/s/j3s5sov98q9yvcv/BPdf_by_NB')

ggplot(data = mydf) +
  geom_line(aes(x = YEARMONTH, y = NEWCONS, group = 1), color="darkseagreen3")  +
  geom_line(aes(x = YEARMONTH, y = DEMOLITIONS, group = 1), color = "black") +
  theme_minimal() + 
  labs(title="New constructions Vs Demolitions (2010 - 2014)\n") +
  theme( axis.line = element_blank(),
         axis.title.x = element_blank(),
         axis.title.y = element_blank(),
         axis.text.x = element_blank(),
         axis.text.y = element_blank()) +
  facet_wrap(~ NB) 

Result:

ggplot2 facet wrap

(I've manually added a legend for the place where I want to place the scale)

like image 961
HAVB Avatar asked Apr 21 '16 20:04

HAVB


1 Answers

The idea for this was taken from this answer.

p <- ggplot(data = mydf) +
    geom_line(aes(x = YEARMONTH, y = NEWCONS, group = 1), color="darkseagreen3")  +
    geom_line(aes(x = YEARMONTH, y = DEMOLITIONS, group = 1), color = "black") +
    theme_minimal() + 
    labs(title="New constructions Vs Demolitions (2010 - 2014)\n") +
    theme( axis.line = element_blank(),
                 axis.title.x = element_blank(),
                 axis.text.x = element_blank()) +
    facet_wrap(~ NB) 

Note the changes in the theme call, so that we can selective remove some grobs later.

library(gtable)
p_tab <- ggplotGrob(p)
print(p_tab)

So we want to remove all but four of the left axis items. There's a gtable_filter function using regexes, but it was simpler to just write my own function that does simple negative subsetting (since I couldn't craft the correct regex):

gtable_filter_remove <- function (x, name, trim = TRUE){
    matches <- !(x$layout$name %in% name)
    x$layout <- x$layout[matches, , drop = FALSE]
    x$grobs <- x$grobs[matches]
    if (trim) 
        x <- gtable_trim(x)
    x
}

p_filtered <- gtable_filter_remove(p_tab,name = paste0("axis_l-",5:16),trim=FALSE)

library(grid)
grid.newpage()
grid.draw(p_filtered)

enter image description here

like image 127
joran Avatar answered Oct 31 '22 23:10

joran