2017-02-23 60 views
0

我試圖用[R plotly繪製的是具有以下特點的圖表:Plotly - 劇情2 y軸的時間序列

  1. Date對象爲X變量
  2. 2線圖中的一個圖表用2 Y軸:一個在左邊,另一個在右邊

    Date    Amount1   Amount2 
    2/1/2017   19251130  21698.94 
    2/2/2017   26429396  10687.37 
    2/5/2017   669252   0.00 
    2/6/2017   25944054  11885.10 
    2/7/2017   27895562  14570.39 
    2/8/2017   20842279  20080.56 
    2/9/2017   25485527   9570.51 
    2/10/2017   17008478  14847.49 
    2/11/2017   172562   0.00 
    2/12/2017   379397   900.00 
    2/13/2017   25362794  18390.80 
    2/14/2017   26740881  11490.94 
    2/15/2017   20539413  22358.26 
    2/16/2017   22589808  12450.45 
    2/17/2017   18290862   3023.45 
    2/19/2017   1047087   775.00 
    2/20/2017   4159070   4100.00 
    2/21/2017   28488401  22750.35 
    

和我使用的代碼是:

 ay <- list(
    #tickfont = list(color = "red"), 
    overlaying = "y", 
    side = "right" 
) 

    p <- plot_ly() %>% 
    add_lines(x = df$Date, y = df$Amount1, name = "Amount1",type = "scatter", mode = "lines") %>% 
    add_lines(x = df$Date, y = df$Amount2, name = "Amount2", yaxis = "y2",type = "scatter", mode = "lines") %>% 
    layout(
     title = "Chart Summary", yaxis2 = ay, 
     xaxis = list(title="Date") 
    ) 

Chart

輸出圖表看起來不錯,但在X軸上的日期間隔面色不善。我想知道這是什麼解決方案,如果我想使用上面的數據在一張圖表中創建2個直方圖,那麼最佳方式是什麼?

謝謝你的幫忙!

回答

0

是你的Date專欄a stringdate

如果它是string,請將其轉換爲date並讓Plotly處理它。

df$Date <- as.Date(df$Date , "%m/%d/%Y") 

Autofix 的完整代碼

library('plotly') 

txt <- "Date Amount1 Amount2 
2/1/2017 19251130 21698.94 
2/2/2017 26429396 10687.37 
2/5/2017 669252 0 
2/6/2017 25944054 11885.1 
2/7/2017 27895562 14570.39 
2/8/2017 20842279 20080.56 
2/9/2017 25485527 9570.51 
2/10/2017 17008478 14847.49 
2/11/2017 172562 0 
2/12/2017 379397 900 
2/13/2017 25362794 18390.8 
2/14/2017 26740881 11490.94 
2/15/2017 20539413 22358.26 
2/16/2017 22589808 12450.45 
2/17/2017 18290862 3023.45 
2/19/2017 1047087 775 
2/20/2017 4159070 4100 
2/21/2017 28488401 22750.35" 
df$Date <- as.Date(df$Date , "%m/%d/%Y") 
ay <- list(
    #tickfont = list(color = "red"), 
    overlaying = "y", 
    side = "right" 
) 

p <- plot_ly() %>% 
    add_lines(x = df$Date, y = df$Amount1, name = "Amount1",type = "scatter", mode = "lines") %>% 
    add_lines(x = df$Date, y = df$Amount2, name = "Amount2", yaxis = "y2",type = "scatter", mode = "lines") %>% 
    layout(
    title = "Chart Summary", yaxis2 = ay, 
    xaxis = list(title="Date", ticks=df$Date) 
) 
p 
+0

謝謝!這樣可行。我想我錯過了,因此x軸上的刻度顯示不正確。 –