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 badges2 Answers
Reset to default 7First 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
版权声明:本文标题:javascript - Plot.ly in R: Unwanted alphabetical sorting of x-axis - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1743891234a2556955.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论