McCandar McCandar - 2 months ago 46
R Question in R: Unwanted alphabetical sorting of x-axis

I tried for hours, but I could not succeed. My data frame is simply

df <-"g","d","a","b","z",5,4,3,2,1),5,2))

p <- plot_ly(data = df,x = ~V1,y = ~V2,type = "scatter",mode = "lines+markers") %>%
layout(title = "my title")

So, this give me


But I don't want x axis to be sorted alphabetically, I just want to keep the order as it is and see a decreasing graph.


First of all, a matrix can only hold data of one class. Hence you have a matrix of strings that you are converting to a data.frame. Because by default stringAsFactors = TRUE, your character matrix is converted to a data.frame of factor's, where the levels of your two columns are by default sorted. Alphabetically for V1 and in increasing order for V2.

If you don't wish to modify the data directly to remedy the issue at the source - as pointed out in the other answers, you can altenatively use plotly's categoryorder = argument inside layout() in the following way:

xform <- list(categoryorder = "array",
              categoryarray = df$V1)

plot_ly(data = df,
        x = ~V1,
        y = ~V2,
        type = "scatter",
        mode = "lines+markers") %>%
        layout(title = "my title",
               xaxis = xform)

enter image description here