각 서브 플롯 그래프에 여러 산점도를 배치합니다.

Aug 21 2020

이 코드로 만들 수있는 데이터 프레임이 있습니다.

x = data.frame(metrics=c("type1", "type1", "type1","type1", "type1", "type1", "orders", "orders", "orders","orders", "orders", "orders", "mean","mean","mean","mean","mean","mean"), hr=c(6,7,8,6,7,8,6,7,8,6,7,8,6,7,8,6,7,8), actual=c(14,20,34,22,24,27,56,12,34,11,15,45,56,78,89,111,123,156), time=c("today", "yesterday", "today", "yesterday", "today", "yesterday"))

plot_ly 함수를 사용하여이 데이터를 시각화하고 싶습니다. "metrics"열의 각 값 유형에 대해 세 개의 하위 그림을 만들고 싶습니다. 또한 각 서브 플롯에는 "시간"열 (오늘, 어제)의 각 값 유형에 대해 두 개의 산점도가 있어야합니다.

"시간"열의 각 값 유형에 대해 두 개의 산점도를 다른 색상으로 만드는 것을 제외하고는 모두 수행했습니다.

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)

이 그래프를 얻습니다.

각 서브 플롯에서이 두 산점도를 다른 색상으로 만드는 방법은 무엇입니까?

답변

ismirsehregal Aug 21 2020 at 11:33

다음은 당신이 추구하는 것입니다.

library(plotly)

x = data.frame(metrics=c("type1", "type1", "type1","type1", "type1", "type1", "orders", "orders", "orders","orders", "orders", "orders", "mean","mean","mean","mean","mean","mean"), hr=c(6,7,8,6,7,8,6,7,8,6,7,8,6,7,8,6,7,8), actual=c(14,20,34,22,24,27,56,12,34,11,15,45,56,78,89,111,123,156), time=c("today", "yesterday", "today", "yesterday", "today", "yesterday"))


plot <- function(df) {
  subplotList <- list()
  for(metric in unique(df$metrics)){ subplotList[[metric]] <- df[df$metrics == metric,] %>%
      plot_ly(
        x = ~ hr,
        y = ~ actual,
        name = ~ paste(metrics, " - ", time),
        colors = ~ time,
        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(width = 1.5)
        ),
        width = 680,
        height = 420
      )
  }
  subplot(subplotList, nrows = length(subplotList), margin = 0.1)
}

plot(x)

미래 독자를위한 이전 질문 .