[英]Plot.ly in R: Unwanted alphabetical sorting of x-axis
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. 但是我不希望x轴按字母顺序排序,我只是想按顺序保持顺序并看到减少的图形。
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
. 因此,您有一个字符串矩阵,您将转换为
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. 因为默认情况下
stringAsFactors = TRUE
,您的字符矩阵将转换为factor
的data.frame
,其中默认情况下stringAsFactors = TRUE
两列的级别进行排序。 Alphabetically for V1
and in increasing order for V2
. V1
按字母顺序排列,按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: 如果您不希望直接修改数据以在源代码中解决问题 - 正如其他答案所指出的那样,您可以通过以下方式在
layout()
内部使用plotly
的categoryorder =
参数:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.