Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Keep same order as in data files when using ggplot

Tags:

r

ggplot2

I am using the attached data below to produce boxplot. Datalink https://www.dropbox.com/s/dt1nxnkhq90nea4/GTAP_Sims.csv

So far, I have this code that I am using:

# Distribution of EV for all regions under the BASE scenario

evBASE.f <- subset(ccwelfrsts, tradlib =="BASE")
p <- ggplot(data = evBASE.f, aes(factor(region), ev))
p + geom_boxplot() + 
    theme(axis.text.x = element_text(colour = 'black', angle = 90, size = 16)) +
    theme(axis.text.y = element_text(colour = 'black', size = 16))

it reproduces a plot that looks: Plot file:///C:/Users/iouraich/Documents/ggplot_Results.htm

What I am looking for here is to have the x-axis in the plot match the order of the header "region" in the csv file.

Is there any option within ggplot that allows to control for that?

Thanks a lot

like image 962
iouraich Avatar asked Jan 18 '13 15:01

iouraich


1 Answers

Basically you just need region <- factor(region,levels=unique(region)) to specify the levels in the order in which they appear in the data.

A full solution based on the data you provided:

ccwelfrsts <- read.csv("GTAP_Sims.csv")
## unmangle data
ccwelfrsts[5:8] <- sapply(ccwelfrsts[5:8],as.numeric)
evBASE.f <- droplevels(subset(ccwelfrsts, tradlib =="BASE"))
## reorder region levels
evBASE.f <- transform(evBASE.f,region=factor(region,levels=unique(region)))
library(ggplot2)
theme_set(theme_bw())
p <- ggplot(data = evBASE.f, aes(region, ev))
p + geom_boxplot() + 
    theme(axis.text.x = element_text(colour = 'black', angle = 90, size = 16)) +
    theme(axis.text.y = element_text(colour = 'black', size = 16))+
    xlab("")

You might consider switching the orientation of the graph (via coord_flip or by explicitly switching x and y axis mappings) to make the labels easier to read, although the layout with the numerical response on the y axis is more familiar to most viewers.

like image 83
Ben Bolker Avatar answered Nov 05 '22 13:11

Ben Bolker