如何为R中的plotly热图生成自定义色阶

时间:2017-07-05 06:40:40

标签: r plotly heatmap

我想获得一个自定义色标,看起来像是热情地图(plot_ly(z = data, colors = customcolors, type = "heatmap")

palette <- colorRampPalette(c("darkblue", "blue", "lightblue1",
                          "green","yellow", "red", "darkred"))
plot(rep(1,50),col=palette(50), pch=19, cex=3, xlab = "", ylab ="", axes = F)

并且蓝色末端代表1,红色末端代表10 ^ 6,绘制的数据在此区间内具有不同的值。

1 个答案:

答案 0 :(得分:3)

用于生成调色板的代码工作得很好。您只需提供与heatmap匹配的数据。以下代码提供了这个:

library(RColorBrewer)
library(plotly)

# your palette definition
palette <- colorRampPalette(c("darkblue", "blue", "lightblue1",
                              "green","yellow", "red", "darkred"))

set.seed(9876)    # for reproducibility

## a complete random set
hmdata <- matrix(data = sample(x = 1:10^6, size = 100*100), nrow = 100, ncol = 100)
plot_ly(z = hmdata, colors = palette(50), type = "heatmap")

这给出了以下热图:

enter image description here

## a random set that has been sorted
hmdata_s <- matrix(data = sort(sample(x = 1:10^6, size = 100*100)), nrow = 100, ncol = 100)
plot_ly(z = hmdata_s, colors = palette(50), type = "heatmap")

产生这个情节: enter image description here

请告诉我这是否是你想要的。

更新

您可以使用plot_lyzautozmaxzmin中设置自定义比例。以下2段代码和图表将说明这一点:

比例设置为1到100,数据的变化相似:

hmdata_s3 <- matrix(data = sort(sample(x = 1:100, size = 100*100, replace = TRUE)), nrow = 100, ncol = 100)
plot_ly(z = hmdata_s3, colors = palette(50), type = "heatmap", zauto = FALSE, zmin = 1, zmax = 100)

enter image description here

比例设置为1到100,数据仅在50到100之间

hmdata_s4 <- matrix(data = sort(sample(x = 50:100, size = 100*100, replace = TRUE)), nrow = 100, ncol = 100)
plot_ly(z = hmdata_s4, colors = palette(50), type = "heatmap", zauto = FALSE, zmin = 1, zmax = 100)

enter image description here