【问题标题】:ggplot2 facet wrap: y-axis scale on the first row onlyggplot2 facet wrap:仅第一行的 y 轴刻度
【发布时间】:2016-04-21 20:13:09
【问题描述】:

是否可以将 y 轴添加到 facet wrap,但仅限于第一行,如屏幕截图所示?

我的情节代码:

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) 

结果:

(我已经手动为要放置刻度的位置添加了图例)

【问题讨论】:

    标签: r ggplot2 facet


    【解决方案1】:

    这个想法来自this的回答。

    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) 
    

    注意 theme 调用中的变化,以便我们以后可以选择性地删除一些 grobs。

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

    所以我们想要删除除了四个左轴项目之外的所有项目。有一个使用正则表达式的gtable_filter 函数,但编写我自己的函数来执行简单的负子集设置更简单(因为我无法制作正确的正则表达式):

    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)
    

    【讨论】:

    • 快到了!现在有一个我不需要的 y 轴标签(“NEWCONS”)。以防万一,是否可以在保持刻度的同时避开标签?
    • @HAVB 哦,我想我太激进了,不想从你原来的theme 电话中删除它。我想如果你把它放回去就可以了。
    • @HAVB ...我的意思是,把axis.title.y = element_blank()放回去。或者只是y = NULLlabs()中。
    • 你是对的,只需将axis.title.y = element_blank() 放回theme() 调用中。已接受答案。
    • ggplot2 发生了一些变化。我不得不使用p_filtered &lt;- gtable_filter_remove(p_tab, name = paste0("axis-l-", 2:4, "-1"), trim = FALSE) 让它再次正常工作:)。谢谢!
    猜你喜欢
    • 2015-08-24
    • 1970-01-01
    • 1970-01-01
    • 2021-12-19
    • 2017-07-18
    • 2017-09-23
    • 2022-09-23
    • 1970-01-01
    • 2021-11-07
    相关资源
    最近更新 更多