0

I want to draw a bar plot of this data.frame in the order it is at the moment:

df <- data.frame(y=rnorm(5),row.names=c("C","G","D","A","R"))

Height shall be y, x shall be the row names.

I tried tried the following with no success:

df$labels <- row.names(df)
ggplot(df, aes(x = labels, y = y)) + geom_bar(stat = "identity")
ggplot(df, aes(x = factor(labels, ordered = TRUE), y = y)) + geom_bar(stat = "identity")
df <- within(df, labels.factor <- factor(labels, levels=labels, ordered=T))
ggplot(df, aes(x = labels.factor, y = y)) + geom_bar(stat = "identity")

Fruitless attempt with wrong order

So my question is: Why does my "order" gets ignored? How do I do this correctly? I'm sure that I'm missing something obvious here as it is so basic. Thanks in advance.

Edit: I did a mistake in my R session and oversaw that one proposed solution actually worked. Thanks @jlhoward and user2633645.

Matthew Lundberg
  • 42,009
  • 6
  • 90
  • 112
Andarin
  • 799
  • 1
  • 8
  • 17
  • possible duplicate of [how to change the order of a discrete x scale in ggplot?](http://stackoverflow.com/questions/3253641/how-to-change-the-order-of-a-discrete-x-scale-in-ggplot) – Henrik Mar 07 '14 at 11:36
  • See also examples on the [**help page for `geom_bar`**](http://docs.ggplot2.org/current/geom_bar.html) – Henrik Mar 07 '14 at 11:38
  • Yes, I looked at that; the problem is that they are doing histograms and I wasn't able to broaden their solution given x values. – Andarin Mar 07 '14 at 11:39
  • 1
    Your third option (last two lines of code) works when I try it. This also works: `ggplot(df, aes(x = factor(labels, levels=labels, ordered = TRUE), y = y)) + geom_bar(stat = "identity")` – jlhoward Mar 07 '14 at 11:47
  • I don't know if I should delete this post as I obviously did a mistake, but then you won't get reputation for it. Hence I just let it. – Andarin Mar 07 '14 at 11:55

1 Answers1

1

Try:

df <- data.frame(cbind(x = c("C","G","D","A","R"), y=rnorm(5)), stringsAsFactors = FALSE)
head(df)
df$x <- factor(df$x, levels = c("C","G","D","A","R"))
levels(df$x)
class(df$y)
df$y <- as.numeric(df$y)
ggplot(df, aes(x = x, y = y))  + geom_bar(stat = "identity")
r.bot
  • 5,309
  • 1
  • 34
  • 45