如何在R中为Plotly热力图生成自定义颜色刻度

6

我希望获取一个自定义的颜色比例尺,类似于plotly热图(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,绘制的数据将在此区间内具有不同的值。


我更新了我的答案,请看一下。 - KoenV
1个回答

12

您用来生成调色板的代码运行良好。您只需要提供与 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")

这将生成以下热力图:

输入图像描述

## 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_ly中使用zautozmaxzmin设置自定义比例。以下两段代码和图表将说明此点:

比例尺设置为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)

输入图像描述

该比例尺设置为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


在我的数据中(97x138矩阵,97个通道和138个时间戳),数值范围从0到10^8,即使我的数据没有这样的值,我也希望0/1表示深蓝色,10^8表示深红色等,以防其他数据集有这样的值。 - Tsingis
我想我现在明白了你的问题。请看更新后的答案。 - KoenV
由于某种原因,当我将调色板应用于我的数据时,比例尺仅包含红色、紫色和蓝色,没有其他定义的颜色。另外感谢zauto、zmin和zmax。它们正是我在寻找的。 - Tsingis
您可以使用以下代码检查您的调色板:plot(rep(1,50),col=palette(50), pch=19, cex=3)。如果看起来不错,您可以查看数据的分布情况,也许数据与您的期望有所不同。作为最后的手段,您可以重新启动R/RStudio并重复这些步骤。 - KoenV
1
这真是太棒了,我已经寻找了很长时间才找到能帮助我的东西。我有一个带有自定义色条的分类数据。我正在创建一个函数,它将动态地创建一个具有多个子图的绘图。我不知道它们是否都包含了我所有的类别。zmax和zmin确保我放置图例的图中包含了所有类别。太棒了。谢谢。 - Matt Dzievit
显示剩余4条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接