サブプロットの各グラフにいくつかの散布図を配置します

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関数を使用してこのデータを視覚化したい。「メトリック」列の値のタイプごとに3つのサブプロットを作成したいと思います。また、各サブプロットでは、列「時間」(今日、昨日)の値のタイプごとに2つの散布図が必要です。

列「時間」の値のタイプごとに2つの散布図を異なる色にすることを除いて、すべてを実行しました。

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)

私はこのグラフを取得します:

各サブプロットのこれら2つの散布図を異なる色にする方法は?

回答

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)

将来の読者のための前の質問。