使用 plotly 时图例中的颜色条

Posted

技术标签:

【中文标题】使用 plotly 时图例中的颜色条【英文标题】:Colorbar in legend when using plotly 【发布时间】:2017-06-07 10:23:05 【问题描述】:

这是我的数据:

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)

如何在颜色基于Index 值的图例中获得colorbar。

【问题讨论】:

【参考方案1】:

你在找这个吗:

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")

【讨论】:

以上是关于使用 plotly 时图例中的颜色条的主要内容,如果未能解决你的问题,请参考以下文章