Aligning and arranging charts in ggplot

心已入冬 提交于 2019-12-31 03:05:21

问题


I have two plots in ggplot with similar ranges on the axis that I would like to align.

Using:

library(grid)
grid.newpage()
grid.draw(rbind(ggplotGrob(g1), ggplotGrob(g2), size = "last"))

where size='last' ensures the grids are aligned for x, I get a layout such as this:

The top chart has an excessive vertical range for the simple row I want to depict.

I would like to have an image more in keeping with the following:

Or alternatively, with the g1 chart aligned below the axis of the g2 chart. (For generality, let's say I want to be able to choose either, or even overlay g1 on top of g2.

(My original model was a single chart with the g1 component simply set as a layer in the g2 chart with y=0; however, the chart is too cluttered to read with that layout, so I thought I should move the original y=0 elements into a separate panel (i.e. g1).

Minimal Example:

size=50
df1=data.frame(x=seq(1,size),y=sample(-100:100,size,rep=TRUE))
df2=data.frame(x=seq(1,size),r=replicate(size,paste(sample(c(letters, LETTERS),3),collapse='')))
g1=ggplot(df1)+geom_point(aes(x=x,y=y))
g2=ggplot(df2)+geom_text(aes(x=x,y=0,label=r),angle=45,size=2)
library(grid) 
grid.newpage()
grid.draw(rbind(ggplotGrob(g1), ggplotGrob(g2), size = "last"))

I want the label strip (g2) to be positioned neatly with respect to the scatterplot. The g2 strip was part of the original chart as a geom_text() element at y=0 but the chart was too cluttered around there with the labels placed there too.


回答1:


you simply need to edit the heights of the gtable,

library(ggplot2)
library(grid)
g1 <- g2 <- ggplotGrob(qplot(1,1))

g <- rbind(g1,g2,size="last")
id <- g$layout$t[g$layout$name == "panel"]
g$heights[id] <- lapply(c(1,4), "unit", "null")
grid.newpage()
grid.draw(g)

Edit: with the more specific instructions, I'd suggest a different strategy: add the first panel only to the gtable of the second plot,

p1 <- ggplot(df1)+geom_point(aes(x=x,y=y))
p2 <- ggplot(df2)+geom_text(aes(x=x,y=0,label=r),angle=45,size=2)
snug <- theme_bw() + theme(plot.margin=unit(c(0.5,0.5,0,0),"line"))

library(gtable)
g1=gtable_filter(ggplotGrob(p1 + snug), pattern = "panel", trim = TRUE, fixed=TRUE)
g2=ggplotGrob(p2 + snug)

g <- g2
g <- gtable_add_rows(g, unit(0.2, "null"), 0)
g <- gtable_add_grob(g, g1, 1, 4)
grid.newpage()
grid.draw(g)



来源:https://stackoverflow.com/questions/28255101/aligning-and-arranging-charts-in-ggplot

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!