Separate order in ggplot graphs

therefore, I have a simple example - a completely cross-section of three experimental experimental studies, where the continuous effect was measured for each treatment pair. I want to order each treatment individually according to each context, but I am stuck on ggplot faceting.

here is my data

df <- data.frame(treatment = rep(letters[1:3], times = 3), context = rep(LETTERS[1:3], each = 3), effect = runif(9,0,1)) 

and I can get something very close if I break down the appeal and context into one 9-point scale, as such:

 df$treat.con <- paste(df$treatment,df$context, sep = ".") df$treat.con <- reorder(df$treat.con, -df$effect, ) ggplot(df, aes(x = treat.con, y = effect)) + geom_point() + facet_wrap(~context, scales="free_x", ncol = 1) 

very close to what i want

besides achieving a separate order in each face, the new x variable that I created is potentially misleading, because it does not show that we used the same call in all three contexts.

Is this solved by manipulating the underlying factor, or is there a ggplot command for this situation?

+7
source share
2 answers

Try:

 ggplot(df, aes(x = treat.con, y = effect)) + geom_point() + facet_wrap(~context, scales="free_x", ncol = 1) + scale_x_discrete(labels=function(x) substr(x,1,1)) 

The anonymous function provided to the labels argument formats labels. In older versions of ggplot2, the formatter argument was used for this. If your treatment names have different lengths, then the substr approach may not work too well, but you can use strsplit , for example:

 + scale_x_discrete(labels=function(x) sapply(strsplit(x,"[.]"),"[",1)) 
+4
source

Graphics is not really the right tool for what you want to do, because it is really designed for situations of a general scale.

It may make sense to make each chart separately and then arrange them each using grid.arrange from the gridExtra package. (Be careful, the following code may seem a little incomprehensible if you are not familiar with these tools!)

 #I use stringsAsFactors simply to ensure factors on # my system. df <- data.frame(treatment = rep(letters[1:3], times = 3), context = rep(LETTERS[1:3], each = 3), effect = runif(9,0,1),stringsAsFactors = TRUE) require(gridExtra) #One "master" plot (to rule them all) p <- ggplot(df,aes(x = treatment,y = effect)) + geom_point() + facet_wrap(~context) #Split data set into three pieces df_list <- split(df,df$context) #...and reorder the treatment variable of each one df_list <- lapply(df_list,function(x){x$treatment <- reorder(x$treatment,-x$effect); x}) #"Re-do" the plot p using each of our three smaller data sets # This is the line that might be the most mysterious p_list <- lapply(df_list,function(dat,plot){plot %+% dat},plot = p) #Finally, place all three plots on a single plot do.call(grid.arrange,p_list) 

enter image description here

+4
source

All Articles