2017-12-06 6 views
3

Ich verwende egg Paket von @baptiste entwickelt. Unten ist ein Beispiel von GitHub. Ich frage mich, ob es möglich ist, zwei Spalten mit den Titeln a) und c) statt Plot-Bereich auszurichten? Vielen Dank!Wie kann ich mehrere Plots an ihren Titeln anstatt an der Plotfläche ausrichten?

Code:

library(egg) 
library(grid) 

p1 <- ggplot(mtcars, aes(mpg, wt, colour = factor(cyl))) + 
    geom_point() + ggtitle("a)") 
p1 

p2 <- ggplot(mtcars, aes(mpg, wt, colour = factor(cyl))) + 
    geom_point() + facet_wrap(~ cyl, ncol = 2, scales = "free") + 
    guides(colour = "none") + 
    theme() + ggtitle("b)") 
p2 

p3 <- ggplot(mtcars, aes(mpg, wt, colour = factor(cyl))) + 
    geom_point() + facet_grid(. ~ am, scales = "free") + guides(colour="none") + 
    ggtitle("c)") 
p3 

g1 <- ggplotGrob(p1) 

g2 <- ggplotGrob(p2) 

g3 <- ggplotGrob(p3) 

fg1 <- gtable_frame(g1, debug = TRUE) 
fg2 <- gtable_frame(g2, debug = TRUE) 
fg12 <- gtable_frame(gtable_rbind(fg1, fg2), 
        width = unit(2, "null"), 
        height = unit(1, "null")) 
fg3 <- 
    gtable_frame(
    g3, 
    width = unit(2, "null"), 
    height = unit(1, "null"), 
    debug = TRUE 
) 
grid.newpage() 
combined <- gtable_cbind(fg12, fg3) 
grid.draw(combined) 

Grundstück:

enter image description here

Antwort

2

fand ich eine andere Art und Weise unter Verwendung cowplot Paket

left_col <- cowplot::plot_grid(p1 + ggtitle(""), p2 + ggtitle(""), 
           labels = c('a)', 'b)'), label_size = 14, 
           ncol = 1, align = 'v', axis = 'lr') 
cowplot::plot_grid(left_col, p3 + ggtitle(""), 
        labels = c('', 'c)'), label_size = 14, 
        align = 'h', axis = 'b') 

enter image description here

Siehe auch here

Edit:

Ein kürzlich entwickeltes Paket patchwork für ggplot2 auch den Job

erledigen
library(patchwork) 

{ 
    p1 + {p2} + patchwork::plot_layout(ncol = 1) 
}/p3 + patchwork::plot_layout(ncol = 2) 

enter image description here

+1

Ihre linke Spalte in Ihrer Cowplot-Lösung ist nicht vollständig ausgerichtet. Ich denke, es braucht "axis = 'lr'" statt "axis =' r'", aber das habe ich nicht ausprobiert. –

+0

Sie hatten Recht. Danke für die Korrektur! – Tung

2

eine leere Dummy Facettierung Variable Hinzufügen p1/a) zu zeichnen scheint, wie die einfachste Lösung

enter image description here

+0

Vielen Dank für die Hilfe sehr viel! Das ist ziemlich clever. Ich suche jedoch nach einer allgemeineren Lösung. Siehe die Antwort, die ich gerade gefunden habe – Tung

Verwandte Themen