aligning distinct non-facet plots in ggplot2 using Rpy2 in Python

前端 未结 3 1473
广开言路
广开言路 2021-01-02 01:55

I am combining two distinct plots into a grid layout with grid as suggested by @lgautier in rpy2 using python. The top plot is a density and and the bottom a ba

3条回答
  •  遥遥无期
    2021-01-02 02:23

    Untested translation of the answer using gridExtra's grid.arrange(). The left sides of the plots (where the labels for the y-axis are) might not always be aligned though.

    from rpy2.robjects.packages import importr
    gridextra = importr('gridExtra')
    from rpy2.robjects.lib import ggplot2
    _ggplot2 = ggplot2.ggplot2
    def dollar(x, name): # should be included in rpy2.robjects, may be...
        return x[x.index(name)]
    
    def g_legend(a_gplot):
        tmp = _ggplot2.ggplot_gtable(_ggplot2.ggplot_build(a_gplot))
        leg = [dollar(x, 'name')[0] for x in dollar(tmp, 'grobs')].index('guide-box')
        legend = dollar(tmp, 'grobs')[leg]
        return legend
    legend1 = g_legend(p1)
    legend2 = g_legend(p2)
    nolegend = ggplot2.theme(**{'legend.position': 'none'})
    gridexta.grid_arrange(p1 + nolegend, legend1, 
                          p2 + nolegend, legend2,
                          ncol=2, widths = FloatVector((5.0/6,1.0/6)))
    

提交回复
热议问题