I am a newbie using ggplot2 and I'm trying to plot a scatter plot above a heatmap. Both plots have the same discrete x-axis.
This is the code I'm trying:
library(ggplot2) library(grid) library(reshape2) #data for the scatterplot df = data.frame(id1 = letters[1:10], C = abs(rnorm(10))) #scatter plot p1 <- ggplot(df, aes(x= id1, y = C)) + geom_point(pch = 19) + theme_bw() + scale_x_discrete(expand = c(0, 0), breaks = letters[1:10]) + theme(legend.position = "none") + theme(axis.title.y = element_blank()) + theme(axis.title.x = element_blank()) #data for the heatmap X = data.frame(matrix(rnorm(100), nrow = 10)) names(X) = month.name[1:10] X = melt(cbind(id1 = letters[1:10], X)) #heatmap p2 <- ggplot(X, aes(x = id1, y = variable, fill = value)) p2 <- p2 + geom_tile() p2 <- p2 + scale_fill_gradientn(colours = c("blue", "white" , "red")) p2 <- p2 + theme(legend.position = "none") + theme(axis.title.y = element_blank()) + theme(axis.title.x = element_blank()) p2 <- p2 + scale_x_discrete(expand = c(0, 0), breaks = letters[1:10]) p2 <- p2 + scale_y_discrete(expand = c(0, 0)) layt <- grid.layout(nrow=2,ncol=1,heights=c(2/8,6/8),default.units=c('null','null')) vplayout <- function(x,y) {viewport(layout.pos.row = x, layout.pos.col = y)} grid.newpage() pushViewport(viewport(layout=layt)) print(p1,vp=vplayout(1,1)) print(p2,vp = vplayout(2,1)) The problem is that the axis are not situated one above the other.
Is there any solution? It is possible to reshape the data and make something like facets?

grid.extrapackage, but aligning axes like this is always difficult. You may want to consider different visualizations (i.e. include the legend in your heatmap so you can avoid the need for a scatter plot).