2 views

Is there a way of creating scatterplots with marginal histograms just like in the sample below in ggplot2? In Matlab, it is the scatterhist() function and there exist equivalents for R as well. However, I haven't seen it for ggplot2.

I started an attempt by creating the single graphs but don't know how to arrange them properly.

require(ggplot2)

x<-rnorm(300)

y<-rt(300,df=2)

xy<-data.frame(x,y)

xhist <- qplot(x, geom="histogram") + scale_x_continuous(limits=c(min(x),max(x))) + opts(axis.text.x = theme_blank(), axis.title.x=theme_blank(), axis.ticks = theme_blank(), aspect.ratio = 5/16, axis.text.y = theme_blank(), axis.title.y=theme_blank(), background.colour="white")

yhist <- qplot(y, geom="histogram") + coord_flip() + opts(background.fill = "white", background.color ="black")

yhist <- yhist + scale_x_continuous(limits=c(min(x),max(x))) + opts(axis.text.x = theme_blank(), axis.title.x=theme_blank(), axis.ticks = theme_blank(), aspect.ratio = 16/5, axis.text.y = theme_blank(), axis.title.y=theme_blank() )

scatter <- qplot(x,y, data=xy)  + scale_x_continuous(limits=c(min(x),max(x))) + scale_y_continuous(limits=c(min(y),max(y)))

none <- qplot(x,y, data=xy) + geom_blank()

and arranging them with the function posted here. But to make a long story short: Is there a way of creating these graphs?

by

To plot a scatterplot with marginal histograms in ggplot2, you can use the grid.arrange function from the gridExtra package as follows:

To create a Scatter plot:

scatter <- ggplot()+geom_point(aes(rnorm(1000), rnorm(1000)))

To create the histogram to be placed on top of the scatter plot:

hist_top <- ggplot()+geom_histogram(aes(rnorm(1000)))

To create the histogram to be placed at the right side of the scatter plot:

hist_right <- ggplot()+geom_histogram(aes(rnorm(1000)))+coord_flip()

To create an empty space between the histograms and scatter plot:

empty <- ggplot()+geom_point(aes(1,1), colour="white")+

theme(axis.ticks=element_blank(),

panel.background=element_blank(),

axis.text.x=element_blank(), axis.text.y=element_blank(),

axis.title.x=element_blank(), axis.title.y=element_blank())

To plot the scatter plot with marginal histograms:

library("ggplot2")

library("gridExtra")

grid.arrange(hist_top, empty, scatter, hist_right, ncol=2, nrow=2, widths=c(4, 1), heights=c(1, 4))

Output: