[R] Overlaying two graphs using ggplot2 in R

David Winsemius dwinsemius at comcast.net
Tue Jan 28 03:40:14 CET 2014

On Jan 27, 2014, at 3:13 AM, Kristi Glover wrote:

> Hi R Users,
> I was struggling to overlay two graphs created from the two different dataset using ggplot2. Furthermore, I could not join means of the box plots.
> I tried this way but did not work. Any suggestions?
> dat1<-structure(list(site = c(1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 
> 2L, 2L, 3L, 3L, 3L, 3L, 3L, 3L, 3L), layer = structure(c(2L, 
> 2L, 2L, 1L, 1L, 1L, 2L, 2L, 2L, 1L, 1L, 1L, 2L, 2L, 2L, 1L, 1L, 
> 1L, 1L), .Label = c("bottom", "top"), class = "factor"), Present = c(120L, 
> 125L, 123L, 23L, 21L, 19L, 131L, 124L, 127L, 24L, 27L, 25L, 145L, 
> 143L, 184L, 29L, 14L, 17L, 38L)), .Names = c("site", "layer", 
> "Present"), row.names = c(NA, 19L), class = "data.frame")
> dat1
> dat2<-structure(list(site = 1:3, present = c(-3L, 2L, 5L)), .Names = c("site", 
> "present"), row.names = c(NA, 3L), class = "data.frame")
> dat2
> library("plyr")
> library(ggplot2)
> A<-ggplot(dat1, aes(x = factor(site), y = Present, colour = layer, fill=layer)) + 
>    geom_boxplot(outlier.shape = 16, outlier.size = 1)  + theme_bw()+ ylim(0,185)
> # Here I wanted to join the means of the boxplots among the sites, but I could not join it.
> B<-ggplot(dat2, aes(x=factor(site),y= present, colour="blue") + 
>     geom_line() + geom_point()) # wanted to plot it using second y axis. 
> A+B
> Thanks for your help.

I believe you may be able to find 'ggplot2' hacks that deliver double ordinate plots but Hadley Wickham has an intense aversion to such plots, so you won't find them in standard `gglot2` functions. Do a search on StackOverflow and in the archives. I cannot remember the names of the functions or the authors, but I do remember experiencing the heresy of double ordinates within the vaulted arches the Church of GGplot.

> 	[[alternative HTML version deleted]]

And you should learn to post in plain text.


David Winsemius
Alameda, CA, USA

More information about the R-help mailing list