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

妖精的绣舞 提交于 2019-12-12 11:03:54

问题


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:

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


回答1:


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)



来源:https://stackoverflow.com/questions/36779537/ggplot2-facet-wrap-y-axis-scale-on-the-first-row-only

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!