问题
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.
回答1:
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")
来源:https://stackoverflow.com/questions/41797368/colorbar-in-legend-when-using-plotly