2015-05-22 61 views
4

我試圖使用ggplot在一個窗口框中對齊柱圖和線圖的x軸。這是我正在嘗試使用的假數據。使用ggplot對齊盒圖和線圖的x軸

library(ggplot2) 
library(gridExtra) 
m <- as.data.frame(matrix(0, ncol = 2, nrow = 27)) 
colnames(m) <- c("x", "y") 
for(i in 1:nrow(m)) 
{ 
    m$x[i] <- i 
    m$y[i] <- ((i*2) + 3) 
} 

My_plot <- (ggplot(data = m, aes(x = x, y = y)) + theme_bw()) 
Line_plot <- My_plot + geom_line() 
Bar_plot <- My_plot + geom_bar(stat = "identity") 

grid.arrange(Line_plot, Bar_plot) 

謝謝你的幫助。

回答

5

@ eipi10回答這種特殊情況,但一般情況下,您還需要均衡繪圖寬度。如果,例如,傳遞給grid.arrange當在曲線圖的一個在y標籤佔用更多的空間比其他的,即使您使用同一軸線上的每個情節,他們將不排隊:

axis <- scale_x_continuous(limits=range(m$x)) 

Line_plot <- ggplot(data = m, aes(x = x, y = y)) + theme_bw() + axis + geom_line() 

m2 <- within(m, y <- y * 1e7) 
Bar_plot <- ggplot(data = m2, aes(x = x, y = y)) + theme_bw() + axis + geom_bar(stat = "identity") 

grid.arrange(Line_plot, Bar_plot) 

enter image description here

在這種情況下,你必須平衡的情節寬度:

Line_plot <- ggplot_gtable(ggplot_build(Line_plot)) 
Bar_plot <- ggplot_gtable(ggplot_build(Bar_plot)) 

Bar_plot$widths <-Line_plot$widths 

grid.arrange(Line_plot, Bar_plot) 

enter image description here

+0

請問這種方法也可用於核絲工作使用高度調高每個地塊的y軸? –

+0

我想象。試試看? –

+0

@JakeConway是的,它的確如此。但看到這個答案更簡潔的方法:http://stackoverflow.com/questions/30492434/show-ggplot2-title-without-reserving-space-for-it/30492601#30492601 –

1

如果您使用scale_x_continuous強制ggplot使用您指定的限制,x軸上的網格線將對齊。

My_plot <- ggplot(data = m, aes(x = x, y = y)) + theme_bw() + 
       scale_x_continuous(limits=range(m$x)) 

現在,當您添加圖層時,座標軸將共享公共縮放。