-1

I am representing a line chart where the X axis is formed by a qualitative variable, which originally is not alphabetically sorted.

When doing the ggplot chart, it automatically orders the X axis alphabetically.

How can I stop ggplot from doing this and keeping the original order?

antecessor
  • 2,688
  • 6
  • 29
  • 61
  • 2
    Possible duplicate of https://stackoverflow.com/questions/34137882/ordered-dataframe-not-same-order-when-ggplotting, https://stackoverflow.com/questions/8713462/ggplot2-change-order-of-display-of-a-factor-variable-on-an-axis, https://stackoverflow.com/questions/3253641/change-the-order-of-a-discrete-x-scale – r2evans May 14 '18 at 16:06
  • Possible duplicate of [How do you specifically order ggplot2 x axis instead of alphabetical order?](https://stackoverflow.com/questions/12774210/how-do-you-specifically-order-ggplot2-x-axis-instead-of-alphabetical-order) – GordonShumway May 14 '18 at 16:33

1 Answers1

1

Each column with qualitative data in an R dataframe has a "levels" attribute. This is a list of unique values in the column and it is what ggplot uses to determine the order of how things appear in your plots. By default, ggplot will order things alphabetically.

In order to override the default behavior, you need to override the "levels" attribute for the column you're interested in applying some custom order to. Here is some example code on how you may achieve that:

df$MAKE = factor(df$MAKE, levels = c("Honda", "Chevy", "Toyota"))

The factor() method will convert the column to a factor (in case it isn't already) and you can set the levels attribute in there as well.

Run a line of code similar to the above prior to running the ggplot() method and you should find that your ggplot output will order the values in this column in the way you dictated.

LetEpsilonBeLessThanZero
  • 2,395
  • 2
  • 12
  • 22