1

My dataframe column for the x-axis values is in the correct decreasing order that I want it, but the ggplot x-axis is rearranging the values according to alphabetical order. Basically, my x-axis variable contains a "Baseline" value, a range of treatment days "TD1, TD2, ..." values that are a different quantity for each subject, and a "Post" value.

Currently, ggplot reorders this alphabetically as 'Baseline, Post, TDx...', when clearly I need it to just follow the order of the dataframe.

How do I solve this? Can I do it in ggplot syntax, or is there a way to set the order of the variable before I pass the dataframe to ggplot? I cannot seem to find an answer that works.

Thanks in advance!

BDizzle
  • 21
  • 3
  • 1
    Any time I see questions about `ggplot2` and *"order facets"*, almost every answer comes down to `factor`. – r2evans Nov 20 '19 at 20:29

2 Answers2

1

Have you tried ordering the factor that you are plotting on the x-axis before you plot the graph?

e.g. x_axis$conditions <- factor(x_axis$conditions, levels = c("Baseline", "TD1", "TD2"))

There are other answers on a similar question here: Change the order of a discrete x scale

Alicia
  • 57
  • 1
  • 9
0

If you want to order in decreasing order, something like this should work:

p1 <- ggplot(data, aes(x=reorder(foo, -bar), y=bar))) +
    geom_bar(stat='identity')

If you need further clarification, please post a reproducible example. You can manually set the order by changing the levels of the factor, also.

Kris
  • 420
  • 2
  • 11