Wrong X axis order when using geom_bar () with X character object
Considering the bar chart represented 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')
It's weird what 0~0.1
is at the end of the X-axis, even if it 0~0.1
is on the first line data
.
However, when I change '0~0.1'
to '0.0~0.1'
, I got the plot I wanted.
Why is this happening? And is there any other way to make the order of the x-axis match the order of the initial data?
source to share
You create a variable x
as you factor
make sure the levels are properly ordered in it. In this example, you have created a variable x
that has levels in the correct order. If not, you must assign a properly ordered vector to the argument levels
in x <- factor( x, levels = properly_ordered_vector )
.
Also, make sure that there are no duplicate values ββin the correct_ordered_vector while assigning the levels to the factor variable. Once you set it up like this, ggplot takes care of the order of the xaxis labels based on the order of the 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')
source to share
Didn't work for me. Best solution for me, analog as described by Aaron . The variable x must be a " factor " (whatever that means ...), so it is treated discretely, and x-data is treated as levels . Not sure why to specify it 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
source to share