Avoid ggplot sorting the x-axis while plotting geom_bar()

ggplot2, r

Solution

You need to tell ggplot that you've got an ordered factor already, so it doesn't automatically order it for you.

dat <- read.table(text=
"SC_LTSL_BM    16.8275
SC_STSL_BM    17.3914
proB_FrBC_FL   122.1580
preB_FrD_FL    18.5051
B_Fo_Sp    14.4693
B_GC_Sp    15.4986", header = FALSE, stringsAsFactors = FALSE)

# make V1 an ordered factor
dat$V1 <- factor(dat$V1, levels = dat$V1)

# plot
library(ggplot2)
ggplot(dat,aes(x=V1,y=V2))+geom_bar(stat="identity")

Problem

I have the following data which I want to plot with ggplot: ``` SC_LTSL_BM 16.8275 SC_STSL_BM 17.3914 proB_FrBC_FL 122.1580 preB_FrD_FL 18.5051 B_Fo_Sp 14.4693 B_GC_Sp 15.4986 ``` What I want to do is to make a bar plot and maintain the order of the bar, (i.e. starting with `SC_LTSL_BM ...B_GC_Sp`). But the default behavior of ggplot geom_bar is to sort them. How can I avoid that? ``` library(ggplot2) dat <- read.table("http://dpaste.com/1469904/plain/") pdf("~/Desktop/test.pdf") ggplot(dat,aes(x=V1,y=V2))+geom_bar() dev.off() ``` The current figure looks like this:

Original source