How to change the color of the lines based on a certain rules in plotly

To give you an example plotly comes with an inbuilt dataset called txhousing. try to run this code on your machine.

# lines -------------------------------------------------------------------
txhousing %>% setDT()
top5 <-
    txhousing[, mean(sales, na.rm = T), city][order(-V1), ][1:5,]

txhousing %>% setkey(city)
top5 %>% setkey(city)

txhousing %>%
    plot_ly() %>%
        x =  ~ date,
        y =  ~ median,
        alpha = .2,
        color =  ~ city,
        colors = 'black'
    ) %>%
        data = (top5[txhousing][!,]),
        x = ~ date,
        y =  ~ median,
        color =  ~ city,
        colors = I('red'),
        size = I(2)
    ) %>%
    hide_legend() %>%
    config(displayModeBar = F)

above code is meant to highlight top 5 cities in the data. and it is taken from the book

3 Scattered foundations | Interactive web-based data visualization with R, plotly, and shiny.

But I do not find any example where I could change the color of a current line.

now this code should plot another line on the top of the last line just like geom_line() does in ggplot2. but it doesn't the plot it produces is.

instead of changing the color to red it doesn't change color at all.

Is there a method to do that. or there something I am missing. I need this thing to create a different plot for shiny dashboard and it has to be interactive and fast. so I would rather choose a plot_ly alternative than to first plot it in ggplot2 and then change it to plotly.

Is there a any method. Please let me know.

I want to draw a graph something like this

but I want to draw this directly in plotly without going through ggplot2.

when I try that it gives me..

Please help me out as this graph will go into a live dashboard speed and look both matters

Can you please add reprexes with the code for both figures above. It'll be easier for someone to help you if they can see where you've started!

Hi @mara,

I don't think I would be able to share this data. But just for reference I have shared the basic code above. With the in built dataset in plotly package. I just want to highlight selected lines in different colors. That's it.

Say if there are 10 lines I want to highlight 3 or 4 in different colors.

How should I do it.

If you want to avoid ggplot2, and use plotly for a shiny app, this question might be better suited for #shiny than #tidyverse

1 Like


I have changed it to shiny from tidy verse but nobody replied yet.

If you know how to do it in plotly could you please help me out...