Keep the same order as in data files when using ggplot

I use the data below to create a boxplot. Data Link https://www.dropbox.com/s/dt1nxnkhq90nea4/GTAP_Sims.csv

So far, I have this code that I use:

# 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 plays a plot that looks like: plot File: /// C: /Users/iouraich/Documents/ggplot_Results.htm

I am looking here for the x axis in the graph to match the order of the "region" header in the csv file.

Is there any parameter in ggplot that allows me to control this?

Thank you so much

+7
source share
1 answer

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

Complete solution based on the data 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 want to switch the orientation of the graph (via coord_flip or by explicitly switching the x and y axis displays) to make labels easier to read, although most viewers are more familiar with the layout with a numerical response on the y axis.

+8
source

All Articles