2016-12-19 15 views
7

私はお互いの下にいくつかのプロットを配置する必要があり、マージンとFigure領域の幅をきちんと整列させたいと思います。私は2つの単一プロットが必要であり、1つのプロットプロットは必要ないことに注意してください。私は別々のPNGファイルにそれぞれを保存したい。私はちょうどそれらの構造(マージン、図の領域のサイズ)を同一にしたい。ggplot2のマージン/フィギュア領域の幅を整列/設定する

library(ggplot2) 

d <- data.frame(label=c("some very longe label with lots of text", 
         "another long label with lots of text", 
         "short", 
         "also short", 
         "          short", 
         "        also short"), 
         x = 1:6) 

ggplot(d[1:2, ], aes(label, x)) + geom_bar(stat = "identity") + coord_flip() 
ggplot(d[3:4, ], aes(label, x)) + geom_bar(stat = "identity") + coord_flip() 

enter image description here enter image description here

私が欲しいのは、余分な空白を追加することなく、当然のことながら、多かれ少なかれ以下のように、プロット1と同じ左マージン幅を持っているプロット2である。)

enter image description here

ベースグラフィックでは、それに応じてpar("mar")を設定します。

これをggplotでどうすれば達成できますか?

+0

このコメントhttp://stackoverflow.com/questions/41230345/ggplot2-change-plot-areas-for-same-size-にあるリンクを参照してください。プロット - インマルチプロット#comment69662588_41230345 – user20650

+0

https://github.com/baptiste/egg#setting-panel-size – baptiste

答えて

5

last link from the comment aboveからの回答に基づいて、 は、プロットの幅を同じにすることができます。その答えとの唯一の違いは、それらが結合されていないということです。あなたのプロットに対してそう

library(ggplot2) 
p1 <- ggplot(d[1:2, ], aes(label, x)) + geom_bar(stat = "identity") + coord_flip() 
p2 <- ggplot(d[3:4, ], aes(label, x)) + geom_bar(stat = "identity") + coord_flip() 

同一視プロットの幅

library(grid) 
gl <- lapply(list(p1,p2), ggplotGrob) 
wd <- do.call(unit.pmax, lapply(gl, "[[", 'widths')) 
gl <- lapply(gl, function(x) { 
     x[['widths']] = wd 
     x}) 

プロット生成

grid.newpage(); grid.draw(gl[[1]]) 
grid.newpage(); grid.draw(gl[[2]]) 

プロットを1

enter image description here

プロット2

enter image description here

+0

素晴らしい、ありがとう!幅はここで重要です。あなたはggplotの図形領域の構造をよく知っていますか?これは基本図形のようなものです:http://www.melissaclarkson.com/resources/R_guides/documents/figure_layout_Ver1.pdf –

+0

@MarkHeckmann;バプティストは本当にこれを手助けする人です。しかし、彼の[egg package'](https://github.com/baptiste/egg)の 'expose_layout'が役に立ちます。したがって、 'p1 < - qplot(mpg、wt、data = mtcars、color = cyl)+ ggtitle("ファセットプロット ")を使います。 g = expose_layout(p1); g $ widths'となります。次に、幅が露出レイアウトプロットとどのように揃うかを確認します。 (幅は左から右へ)(他のものを調べるには 'names(g)'も見てください) – user20650

関連する問題