Image marginal histograms

March 11, 2016

(This article was first published on R – Irregularly Scheduled Programming, and kindly contributed to R-bloggers)

Another day, another interesting challenge.

I follow Bob Rudis’ (a.k.a. hrbrmstr’s) blog, typically via R-bloggers, and this post caught my eye. Partly because I thought I knew of an existing way to do this. As usual, actually getting that to work took a little longer than I might have hoped, but I think the end result is pretty neat.

His post describes the process of writing an R function to take an image file, for example this one


and producing a histogram along the sides of the number of pixels on a given row/column. This is what he created (a different image to the example, I believe)

Something funny is going on with the right-hand histogram; it doesn’t line up with the image.

Here’s my approach.

It leverages the png package to extract the channels into a matrix, converts those to x,y,z data.frames, takes the median value, plots that with ggplot2, then leverages ggExtra::ggMarginal to add the marginal histograms. Note that the ggExtra package has some bugs (it hasn’t been maintained in a while) in relation to more recent (possibly the dev branch) of ggplot2. I got it working on at least one of my machines. This is my result

file10a566a2b4dc3 vs marginal

I’ve had several uses for these types of marginal plots lately, so hopefully I can sort out the issues I’ve been getting in combination with ggplot2.

To leave a comment for the author, please follow the link and comment on their blog: R – Irregularly Scheduled Programming. 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)