使用R中的plot_ly函数为热图获取单独的正/负颜色

时间:2017-07-14 12:31:14

标签: r plotly heatmap

我有一个包含以下值的矩阵。

heatrix = matrix(c(-32.28, 1, -3.57, 14.75, 26.62, 0, 0, 0, 0, 21, 26, -69.2, -59, -5.12, -14.94, 0),nrow = 4,ncol=4,byrow = T)

我想制作一个热图,其中heatrix中的正值为绿色,负值为红色。 " 0"值可以是白色或任何其他任意数字。

p <- plot_ly(
x = c("0-25", "25-50", "50-75", "75-100"),
y = c("0-25", "25-50", "50-75", "75-100"),
z = heatrix, type = "heatmap",
colors = colorRamp(c("red", "green"))

这给了我带负值的绿色方块,因此很难判断哪些值高于或低于0。如何使用plot_ly制作我喜欢的音阶?

1 个答案:

答案 0 :(得分:0)

不幸的是,我不知道使用plot_ly()的解决方案,但是当我想要使用实际值而不是z-score的热图时,我会使用我之前在这里找到的解决方案。也许它对你也有用。

library(tidyr)
library(tibble)
heatrix = matrix(c(-32.28, 1, -3.57, 14.75, 26.62, 0, 0, 0, 0, 21, 26, -69.2, -59, -5.12, -14.94, 0),nrow = 4,ncol=4,byrow = T)
dat <- heatrix %>%
  tbl_df() %>%
  rownames_to_column('Var1') %>%
  gather(Var2, value, -Var1) %>%
  mutate(
    Var1 = factor(Var1, levels=1:10),
    Var2 = factor(gsub("V", "", Var2), levels=1:10)
  )

ggplot(dat, aes(Var1, Var2)) +
  geom_tile(aes(fill = value)) + 
  geom_text(aes(label = round(value, 1))) +
  scale_fill_gradient(low = "red", high = "green")

enter image description here

是的,我们可以更改两个轴的粗标签:

new_scale <- c("0-25", "25-50", "50-75", "75-100")

然后在ggplot()函数

中添加图层
ggplot(dat, aes(Var1, Var2)) +
  geom_tile(aes(fill = value)) + 
  geom_text(aes(label = round(value, 1))) +
  scale_y_discrete(labels= new_scale) + # <-
  scale_x_discrete(labels= new_scale) + # <-
  scale_fill_gradient(low = "red", high = "green")

enter image description here