Learning ggplot2: 2D plot with histograms for each dimension

September 3, 2009

(This article was first published on bioCS, and kindly contributed to R-bloggers)

I have two 2D distributions and want to show on a 2D plot how they are related, but I also want to show the histograms (actually, density plots in this case) for each dimension. Thanks to ggplot2 and a Learning R post, I have sort of managed to do what I want to have:

There are still two problems: The overlapping labels for the bottom-right density axis, and a tiny bit of misalignment between the left side of the graphs on the left. I think that the dot in the labels for the density pushes the plot a tiny bit to the right compared with the 2D plot. Any ideas?

Here’s the code (strongly based on the afore-linked post on Learning R):

p <- qplot(data = mtcars, mpg, hp, geom = "point", colour = cyl)

p1 <- p + opts(legend.position = "none")

p2 <- ggplot(mtcars, aes(x=mpg, group=cyl, colour=cyl))
p2 <- p2 + stat_density(fill = NA, position="dodge")
p2 <- p2 + opts(legend.position = "none", axis.title.x=theme_blank(),

p3 <- ggplot(mtcars, aes(x=hp, group=cyl, colour=cyl))
p3 <- p3 + stat_density(fill = NA, position="dodge") + coord_flip()
p3 <- p3 + opts(legend.position = "none", axis.title.y=theme_blank(),

legend <- p + opts(keep= "legend_box")

## Plot Layout Setup
Layout <- grid.layout( nrow = 2, ncol = 2,
widths = unit (c(2,1), c("null", "null")),
heights = unit (c(1,2), c("null", "null"))
vplayout <- function (...) {
pushViewport(viewport(layout= Layout))
subplot <- function(x, y) viewport(layout.pos.row=x, layout.pos.col=y)

# Plotting
print(p1, vp=subplot(2,1))
print(p2, vp=subplot(1,1))
print(p3, vp=subplot(2,2))
print(legend, vp=subplot(1,2))

To leave a comment for the author, please follow the link and comment on their blog: bioCS.

R-bloggers.com offers daily e-mail updates about R news and tutorials on topics such as: Data science, Big Data, R jobs, visualization (ggplot2, Boxplots, maps, animation), programming (RStudio, Sweave, LaTeX, SQL, Eclipse, git, hadoop, Web Scraping) statistics (regression, PCA, time series, trading) and more...

If you got this far, why not subscribe for updates from the site? Choose your flavor: e-mail, twitter, RSS, or facebook...

Comments are closed.

Search R-bloggers


Never miss an update!
Subscribe to R-bloggers to receive
e-mails with the latest R posts.
(You will not see this message again.)

Click here to close (This popup will not appear again)