d.b
d.b

Reputation: 32558

Colorbar in legend when using plotly

Here is my data:

set.seed(42)
mydata = data.frame(A = rnorm(20), B = rnorm(20), Index = sample(190:400,20))    

I am trying to divide the data into 20 different intervals based on the Index value and then color the scatter points according to their interval value. Below is my code. It is not working perfectly.

cols = colorRampPalette(c("red", "black"), space = "rgb")(20)
mydata$interval = cut(mydata$Index,breaks = 20)
mydata$cols = cols[mydata$interval]
require(plotly)
x = list(title = "A")
y = list(title = "B")
plot_ly(mydata, x = ~A, y = ~B,  color = ~cols, type = "scatter",
                        mode = 'markers', hoverinfo = 'text',
                        text = ~paste(interval)) %>%
                        layout(xaxis = x, yaxis = y)

How do I get a colorbar in the legend where the colors are based on Index value.

Upvotes: 1

Views: 2288

Answers (1)

MLavoie
MLavoie

Reputation: 9886

Are you looking for this:

plot_ly(mydata, x = ~A, y = ~B, type = "scatter",
        mode = 'markers', hoverinfo = 'text', colors = colorRampPalette(c("red", "black"), space = "rgb")(20), color = ~Index, text = ~paste(interval), marker = list(size=14)) %>%
        layout(xaxis = x, yaxis = y) %>%
        colorbar(title = "My Legend")

Upvotes: 3

Related Questions