Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
496 views
in Technique[技术] by (71.8m points)

r - Keep same order as in data files when using ggplot

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...