【问题标题】:Subplots Using Plotly in R在 R 中使用 Plotly 绘制子图
【发布时间】:2020-08-27 16:29:37
【问题描述】:

我正在尝试使用 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)

但我收到以下错误:

这是我的数据:

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

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

此外,我尝试使用 as.Date() 将时间戳转换为 Date 类,并将 tibble 转换为 data.frame,使其与示例中描述的内容相匹配,但这似乎不是导致问题的原因.此外,当我跳过子情节线时,它会创建一个带有多条线的情节。

【问题讨论】:

  • 您的代码中的对象activated_carbons_plot 是什么?应该是test_plot
  • 哎呀,你是对的。它应该是 test_plot。进行了更正,但这不是问题

标签: r plotly r-plotly


【解决方案1】:

在绘图之前只需按 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)

【讨论】:

  • 不幸的是,我仍然遇到同样的错误。当我直接粘贴你的代码时它可以工作,但我的数据结构必须有所不同。我似乎无法弄清楚是什么。不过谢谢!
猜你喜欢
  • 2020-12-27
  • 1970-01-01
  • 2021-05-02
  • 2018-10-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-17
  • 2020-05-10
相关资源
最近更新 更多