4

I have a scatter plot with 3 factors. I add 3 traces where each trace corresponds to a factor. I want the scatter plot and the trace to be the same color. Here is simple function to generate appropriate test data:

## generate test data
getTestData <- function(seed_val=711, noise=1.0) {
    set.seed(seed_val)
    d <- seq(as.Date('2017/01/01'), as.Date('2017/01/08'), "days")
    first_name <- rep("Jane", 8)
    first_name <- append(first_name, rep("Fred", 8))
    first_name <- append(first_name, rep("Sally", 8))
    y1_vals <- seq(1, 3*8, 1)
    y2_vals <- rnorm(3*8, mean=y1_vals, sd=noise)
    dat <- data.frame(date=d, f_name=first_name, y1=y1_vals, y2=y2_vals,
                      stringsAsFactors = FALSE)
    return(dat)
}

If I create a data frame and pass it to plot_ly like this:

library(plotly)
library(dplyr)
df <- getTestData()
p1 <- plot_ly(df, x=~date, y=~y1, color=~f_name,
          type = 'scatter', mode = "lines+markers") %>% 
      layout(yaxis = list(title = "some important y value")) %>% 
      add_trace(y=~y2, name='actual', showlegend=TRUE, 
          type='scatter', mode='lines',
          line=list(width = 2, dash = 'dash', color=~f_name))

I get this:

enter image description here

How do I get the colors of the scatter and the corresponding trace to be the same?

This wasn't quite what I needed: Grouped line plots in Plotly R: how to control line color?

This was very close: Same color assigned to same level of factor in R plotly but the author of this answer points out exactly the problem I run into when I try various hacks when they state:

Note that hav[ing] factor variables can mess this up due to the ordering that plotly uses (which I can't decipher sometimes).

1 Answer 1

5

Are you looking for something like this:

pal <- c("red", "blue", "green")
p1 <- plot_ly(df, x=~date, y=~y1, color=~f_name, colors = pal,
              type = 'scatter', mode = "lines+markers") %>% 
    layout(yaxis = list(title = "some important y value")) %>% 
    add_trace(y=~y2, name='actual', showlegend=TRUE, 
              type='scatter', mode='lines',
              line=list(width = 2, dash = 'dash'), color=~f_name, colors = pal)
p1

enter image description here

Sign up to request clarification or add additional context in comments.

1 Comment

Yes. I had tried something almost exactly like this, except that I placed the last 2 args of the trace within the line list. Thanks for clearing this up for me.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.