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
}
私はこのプロットを取得します:

ご覧のとおり、3つのメトリックはすべて1つのプロットです。サブプロットを使用して、それぞれを別々のグラフに配置するにはどうすればよいですか?
回答
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)
