Rlot中的Plot.ly:x轴的不需要的字母排序

时间:2016-11-20 06:54:43

标签: javascript r rstudio plotly

我试了几个小时,但我没能成功。我的数据框只是

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

所以,这给了我

myplot

但我不希望x轴按字母顺序排序,我只是想按顺序保留顺序并查看减少的图表。

2 个答案:

答案 0 :(得分:2)

首先,矩阵只能保存一个类的数据。因此,您有一个字符串矩阵,您要转换为data.frame。因为默认情况下stringAsFactors = TRUE,您的字符矩阵会转换为data.framefactor,其中两列的级别默认排序。 V1按字母顺序排列V2

如果您不希望直接修改数据以在源头补救问题 - 正如其他答案中所指出的那样,您可以使用plotly {{1}以下列方式在categoryorder =内的参数:

layout()

enter image description here

答案 1 :(得分:0)

> 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