Site icon R-bloggers

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

[This article was first published on TRinker's R Blog » R, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

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 their blog: TRinker's R Blog » R.

R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.