Créer des sous-tracés du graphe plot_ly dans R
Aug 21 2020
J'ai un dataframe, qui peut être créé de cette manière:
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))
J'ai essayé de dessiner un nuage de points en utilisant la fonction plot_ly. J'ai écrit une fonction pour cela (j'ai besoin que ce soit une fonction):
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
}
Je reçois ce complot:
Comme vous le voyez, les trois métriques ne forment qu'un seul graphique. Comment puis-je mettre chacun d'eux sur un graphique séparé en utilisant un sous-graphique?
Réponses
1 ismirsehregal Aug 21 2020 at 16:00
En utilisant, subplotvous devrez créer un objet de tracé distinct pour chaque graphique. Nous pouvons utiliser une boucle pour ce faire:
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)