这是我的数据:
set.seed(42)
mydata = data.frame(A = rnorm(20), B = rnorm(20), Index = sample(190:400,20))
我试图根据Index
值将数据划分为20个不同的区间,然后根据区间value
对散点进行着色。以下是我的代码。它运作不正常。
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)
如何在图例中获得colorbar,其中颜色基于Index
值。
答案 0 :(得分:2)
你在找这个:
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")