繁体   English   中英

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

[英]Plot.ly in R: Unwanted alphabetical sorting of x-axis

我试了几个小时,但我没能成功。 我的数据框很简单

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轴按字母顺序排序,我只是想按顺序保持顺序并看到减少的图形。

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

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

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM