2016-11-20 25 views
3

我嘗試了幾個小時,但我無法成功。我的數據幀簡單P:R:X軸不必要的字母排序

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軸,以字母順序排序,我只是想保持這個順序,因爲它是和看到一個遞減的圖。所有的

回答

2

首先,矩陣只能容納一個類的數據。因此,您有一個字符串矩陣,您將轉換爲data.frame。因爲默認stringAsFactors = TRUE,你的字符矩陣被轉換爲的factor's,其中你的兩列的級別默認是排序的。按字母順序排列的V1V2的遞增順序。

如果你不希望直接修改數據,從源頭上解決問題 - 在其他的答案中指出,可以altenatively下列方式使用內部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) 

enter image description here

+0

謝謝,這正是我一直在尋找 – mccandar

0
> 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