library(plotly)
# Sample data
x <- 1:10
y1 <- x^2
y2 <- x^3
linetype <- c(rep("solid", 5), rep("dash", 5))
color <- c(rep("blue", 5), rep("red", 5))
# Create the plot
p <- plot_ly(
data = data.frame(x, y1, y2, linetype, color),
type = "scatter",
mode = "lines"
) %>%
# First trace with color and linetype mapping
add_trace(
x = ~x,
y = ~y1,
line = list(dash = ~linetype),
legendgroup = ~linetype, # Group by linetype
linetype = ~linetype,
color = I("black"), # Set a static color so color doesn't create a new legend
showlegend = TRUE # Only show legend for linetype
) %>%
# Second trace for y2 with color and linetype mapping
add_trace(
x = ~x,
y = ~y2,
line = list(dash = ~linetype),
legendgroup = ~linetype,
linetype = ~linetype,
color = I("black"), # Same static color to avoid color legend entries
showlegend = FALSE # Hide color legend
)
# Display the plot
p
CmxpYnJhcnkocGxvdGx5KQoKIyBTYW1wbGUgZGF0YQp4IDwtIDE6MTAKeTEgPC0geF4yCnkyIDwtIHheMwpsaW5ldHlwZSA8LSBjKHJlcCgic29saWQiLCA1KSwgcmVwKCJkYXNoIiwgNSkpCmNvbG9yIDwtIGMocmVwKCJibHVlIiwgNSksIHJlcCgicmVkIiwgNSkpCgojIENyZWF0ZSB0aGUgcGxvdApwIDwtIHBsb3RfbHkoCiAgZGF0YSA9IGRhdGEuZnJhbWUoeCwgeTEsIHkyLCBsaW5ldHlwZSwgY29sb3IpLAogIHR5cGUgPSAic2NhdHRlciIsCiAgbW9kZSA9ICJsaW5lcyIKKSAlPiUKICAjIEZpcnN0IHRyYWNlIHdpdGggY29sb3IgYW5kIGxpbmV0eXBlIG1hcHBpbmcKICBhZGRfdHJhY2UoCiAgICB4ID0gfngsCiAgICB5ID0gfnkxLAogICAgbGluZSA9IGxpc3QoZGFzaCA9IH5saW5ldHlwZSksCiAgICBsZWdlbmRncm91cCA9IH5saW5ldHlwZSwgICAgICAgICAjIEdyb3VwIGJ5IGxpbmV0eXBlCiAgICBsaW5ldHlwZSA9IH5saW5ldHlwZSwKICAgIGNvbG9yID0g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