本文介绍了在 R 中制作 plot_ly 图的子图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数据框,可以通过这种方式创建:

I have a dataframe, which can be created in this way:

x = data.frame(metrics=c("type1", "type1", "type1", "orders", "orders", "orders", "mean","mean","mean"), hr=c(6,7,8,6,7,8,6,7,8), actual=c(14,20,34,56,12,34,56,78,89))

我尝试使用 plot_ly 函数绘制散点图.我为它写了一个函数(我需要它是一个函数):

I tried to draw a scatterplot using plot_ly function. I wrote a function for it (i need it to be a function):

plot <- function(df){


  gp <- df %>%



    plot_ly(
      x = ~ hr,
      y = ~ actual,

      group = ~ metrics,
      hoverinfo = "text",
      hovertemplate = paste(
        "<b>%{text}</b><br>",
        "%{xaxis.title.text}: %{x:+.1f}<br>",
        "%{yaxis.title.text}: %{y:+.1f}<br>",
        "<extra></extra>"
      ),
      type = "scatter",
      mode = "markers",
      marker = list(
        size = 18,
        color = "white",
        line = list(color = "black",
                  width = 1.5)
    ),
      width = 680,
      height = 420

)

  gp
}

我得到这个情节:

如您所见,所有三个指标都是一个图.我如何使用子图将它们每个放在单独的图形上?

As you see all three metrics are one one plot. How could i put each of them on separate graph using subplot?

推荐答案

使用 subplot 您必须为每个图形创建一个单独的绘图对象.我们可以使用循环来做到这一点:

Using subplot you'll have to create a separate plotly object for each graph. We can use a loop to do so:

library(plotly)

x = data.frame(
  metrics = rep(c("type1", "orders", "mean"), each = 3),
  hr = c(6, 7, 8, 6, 7, 8, 6, 7, 8),
  actual = c(14, 20, 34, 56, 12, 34, 56, 78, 89)
)


plot <- function(df) {
  subplotList <- list()
  for(metric in unique(df$metrics)){
    subplotList[[metric]] <- df[df$metrics == metric,] %>%
      plot_ly(
        x = ~ hr,
        y = ~ actual,
        name = metric,
        hoverinfo = "text",
        hovertemplate = paste(
          "<b>%{text}</b><br>",
          "%{xaxis.title.text}: %{x:+.1f}<br>",
          "%{yaxis.title.text}: %{y:+.1f}<br>",
          "<extra></extra>"
        ),
        type = "scatter",
        mode = "markers",
        marker = list(
          size = 18,
          color = "white",
          line = list(color = "black",
                      width = 1.5)
        ),
        width = 680,
        height = 420
      )
  }
  subplot(subplotList, nrows = length(subplotList), margin = 0.1)
}

plot(x)

这篇关于在 R 中制作 plot_ly 图的子图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

06-13 06:57