Plot.ly 在 R 中:不需要的 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
所以,这个给我
但我不希望x轴按字母顺序排序,我只想保持原样并看到一个递减的图表。
> 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
首先,一个矩阵只能容纳一个class的数据。因此,您有一个要转换为 data.frame
的字符串矩阵。因为默认情况下 stringAsFactors = TRUE
,您的字符矩阵会转换为 factor
的 data.frame
,其中两列的级别默认排序。 V1
按字母顺序排列,V2
按升序排列。
如果您不想直接修改数据以从源头上解决问题 - 正如其他答案中指出的那样,您可以选择使用 plotly
中的 categoryorder =
参数layout()
方式如下:
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))
library("plotly")
p <- plot_ly(data = df,x = ~V1,y = ~V2,type = "scatter",mode = "lines+markers") %>%
layout(title = "my title")
p
所以,这个给我
但我不希望x轴按字母顺序排序,我只想保持原样并看到一个递减的图表。
> 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
首先,一个矩阵只能容纳一个class的数据。因此,您有一个要转换为 data.frame
的字符串矩阵。因为默认情况下 stringAsFactors = TRUE
,您的字符矩阵会转换为 factor
的 data.frame
,其中两列的级别默认排序。 V1
按字母顺序排列,V2
按升序排列。
如果您不想直接修改数据以从源头上解决问题 - 正如其他答案中指出的那样,您可以选择使用 plotly
中的 categoryorder =
参数layout()
方式如下:
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)