【发布时间】:2014-08-11 10:30:54
【问题描述】:
问题
如何组合不同的图 (ggplot2),具有不同的 y 轴和不同的图高度,但仍保持对齐?
详情
当使用 grid.arrange(方法 1)组合不同 y 轴单位的图时,它们不会对齐。解决此问题的一种方法是使用gtable(方法2),但我无法调整绘图的相对高度。
示例
require(ggplot2)
#Make two plots, with different y axis
x = c(1, 5)
y= c(.1, .4)
data1<-data.frame(x,y)
top<-
ggplot(data1, aes(x=x, y=y))+
geom_line()
x = c(1, 5)
y= c(100000, 400000)
data2<-data.frame(x,y)
bottom<-
ggplot(data2, aes(x=x, y=y))+
geom_line()
# Method 1 - Grid Extra
require(gridExtra)
grid.arrange(top, bottom, heights=c(.6,.3))
方法1的结果是这个图,由于y轴标签的长度不同,所以没有对齐:
#Method 2 - gtable
require(gtable)
#Extract Grobs
g1<-ggplotGrob(top)
g2<-ggplotGrob(bottom)
#Bind the tables
g<-gtable:::rbind_gtable(g1, g2, "first")
#Remove a row between the plots
g <- gtable_add_rows(g, unit(-1,"cm"), pos=nrow(g1))
#draw
grid.newpage()
grid.draw(g)
方法 2 导致绘图对齐,但我无法调整每个绘图的高度。
谢谢!
【问题讨论】:
标签: r ggplot2 alignment gridextra gtable