Facet_grid failed bar chart

I'm having trouble creating a back-to-back histogram facet grid 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 graph is fine, but if I try the following, I get an error: Error: The casting formula contains variables not found in the 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 why this fails?

0
source share
2 answers

The problem is that the variables specified in facet_grid are considered in data.frames, which are passed to different levels. You created (implicitly and explicitly) data.frames that only have lat data and don't have subject information. If you use x.sub_ki and x.sub_kn , they have a subject variable associated with 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 the full ggplot syntax; which shows the parallel structure of ki and kn better.

+1
source

The syntax above does not work with newer versions of ggplot2, use instead of formatting the axes instead:

 abs_format <- function() { function(x) abs(x) } hist_K_sub <- hist_K_sub+ scale_y_continuous(labels=abs_format()) 
0
source

Source: https://habr.com/ru/post/1439243/


All Articles