ggplot2:Reversing the order of a discrete character variable for each facet on a free scale?
ggplot2, r
Solution
You can transform the string vector to a factor and specify the order of levels:
The following command will create a factor. The levels are in decreasing alphabetical order:
msleep.noNA.red <- within(msleep.noNA.red,
name <- ordered(name, levels = rev(sort(unique(name)))))
Now you can plot the data:
pg <- ggplot(msleep.noNA.red, aes(value, name, colour = variable)) +
geom_point() +
facet_grid(vore ~ ., scale="free_y", space = "free_y")
Problem
I'd like to plot a faceted ggplot2 dot plot. x-axis is continuous, y-axis is a list of animals. Two variables are plotted and faceted according to eating behavior. The y-axis is on a free scale because each animal only appears in one eating behavior category. ``` library(ggplot2) # First clean up the data set: msleep.noNA <- msleep[!is.na(msleep$vore),] msleep.noNA.red <- msleep.noNA[c(1,3,6,7)] msleep.noNA.red <- msleep.noNA.red[!is.na(msleep.noNA.red[4]),] msleep.noNA.red <- melt(msleep.noNA.red) pg <- ggplot(msleep.noNA.red, aes(value, name, colour = variable)) + geom_point() + facet_grid(vore ~ ., scale="free_y", space = "free_y") pg # Try to reverse order of the y axis: pg + scale_y_reverse() # Not possible because its a factor, but it's not classified as such: class(msleep.noNA.red$name) ``` Does anybody have some clues as to how I can make the list of animal names alphabetical in each sub-plot?