3
votes

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

1 Answers

3
votes

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