在绘制geom_bar()时避免ggplot对x轴进行sorting

我有我想用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 

我想要做的是做一个条形图并保持条的顺序,(即从SC_LTSL_BM ...B_GC_Sp )。 但是ggplot geom_bar的默认行为是对它们进行sorting。 我怎样才能避免呢?

  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() 

目前的数字如下所示: 在这里输入图像说明

你需要告诉ggplot你已经有一个订购的因素,所以它不会自动为你订购。

 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") 

在这里输入图像说明

您也可以按照此处所述重新排列相应的因子

 x$name <- factor(x$name, levels = x$name[order(x$val)]) 

这是一种不会修改原始数据的方法,但使用scale_x_discrete。 来自?scale_x_discrete“使用限制来调整显示的级别(以及按什么顺序)”例如:

 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) # plot library(ggplot2) ggplot(dat,aes(x=V1,y=V2))+ geom_bar(stat="identity")+ scale_x_discrete(limits=dat$V1) 

在这里输入图像说明