在 R 中使用 Plotly 的子图(已修复错误)

Subplots using Plotly in R (bug fixed)

如何在 R 中使用 Plotly 创建子图网格?

官方网站有这个nice Python example:

python 代码有选项 rows=2cols=2,但在 R 中 subplot 函数只有参数 nrows,没有 ncols.

我在 R 中试过这个例子,但是 nrows 没有像预期的那样工作:

# Basic subplot
library(plotly)
p <- plot_ly(economics, x = date, y = uempmed)
subplot(p,p,p,p,
  margin = 0.05,
  nrows=2
) %>% layout(showlegend = FALSE)

它们排成一行而不是网格。查看结果:

这里是R suplots page for reference. Unfortunately, use ggplotly is not a option for me, like this

更新

这是一个错误。 Plotly团队速度很快,3天就搞定了(check here)! Github 版本已更新。干得好!

这似乎是 subplot() 为两个地块生成 y-axis 域的方式中的真正错误。实际上,它们重叠,如果您执行

可以很容易地看到
p <- plot_ly(economics, x = date, y = uempmed)
q <- plot_ly(economics, x = date, y = unemploy)


subplot(p,q, nrows = 2)

这将产生以下情节:

如果您仔细观察 y-axis,您会发现它们重叠。这暗示 subplot() 定义子图 y-axes 域的方式存在问题。

如果我们手动更正 y-axes 的域规范(在 plotly documentation 之后),我们可以解决问题:

subplot(p,q, nrows = 2) %>% layout(yaxis = list(domain = c(0, 0.48)), 
                                   yaxis2 = list(domain = c(0.52, 1)))

这会产生:

现在,如果您想重现类似于 Python 示例的 4x4 子图矩阵,您可能需要以类似的方式手动调整 x-axis 域。

由于这是一个错误,而我的解决方案只是一种解决方法,因此我建议您在 GitHub.

上使用 plotly 提交问题

基于this

p <- economics %>%
  tidyr::gather(variable, value, -date) %>%
  transform(id = as.integer(factor(variable))) %>%
  plot_ly(x = ~date, y = ~value, color = ~variable, colors = "Dark2",
          yaxis = ~paste0("y", id)) %>%
  add_lines() %>%
  subplot(nrows = 5, shareX = TRUE)