Plot.ly in R: Unwanted alphabetical sorting of x-a

2019-05-10 05:51发布

问题:

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

df <- as.data.frame(matrix(c("g","d","a","b","z",5,4,3,2,1),5,2))

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

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.

回答1:

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:

library(plotly)
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)



回答2:

> df <- as.data.frame(matrix(c("g","d","a","b","z",5,4,3,2,1),5,2))
> str(df)
'data.frame':   5 obs. of  2 variables:
$ V1: Factor w/ 5 levels "a","b","d","g",..: 4 3 1 2 5
$ V2: Factor w/ 5 levels "1","2","3","4",..: 5 4 3 2 1
> df$V1
[1] g d a b z
Levels: a b d g z
> df$V1 <- ordered(df$V1, c("g","d","a","b","z"))
> df$V1
[1] g d a b z
Levels: g < d < a < b < z