Search code examples
rplotplotlyr-plotly

Make subplots of plot_ly graph in R


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?


Solution

  • 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