How do I re-arrange…?: Ordering a plot.

October 15, 2012
By

(This article was first published on TRinker's R Blog » R, and kindly contributed to R-bloggers)

One of the most widely seen FAQ coming across list serves and R help sites is the question:

“How do I re-arrange/re-order (plotting geom/aesthetic such as bar/labels) in a (insert plot type here) using(insert graphics system here) in R?”
.

Don’t believe me? google “reorder factor r plot” and see how many hits you get. I’d venture to say that in almost all cases when you use the words “plot” and “re-arrange”/”re-order” in a question the answer is…

Reorder your factor levels!!
.

Here’s a quick and dirty R theater demo of how to do this:

 library(ggplot2)
ggplot(data=mtcars, aes(y=as.factor(carb), x=mpg, colour=hp)) +
    geom_point()

# Rearrange_Guy: But I want 2 to come first and 8 last
# Helpful_Gal: OK use rev with levels 

mtcars$carb2 <- factor(mtcars$carb, levels=rev(levels(factor(mtcars$carb))))

ggplot(data=mtcars, aes(y=carb2, x=mpg, colour=hp)) +
    geom_point()

# Rearrange_Guy: Well I just want to specify the order
# Helpful_Gal: OK type it in by hand then

mtcars$carb2 <- factor(mtcars$carb, levels=c("1", "2", "3", "6", "8", "4"))
ggplot(data=mtcars, aes(y=carb2, x=mpg, colour=hp)) +
    geom_point()

# Rearrange_Guy: What about faceting?  I bet it doesn't work for that.
# Helpful_Gal: Um yes it does.

ggplot(data=mtcars, aes(y=carb2, x=mpg, colour=hp)) +
    geom_point() + facet_grid(cyl~.)

# Rearrange_Guy: OK Helpful_Gal I want it to go 6, 4, and then 8
# Helpful_Gal: OK

mtcars$cyl2 <- factor(mtcars$cyl, levels=c("6", "4", "8"))
ggplot(data=mtcars, aes(y=carb2, x=mpg, colour=hp)) +
    geom_point() + facet_grid(cyl2~.)

# Rearrange_Guy: Why do you keep making new variables?
# Helpful_Gal: It's probably not the best idea to overwrite variables just for the sake of plotting
# Rearrange_Guy: Thank you for showing me the way of re-ordering and re-arranging.
# Helpful_Gal: You welcome.

So if you catch yourself using “re-arrange”/”re-order” and “plot” in a question think…

factor & levels

To leave a comment for the author, please follow the link and comment on his blog: TRinker's R Blog » R.

R-bloggers.com offers daily e-mail updates about R news and tutorials on topics such as: visualization (ggplot2, Boxplots, maps, animation), programming (RStudio, Sweave, LaTeX, SQL, Eclipse, git, hadoop, Web Scraping) statistics (regression, PCA, time series, trading) and more...



If you got this far, why not subscribe for updates from the site? Choose your flavor: e-mail, twitter, RSS, or facebook...

Comments are closed.