Search code examples
rggplot2r-factor

R ggplot and factor(ordered): Why does my box plot gets ordered?


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.


Solution

  • 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")