在R中使用Plotly的子图

问题描述 投票:0回答:1

我正在尝试使用Plotly中的subplot函数创建图。我正在按照here中描述的示例进行操作。我到目前为止编写的代码:

test_plot <- plot_ly(testData, x = ~timestamp, y = ~reading, 
                     color = ~vessel, colors = "Dark2",
                     yaxis = ~paste0("y", id))
test_plot <- test_plot %>% add_lines()
test_plot <- test_plot %>% subplot(nrows = 6, shareX = TRUE)

但出现以下错误:

Error Traceback

这是我的数据:

testData <- structure(list(timestamp = c("2019-01-02 09:00:00", "2019-01-02 09:00:00", 
"2019-01-02 09:00:00", "2019-01-03 09:00:00", "2019-01-02 09:00:00", 
"2019-01-02 09:00:00", "2019-01-03 09:00:00", "2019-01-02 09:00:00"
), vessel = c("ac_dif_1", "ac_dif_2", "post_ac_1", "post_ac_1", 
"post_ac_2", "pre_ac_1", "pre_ac_1", "pre_ac_2"), reading = c(-4L, 
2L, 58L, 60L, 50L, 54L, 56L, 52L), id = c(1L, 2L, 3L, 3L, 4L, 
5L, 5L, 6L)), class = "data.frame", row.names = c(NA, -8L))

我完全不知道为什么会收到此错误。我可以从Plotly网站复制并粘贴示例,它可以正常工作,但是由于某些原因,当我使用数据时,它会失败。

[另外,我尝试使用as.Date()将时间戳转换为Date类,并将小标题转换为data.frame,以使其与示例中描述的内容匹配,但这似乎不是导致问题的原因。同样,当我跳过子图线时,它会创建一个包含多条线的单个图。

r plotly r-plotly
1个回答
0
投票

只需在绘制之前按ID对数据进行排序。这可能不会导致错误(因此也许您应该在github上提出问题),但是...请尝试:

testData <- read.table(text = "timestamp    vessel    reading  id  
 '2019-01-02 09:00:00'  pre_ac_1   54       5
 '2019-01-02 09:00:00'  post_ac_1  58       3
 '2019-01-02 09:00:00'  ac_dif_1   -4       1
 '2019-01-02 09:00:00'  pre_ac_2   52       6
 '2019-01-02 09:00:00'  post_ac_2  50       4
 '2019-01-02 09:00:00'  ac_dif_2   2        2
 '2019-01-03 09:00:00'  pre_ac_1   56       5
 '2019-01-03 09:00:00'  post_ac_1  60       3", header = TRUE)

# Sort by id
testData <- dplyr::arrange(testData, id)

library(plotly)

test_plot <- plot_ly(testData, x = ~timestamp, y = ~reading,
                     color = ~vessel, colors = "Dark2",
                     yaxis = ~paste0("y", id))
test_plot <- test_plot %>% 
  add_lines %>%
  add_markers()

test_plot <- test_plot %>% 
  subplot(nrows = 6, shareX = TRUE)

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.