Preventing alphabetical sorting in Rstudio

I have data (shown below) I am trying to plot as it is in my excel spreadsheet, but rstudio is automatically sorting it alphabetically which i do not want.
The data:


As you can see the x-axis is sorted alphabetically and so M10 is placed 2nd instead of 10th on the axis. This wouldnt be an issue if it was plotted directly from the spreadsheet data.

The reason this is happening is that it is reading the M1, M10, M2 as character values rather than factor variables. Check out the functions as.factor() or as_factor() and you should be able to order them as you please.

You can easily keep current order while converting to factor with fct_inorder(), see this example:


sample_df <- data.frame(
  stringsAsFactors = FALSE,
     Nad_Frequency = c("W1","W2","W3","W4","W5",
        Nad_Totals = c(550.6233863,553.5625904,

sample_df %>% 
    mutate(Nad_Frequency = fct_inorder(Nad_Frequency)) %>% 
    ggplot(aes(x = Nad_Frequency, y = Nad_Totals)) +

Created on 2021-08-23 by the reprex package (v2.0.1)

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

If you have a query related to it or one of the replies, start a new topic and refer back with a link.