admin管理员组

文章数量:1360337

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.

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.

Share Improve this question edited Nov 20, 2016 at 6:57 mplungjan 178k28 gold badges182 silver badges240 bronze badges asked Nov 20, 2016 at 6:54 mccandarmccandar 7888 silver badges16 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 7

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)

> 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

本文标签: javascriptPlotly in R Unwanted alphabetical sorting of xaxisStack Overflow