Align multiple plots in ggplot2 when some have legends and others don't

前端 未结 6 1452
离开以前
离开以前 2020-11-30 03:09

I have used the method indicated here to align graphs sharing the same abscissa.

But I can\'t make it work when some of my graphs have a legend and others don\'t.

6条回答
  •  失恋的感觉
    2020-11-30 04:03

    There might now be easier ways to do this, but your code was not far wrong.

    After you have ensured that the widths of columns 2 and 3 in gA are the same as those in gB, check the widths of the two gtables: gA$widths and gB$widths. You will notice that the gA gtable has two additional columns not present in the gB gtable, namely widths 7 and 8. Use the gtable function gtable_add_cols() to add the columns to the gB gtable:

    gB = gtable::gtable_add_cols(gB, sum(gA$widths[7:8]), 6)
    

    Then proceed with arrangeGrob() ....

    Edit: For a more general solution

    Package egg (available on github) is experimental and fragile, but works nicely with your revised set of plots.

    # install.package(devtools)
    devtools::install_github("baptiste/egg")
    
    library(egg)
    grid.newpage()
    grid.draw(ggarrange(g1,g2,g3, ncol = 1))
    

提交回复
热议问题