FGiorlando
FGiorlando

Reputation: 1131

facet_grid of back to back histogram failing

I am having some trouble creating a facet grid of a back-to-back histogram created with ggplot.

# create data frame with latency values
latc_sorted <- data.frame(  
subject=c(1,1,1,1,1,2,2,2,2,2),
grp=c("K_N","K_I","K_N","K_I","K_N","K_I","K_N","K_I","K_N","K_I"), 
lat=c(22,45,18,55,94,11,67,22,64,44)    
)   

# subset and order data 
x.sub_ki<-subset(latc_sorted, grp=="K_I")
x.sub_kn<-subset(latc_sorted, grp=="K_N")
x.sub_k<-rbind(x.sub_ki,x.sub_kn)
x=x.sub_ki$lat
y=x.sub_kn$lat
nm<-list("x","y")

# make absolute values on x axis
my.abs<-function(x){abs(x)}

# plot back-to-back histogram
hist_K<-qplot(x, geom="histogram", fill="inverted", binwidth=20) +
geom_histogram(data=data.frame(x=y), aes(fill="non-inverted", y=-..count..),
binwidth= 20) + scale_y_continuous(formatter='my.abs') + coord_flip() + 
scale_fill_hue("variable")

hist_K

this plots fine but if I try the following I get the error: Error: Casting formula contains variables not found in molten data: x.sub_k$subject

hist_K_sub<-qplot(x, geom="histogram", fill="inverted", binwidth=20) +
geom_histogram(data=data.frame(x=y), aes(fill="non-inverted", y=-..count..),
binwidth= 20) + scale_y_continuous(formatter='my.abs') + coord_flip() + 
scale_fill_hue("variable")+
facet_grid(x.sub_k$subject ~ .)

hist_K_sub

any ideas what is causing this to fail?

Upvotes: 0

Views: 1177

Answers (2)

FGiorlando
FGiorlando

Reputation: 1131

The syntax above doesn't work with newer versions of ggplot2, use the following instead for the formatting of axes:

abs_format <- function() {
function(x) abs(x) 
}

hist_K_sub <- hist_K_sub+ scale_y_continuous(labels=abs_format())

Upvotes: 0

Brian Diggs
Brian Diggs

Reputation: 58845

The problem is that the variables referenced in facet_grid are looked for in the data.frames that are passed to the various layers. You have created (implicitly and explicitly) data.frames which have only the lat data and do not have the subject information. If you use x.sub_ki and x.sub_kn instead, they do have the subject variable associated with the lat values.

hist_K_sub <- 
ggplot() +
  geom_histogram(data=x.sub_ki, aes(x=lat, fill="inverted",     y= ..count..), binwidth=20) +
  geom_histogram(data=x.sub_kn, aes(x=lat, fill="not inverted", y=-..count..), binwidth=20) +
  facet_grid(subject ~ .) +
  scale_y_continuous(formatter="my.abs") +
  scale_fill_hue("variable") +
  coord_flip()

hist_K_sub

hist_K_sub

I also converted from qplot to full ggplot syntax; that shows the parallel structure of ki and kn better.

Upvotes: 1

Related Questions