Faça subtramas do gráfico plot_ly em R
Aug 21 2020
Tenho um dataframe, que pode ser criado desta forma:
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))
Tentei desenhar um gráfico de dispersão usando a função plot_ly. Escrevi uma função para ele (preciso que seja uma função):
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
}
Eu entendo este enredo:
Como você pode ver, todas as três métricas são um gráfico. Como eu poderia colocar cada um deles em um gráfico separado usando subplot?
Respostas
1 ismirsehregal Aug 21 2020 at 16:00
Usando subplotvocê terá que criar um objeto plotly separado para cada gráfico. Podemos usar um loop para fazer isso:
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)
O que significa um erro “Não é possível encontrar o símbolo” ou “Não é possível resolver o símbolo”?
Christopher Nolan uma vez se arrependeu de ter lido o 'roteiro de Pulp Fiction' de Quentin Tarantino