ggplot x-axis limits order using factors

Hello,
I need to plot values using as x-axis text.
The data is well structured, but when I plot, the x-axis is order alphabetically and not in the order associated with the x-axis variable. I tried with :

myplot+scale_x_discrete(name="",limits=mydata$xaxis)

But I didn't get the results I needed it.
Can you guide me, please?

You can reorder the levels of the xaxis factor with the factor() function.

library(ggplot2)
DF <- data.frame(fruit = c("apple", "pear", "cherry"), Value = 1:3)
ggplot(DF, aes(fruit, Value)) + geom_point()

DF$fruit <- factor(DF$fruit, levels = c("apple", "pear", "cherry"))
ggplot(DF, aes(fruit, Value)) + geom_point()

Created on 2019-12-11 by the reprex package (v0.2.1)

To complement FJCC's answer, if your variable is already in order, you can use forcats::fct_inorder() to preserve that order, see this example:

library(ggplot2)
library(forcats)

DF <- data.frame(fruit = c("apple", "pear", "cherry"),
                 Value = 1:3)

ggplot(DF, aes(fct_inorder(fruit), Value)) +
    geom_point()

Thanks for your answers. The x-axis variable is similar to a date, something like:

jan - mar 2018
feb - apr 2018
mar -may 2018
apr - jun 2018
...

So, when I plot the x-axis (xdates is the variable), I get listed apr - mar 2018 ( and all remaining years) as the first values. I think I'm generating the factors in the wrong way.

mydata$xdates=as.factor(mydata$xdates)
mydata$xdates=factor(mydata$xdates, levels=mydata$xdates)

The code above is how I create the factors. I'm almost sure It's wrong the way I deal with them.

Does this not work for you?

library(ggplot2)
library(forcats)

mydata <- data.frame(dates = c("jan - mar 2018",
                               "feb - apr 2018",
                               "mar - may 2018",
                               "apr - jun 2018"),
                     Value = 1:4)

ggplot(mydata, aes(fct_inorder(dates), Value)) +
    geom_point() +
    theme(axis.text.x = element_text(angle=45, hjust=1, vjust=1))

If you need more specific help, please provide a proper REPRoducible EXample (reprex) illustrating your issue.

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.