0

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

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
}

I get this plot: enter image description here

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

ismirsehregal
  • 30,045
  • 5
  • 31
  • 78
french_fries
  • 1,149
  • 6
  • 22

1 Answers1

1

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)

result

ismirsehregal
  • 30,045
  • 5
  • 31
  • 78
  • thanks, i made a little update which i forgot to write in this question. here it is: https://stackoverflow.com/questions/63521896/put-several-scatterplots-on-each-graph-of-subplots . could you please look at it? – french_fries Aug 21 '20 at 11:19