cgnx
cgnx

Reputation: 113

Changing color of a line in plot when certain condition is met

I have a plot of a probability of an event which changes in time (x-axis is time and y-axis is the probability variable). Beside that in data I have a variable that can have value 0 or 1. What I am looking for is that the probability line has black color when the binary value is 0 and when the binary variable is 1 then the probability line is red. So at the moment I have only the plot of the probability. I don't know how to incorporate the binary variable.

plot_ly(df,x=df$time,y=df$probab,type="line")

Upvotes: 0

Views: 1111

Answers (1)

Wietze314
Wietze314

Reputation: 6020

To make things easy I made an example with multiple steps:

df <- data.frame(time = 1:11
                 , probab = seq(0.1,0.2, by=0.01)
                 ,bin = rep(1,11))

linecol <- c("black","red")[max(df$bin)+1]

plot_ly(df,x=df$time,y=df$probab,type="scatter", mode="lines"
        , line = list(color=linecol))

I assumed the binary value was in the dataframe, but offcourse another source can be used as well.

Your remark on your question makes it a bit more complex. I suggest to divide your line into different sections of lines. This means duplicating the points of the data, to make the sections.

library(plotly)

df <- data.frame(time = 1:11
                 , probab = seq(0.1,0.2, by=0.01)
                 ,bin = c(rep(0:1,5),1))


df2 <- df[c(1,rep(2:10,each=2),11),]
df2$section = rep(1:10, each=2)

linecol <- c("black","red")[df2$bin[seq(1,20,by=2)]+1]
linecol <- rep(linecol,each=2)
p <- plot_ly(df2 %>% group_by(section),x=~time,y=~probab)
add_trace(p, mode = "markers+lines",color = linecol)

For some reason add_trace did not identify the red and black string as a color. Not sure how to fix this.

Upvotes: 1

Related Questions