Goutham
Goutham

Reputation: 2859

ggplot sorting a bar graph when reorder is not possible

Say I have a dataframe which has only 2 columns, var and fill (both factors). I create a bar graph from this using

ggplot(df, aes(var, fill=fill)) + geom_bar()

The reason I am doing this is because I need a stacked histogram. The y values which are the counts of various values in var seem to be implicitly calculated by ggplot. All this is perfectly fine.

Now, my problem is the resulting graph is not sorted and I cannot sort this using the usual method of reordering since there is no explicit y value here.

How do I do this?

EDIT : Sample Data and plot (I want the plot to be sorted so I see NA first, SA next and Europe last)

> df = data.frame(var=c("NA","EU","SA","NA","SA","NA"),fill=c("f1","f2","f2","f1","f2","f2"))
> df
  var fill
1  NA   f1
2  EU   f2
3  SA   f2
4  NA   f1
5  SA   f2
6  NA   f2
> ggplot(df, aes(x=var, fill=fill)) + geom_bar()

enter image description here

Upvotes: 1

Views: 553

Answers (1)

Koundy
Koundy

Reputation: 5503

You should create ordered factor to do that. In the levels argument you can change the order as you like. When you write ordered = TRUE it will preserve the order

df$var <- factor(df$var,levels = c("SA","NA","EU"),ordered = TRUE)
ggplot(df, aes(x=var, fill=fill)) + geom_bar()

enter image description here

Upvotes: 1

Related Questions