I have been trying to do something that seems like it should be very simple but I cannot get it right, to reorder a grouped geom_bar plot by a numeric value. Reading other questions on here it was suggested to use reorder for factors, but it seems to be ignored here. I would like to avoid using grid.arrange like in this question if possible because I like the facets, but I don't understand what else to try, any suggestions are very welcome.
After reading the suggested posts here, all work to re-order the data and these examples are all with facet_grid, but I would like my "a" groups in 2 different rows so I need to use facte_wrap I guess and nothing works for labelling correctly the x-axis in facet_wrap... I have gotten this far:
df <- data.frame(a = factor(c(1,1,2,1,2,2,1,2)),
b = factor(c(1,2,3,4,5,6,7,2)),
colb = as.character(c("#00AF4F", "#000FEF", "#004FAF", "#003FBF", "#008F6F", "#00DF1F", "#002FCF", "#000FEF")),
c = factor(c(1,2,1,2,1,2,1,2)),
value= 1:8)
In base R I am trying to get a facet for each of the levels a like this, colored by colb:
plot(df$b[df$a==1], df$value[df$a==1])
plot(df$b[df$a==2], df$value[df$a==2])
Thanks to the help below, this is working...
df <- transform(df, category2 = factor(paste(a, b)))
df <- transform(df, category2 = reorder(category2, rank(value)))
ggplot(df, aes(category2, value, fill=colb)) +
geom_bar(stat = "identity") +
facet_grid(. ~ a, scales = "free_x") +
scale_x_discrete(labels=df$b, breaks=df$category2)
but then when I try facet_wrap instead I can't get it to work with correct labels for b:
ggplot(df, aes(category2, value, fill=colb)) +
geom_bar(stat = "identity") +
facet_wrap( ~ a, nrow=2, scales = "free_x")
And now with correct labels! Thank you aosmith!
ggplot(df, aes(category2, value, fill=colb)) +
geom_bar(stat = "identity") + scale_x_discrete(labels=df$b, breaks=df$category2) + facet_wrap( ~ a, nrow=2, scales = "free_x")
What am I doing wrong? If there is no solution with facet_wrap, is there any other way I can place the groups in separate grids? I have been banging my head on this for days now...any help is VERY appreciated... Thank you very much...