Vitomir
Vitomir

Reputation: 295

How to conditionally change color of markers in Plotly?

I have a dataframe in R that has some continuous values in column value and a signal column which is either 0 or 1.

db <- cbind(seq(1,5),rnorm(5,0,1), c(0,0,1,0,1))
colnames(db) <- c("ID","value","signal")
db <- as.data.frame(db)

Using plotly, I want to plot the line+markers of column value and have the marker of a different color from the line when the column signal has value of 1.

Anyone has any idea how to do this? The most I could get is a simple line+markers plot.

plot_ly(db) %>%
  add_trace(x=~ID, y=~value, type='scatter',
            mode='lines+markers', color=I('black'))

Thank you in advance.

Upvotes: 0

Views: 721

Answers (1)

Yuli S
Yuli S

Reputation: 493

You can separate the line plot and dot plot and decide color for them separately. You could try this,

plot_ly(db, x=~ID, y=~value, type='scatter',
        mode='markers', color = db$signal, 
        colors = c("1" = "white", "0" = "black")) %>%
  add_trace(x=~ID, y=~value, type='scatter',
            mode='lines', color=I('black'))

Upvotes: 1

Related Questions