R에서 plot_ly 그래프의 서브 플롯 만들기

Aug 21 2020

이 방법으로 만들 수있는 데이터 프레임이 있습니다.

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 함수를 사용하여 산점도를 그리려고했습니다. 나는 그것을 위해 함수를 썼다 (함수가 필요합니다) :

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
}

이 줄거리를 얻습니다.

보시다시피 세 가지 메트릭은 모두 하나의 플롯입니다. 서브 플롯을 사용하여 각각의 그래프를 개별 그래프에 어떻게 배치 할 수 있습니까?

답변

1 ismirsehregal Aug 21 2020 at 16:00

를 사용 subplot하면 각 그래프에 대해 별도의 플롯 개체를 만들어야합니다. 루프를 사용하여 이렇게 할 수 있습니다.

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)