plotly Line Plot in R (Example) | Draw an Interactive Curve Chart | Color, Type & Overlaid Points

preview_player
Показать описание

R code of this video:

VarA = c(15,20,25,18),
VarB = c(22,24,26,28),
VarC = c(5,10,20,40))

df_long <- df_wide %>% tidyr::pivot_longer(cols = c(VarA, VarB,VarC))

library(plotly)

plot_ly(
data = df_wide,
x = ~date,
y = ~VarA,
type = "scatter",
mode = "lines"
)

plot_ly(
data = df_wide,
x = ~date,
y = ~VarA,
name = "VarA",
type = "scatter",
mode = "lines"
) %>%
add_trace(y = ~VarB, name = "VarB")%>%
add_trace(y = ~VarC, name = "VarC")

plot_ly(
data = df_long,
x = ~date,
y = ~value,
color = ~name,
type = "scatter",
mode = "lines"
)

plot_ly(
data = df_long,
x = ~date,
y = ~value,
color = ~name,
type = "scatter",
mode = "lines+markers"
)

plot_ly(
data = df_long,
x = ~date,
y = ~value,
color = ~name,
type = "scatter",
mode = "lines+markers",
line = list(width = 4)
)

plot_ly(
data = df_long,
x = ~date,
y = ~value,
color = ~name,
type = "scatter",
mode = "lines+markers",
line = list(width = 4, dash = "dot")
)

plot_ly(
data = df_wide,
x = ~date,
y = ~VarA,
name = "VarA",
type = "scatter",
mode = "lines",
line = list(width = 2,
dash = "solid",
color = "green")) %>%
add_trace(y = ~VarB, name = "VarB", mode = "lines", line = list(width = 4, dash = "dash", color = "gray"))%>%
add_trace(y = ~VarC, name = "VarC", mode = "lines+markers", line = list(dash = "dot", color = "red"))

plot_ly(
data = df_long,
x = ~date,
y = ~value,
color = ~name,
type = "scatter",
mode = "lines+markers",
line = list(width = 4, dash = "dot")) %>%
layout(hovermode = "x unified")

Follow me on Social Media:

Рекомендации по теме
Комментарии
Автор

Great tutorial, very helpful, simple and to the point! also many thanks for putting the code in the descirption:)

mohsenhs
Автор

Very nice presentation by Kirby as usual. I have a question for him or possibly a request. Since he keeps comparing plotly with ggplot2 (saying here ggplot2 is simpler etc) I would very interested in seeing a presentation were he compares them directly. Finally, could Kirby comment on the ease of plotting in R in general vs. Python. I am a beginner in python but I found the code that generates plots in Python very clumbsy when compared with R.
Thanks to both of you and Happy New Year...

haraldurkarlsson