2017-11-17 5 views
0

Die multiplot function is defined here in the cookbookMultiplot für gtable Objekte

die folgenden Diagramme Betrachten.

p1 = ggplot(mtcars,aes(y=mpg, x=cyl)) + geom_point() 
p2 = ggplot(mtcars,aes(y=disp, x=cyl)) + geom_point() 
multiplot(p1,p2, layout=matrix(1:2,nrow=1)) 

enter image description here

Ich möchte manipulieren (mit Funktion DoStuff) die Handlung als gtable Objekt und nicht als ggplot Objekt.

g1 = ggplot_gtable(ggplot_build(p1)) 
g1 = DoStuff(g1) 
g2 = ggplot_gtable(ggplot_build(p1)) 
g2 = DoStuff(g2) 

Ich kann eine Gtable mit grid.draw drucken.

Wie kann ich die Multiplot-Funktion ändern, so dass sie auch gtable Objekte und nicht nur ggplot Objekte akzeptiert?

Antwort

2

in meinem somewhat biased view würden Sie besser dran

gridExtra::grid.arrange(g1,g2, ncol=2) 

verwenden, aber Ihre Frage zu beantworten:

Änderung

print(plots[[i]], vp = viewport(layout.pos.row = matchidx$row, 
           layout.pos.col = matchidx$col)) 

um so etwas wie

if(inherits(plots[[i]], "gg")) { 

    print(plots[[i]], vp = viewport(layout.pos.row = matchidx$row, 
            layout.pos.col = matchidx$col)) 

    } else if(inherits(plots[[i]], "gtable")) { 

    pushViewport(viewport(layout.pos.row = matchidx$row, 
          layout.pos.col = matchidx$col)) 
    grid.draw(plots[[i]]) 
    upViewport() 
    } 

und wie vorher anrufen,

g1 <- ggplotGrob(p1) 
g2 <- ggplotGrob(p2) 
multiplot(g1,g2, layout=matrix(1:2,nrow=1)) 
Verwandte Themen