Different x and y axis scales in multifaceted scatter ggplot2

前端 未结 1 805
醉酒成梦
醉酒成梦 2021-01-28 00:54

I have used lemon package with ggplot2 for plotting multifaceted scatter plot with regression and confidence interval line using the following code

1条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-28 01:16

    I have solved this issue after taking help from this post.

    First, create two plots using facet_grid and facet_wrap.

    g1 = ggplot(data_calibration, aes(Observed,Predicted))+
      geom_point(color="black",alpha = 1/3) + 
      facet_wrap(Station ~ Method, scales="free", ncol=6)+
      xlab("Measured") +
      ylab("Predicted")+ theme_bw()+
      geom_smooth(method="lm")+
      theme(strip.background = element_blank(),
            strip.text = element_blank())
    
    g2 = ggplot(data_calibration, aes(Observed,Predicted))+
      geom_point(color="black",alpha = 1/3) + 
      facet_grid(Station ~ Method, scales="free")+
      xlab("Measured") +
      ylab("Predicted")+ theme_bw()+
      geom_smooth(method="lm")
    

    Now replace the top facet strips of g1 with those from g2

    library(grid)
    library(gtable) 
    gt1 = ggplot_gtable(ggplot_build(g1))
    gt2 = ggplot_gtable(ggplot_build(g2))
    gt1$grobs[grep('strip-t.+1$', gt1$layout$name)] = gt2$grobs[grep('strip-t', gt2$layout$name)]
    grid.draw(gt1)
    

    Add the right-hand panel strips

    gt1 = gtable_add_cols(gt1, widths=gt1$widths[1], pos = -1)
    
    panel_id <- gt1$layout[grep('panel-.+1$', gt1$layout$name),]
    gt.side1 = gtable_filter(gt2, 'strip-r-1')
    gt.side2 = gtable_filter(gt2, 'strip-r-2')
    gt.side3 = gtable_filter(gt2, 'strip-r-3')
    gt1 = gtable_add_grob(gt1, zeroGrob(), t = 1, l = ncol(gt1), b=nrow(gt1))
    gt1 = gtable_add_grob(gt1, gt.side1, t = panel_id$t[1], l = ncol(gt1))
    gt1 = gtable_add_grob(gt1, gt.side2, t = panel_id$t[2], l = ncol(gt1))
    gt1 = gtable_add_grob(gt1, gt.side3, t = panel_id$t[3], l = ncol(gt1))
    
    grid.newpage()
    grid.draw(gt1)
    

    0 讨论(0)
提交回复
热议问题