I have this dataframe in R. I’d like to transfer it to plot_ly without using ggplot2 at all.
dt <-
data.frame(
date = c("2020-05", "2020-05", "2020-05", "2020-05", "2020-06", "2020-06", "2020-06", "2020-06"),
type = c("a", "a", "b", "b", "a", "a", "b", "b"),
sub_type = c("aa", "bb", "aa", "bb", "aa", "bb", "aa", "bb"),
value = c(seq(1:8))
)
In ggplot I can have two legends – one for type, one for sub_type – graph is nice and easy to read.
ggplot(dt, aes(x = date, y = value, group = interaction(type,sub_type),
color = type, linetype = sub_type)) +
geom_point()+
geom_line()
I spent hours to achieve similiar output in plot_ly, this is what I have
p <- plot_ly()
combinations <- unique(dt[c("type", "sub_type")])
for(i in seq_len(nrow(combinations))) {
subset_dt <- dt[dt$type == combinations$type[i] & dt$sub_type == combinations$sub_type[i], ]
dash_type <- ifelse(combinations$sub_type[i] == "aa", "solid", "dot")
p <- add_trace(p, data = subset_dt, x = ~date, y = ~value, type = 'scatter', mode = 'lines+markers',
line = list(dash = dash_type), color = ~type, showlegend = TRUE)
}
p
I don’t like it for several reasons: legend is not easy to read – there are two variants for a value, two variants for b value. Additionally I had specify linetype via ifelse function. I highly prefer to let plot_ly assign various linetypes automatically.