[R] problems with geom_vline, histograms, scale=free and facets in ggplot

Julian Burgos jmburgos at uw.edu
Sat Jun 11 06:14:40 CEST 2011


Dear list,

I´m having a little trouble with adding vertical lines to a histogram.
 I need to draw a matrix of histograms (using facets), and in each
histogram add a vertical line indicating the mean value of the data in
each facet.  According to the last example in the geom_hline help, to
display different lines in each facet I need to provide a data frame.
I modified this example to make a plot similar to what I need:


# BEGIN R CODE ############################################
# This example works and does exactly what I need
library(reshape)
library(ggplot2)

# First, create a data frame with the mean value, to add to each facet
mean.data=tapply(mtcars$wt,INDEX=list(mtcars$vs,mtcars$am),mean)
mean.data=melt(mean.data)
colnames(mean.data)=c("vs","am","wt.mean")

# Now do the plot
p <- qplot(wt, data=mtcars)
p <- p + facet_grid(vs ~ am,scale="free")
p <- p + geom_vline(aes(xintercept = wt.mean), mean.data,col="red")
p
###########################################################

###########################################################
# This one does not work
# Create a test data set
set.seed(100)
my.data=data.frame(code1=rep(c("A","B","C"),each=30),
                  code2=rep(rep(c("D","E","F"),each=10),3),
                  n=runif(90))

# Create a data frame with the mean value, to add to each facet
mean.data=tapply(my.data$n,INDEX=list(my.data$code1,my.data$code2),mean)
mean.data=melt(mean.data)
colnames(mean.data)=c("code1","code2","n.mean")

# Now do the plot
p = qplot(n, data=my.data) +
      facet_grid(code2 ~ code1, scales="free")
p + geom_vline(aes(xintercept = n.mean), mean.data,col="red")

#With this I get the following error: "Error in if (length(range) == 1
|| diff(range) == 0) { :   missing value where TRUE/FALSE needed".

# If I remove the "scales=free" argument. I get the lines but also a
lot of extra empty facets.

p = qplot(n, data=my.data) +
      facet_grid(code2 ~ code1)
p + geom_vline(aes(xintercept = n.mean), mean.data,col="red")

# END R CODE ##################################################

I can´t figure out why the second example does not work when having
the "scales=free" argument, and why I get the extra facets when
removing it.  Is this a bug?  Any help will be very welcomed.

Julian

--
Julian Mariano Burgos
Hafrannsóknastofnunin/Marine Research Institute
Skúlagata 4, 121 Reykjavík, Iceland
Sími/Telephone : +354-5752037
Bréfsími/Telefax:  +354-5752001
Netfang/Email: julian at hafro.is, jmburgos at uw.edu



More information about the R-help mailing list