简体   繁体   English

在 R 中使用 Plotly 的子图

[英]Subplots Using Plotly in R

I am trying to create a plot using the subplot function in Plotly. I am following the examples as described here .我正在尝试使用 883276440288 中的子图 function 创建一个 plot。我按照此处描述的示例进行操作。 The code I have written so far:到目前为止我写的代码:

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)

But I get the following error:但我收到以下错误:

错误回溯

Here's my data:这是我的数据:

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("vessel_dif_1", "vessel_dif_2", "post_vessel_1", "post_vessel_1", 
"post_vessel_2", "pre_vessel_1", "pre_vessel_1", "pre_vessel_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))

I'm completely lost on why I'm getting this error.我完全不知道为什么会收到此错误。 I can copy and paste the example from the Plotly website and it works fine, but for some reason when I use my data it fails.我可以从 Plotly 网站复制并粘贴示例,它工作正常,但由于某种原因,当我使用我的数据时它失败了。

Additionally, I've tried turning the timestamp into a Date class using as.Date() and turning the tibble into a data.frame so it matches what is described in the example but that doesn't seem to be what's causing the issue.此外,我尝试使用as.Date()将时间戳转换为 Date class 并将小标题转换为 data.frame 以使其与示例中描述的相匹配,但这似乎不是导致问题的原因。 Also when I skip the subplot line, it creates a single plot with multiple lines on it.此外,当我跳过子图行时,它会创建一个包含多行的 plot。

Simply sort your data by id before plotting.在绘图之前,只需按 id 对数据进行排序。 This should probably not result in an error (so perhaps you should raise an issue on github ) but... Try this:这应该不会导致错误(所以也许你应该在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)

在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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