EDIT: This is not a FAQ, I am not trying to order one plot but TWO in a facet_grid. Something like d$x <- reorder(d$x,d$y,mean) does only reorder the plot on the lower facet not on the other one... I would like both plots to be reordered based on the value in the point plot, the one on top. Doing as suggested in the FAQ p <- ggplot(data = d, mapping = aes(x=reorder(x,y,mean), y=y)) + ... only orders the lower plot...
So I need to reorder the x axis on BOTH plots in the facet based on the value in the dataframe d2. Combining the two seems to break the reordering in d1 and d2.
I have a combined plot using the following code:
library(plyr)
library(ggplot2)
library(grid)
library(gridExtra)
set.seed(123)
x <- sample( LETTERS[1:9], 10000, replace=TRUE, prob=c(0.1, 0.2, 0.15, 0.05,0.1, 0.2, 0.05, 0.05,0.1) )
y <- sample( c("Y","N"), 10000, replace=TRUE, prob=c(0.2, 0.8))
df <- as.data.frame(cbind(x,y))
names(df) <- c("x","y")
df$p_y <- as.numeric(df$y)-1
# create volume data for bar plot
d1 <- as.data.frame(table(df$x))
names(d1) <- c("x","y")
# create p(target) data for point plot
d2 <- ddply(df,1,summarise,y=mean(p_y))
d1$panel <- "volume"
d2$panel <- "p(target)"
# combine dataframes to one
d <- rbind(d1, d2)
# combine plots
p <- ggplot(data = d, mapping = aes_string(x="x", y="y")) +
facet_grid(panel ~ ., scales = "free") +
theme_bw() +
theme(axis.text.x = element_text(angle = 90,hjust = 1)) +
layer(data = d1, geom = c( "bar"), stat = "identity") +
layer(data = d2, geom = c( "point"), stat = "identity")
p
This produces a plot that is ordered according to the factor on the x axis, which by default is Alphabetical ... I would like to sort the X axis on the p_target value in the first plot... So that P(target) is decreasing from left to right. I have been thinkering with ordering the dataframe d to be put in the right order but facet grid puts is right back into alphabetical order...
hugo