Rlot中的Plot.ly:x轴的不需要的字母排序 [英] Plot.ly in R: Unwanted alphabetical sorting of x-axis

查看:779
本文介绍了Rlot中的Plot.ly:x轴的不需要的字母排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

所以,这给了我

但我不想要x轴要按字母顺序排序,我只想按顺序保留订单并查看递减的图表。

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.

推荐答案

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

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.

如果您不希望直接修改数据以在源头解决问题 - 正如其他答案中所指出的那样,您可以使用 plotly categoryorder = layout()中的参数,方式如下:

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)

这篇关于Rlot中的Plot.ly:x轴的不需要的字母排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆