Keep same order as in data files when using ggplot

后端 未结 1 2003
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-16 03:17

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:

1条回答
  •  自闭症患者
    2020-12-16 03:58

    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.

    0 讨论(0)
提交回复
热议问题