3

Considering the bar plot prvided by the following code:

y<-rnorm(10)
x<-c('0~0.1','0.1~0.2','0.2~0.3','0.3~0.4','0.4~0.5','0.5~0.6','0.6~0.7','0.7~0.8','0.8~0.9','0.9~1')
data<-data.frame(x,y)
library('ggplot2')
ggplot(data=data,aes(x=x,y=y))+geom_bar(stat="identity",fill='light blue')

The result is like this: enter image description here

It is strange that the 0~0.1 is located at the end of X axis even though the 0~0.1 is at the first row of data.

However, when I change the '0~0.1' into '0.0~0.1', I got the right plot.

Why this happen? And is there any other way to enforece the order of x axis correspond to the initial data order?

YQ.Wang
  • 1,090
  • 1
  • 17
  • 43
  • 1
    ggplot is ordering the data in its alphabetic order. You can see this by running `sort(x)` and looking at the output. To set character data to the order you want, convert it to a factor. In this case, before creating the plot do `data$x = factor(data$x, levels=x)`. This works because the vector `x` is already ordered the way you want. – eipi10 Mar 21 '17 at 06:06
  • Possible duplicate of [Change the order of a discrete x scale](http://stackoverflow.com/questions/3253641/change-the-order-of-a-discrete-x-scale) – lbusett Mar 21 '17 at 08:11

2 Answers2

2

You create x variable as factor and make sure the levels are properly ordered in it. In this example, you created a variable x which has the levels in proper order. If not, you have to assign a properly ordered vector to levels argument in x <- factor( x, levels = properly_ordered_vector ).

Also, make sure there is no duplicate values in the properly_ordered_vector, while assigning levels to a factor variable. Once you set it up like this, then ggplot will take care of order of xaxis labels based on the order of levels.

set.seed(1L)
y<-rnorm(10)
x<- c('0~0.1','0.1~0.2','0.2~0.3','0.3~0.4','0.4~0.5','0.5~0.6','0.6~0.7','0.7~0.8','0.8~0.9','0.9~1')
x <- factor( x, levels = x )
data<-data.frame(x,y)
library('ggplot2')
ggplot(data=data,aes(x=x,y=y))+geom_bar(stat="identity",fill='light blue')

enter image description here

Sathish
  • 12,453
  • 3
  • 41
  • 59
0

Neither worked for me. The best solution for me, analog as described by Aaron. The x- variable should be a "factor" (whatever that means...) so that is treated discrete and the x-data then as levels. Don´t know why to specify twice, but it works. For example:

mbar <- data.frame(klasse=c("<39", "40-60", "60-80", "80-100", ">100"), len=c(375, 57, 7, 0, 0))
p <- ggplot(data=mbar, aes(x=factor(klasse, levels=klasse), y=len)) + geom_bar(stat="identity")
p
Coliban
  • 601
  • 2
  • 9
  • 24