1

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

2
  • Could you provide a sample data, if you can? Commented Oct 28, 2014 at 6:50
  • Edited my question with sample data and plot. Commented Oct 28, 2014 at 6:56

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

2 Comments

Still puts NA in the middle though. I want NA at the start, SA next and EU last.
in the first line of code in levels argument change the order like levels = c("NA","SA","EU") you can play with the order

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.