在热图中添加单元格值(单位:r)

5f0d552i  于 2023-02-17  发布在  其他
关注(0)|答案(1)|浏览(175)

也许是一个愚蠢的任务,但我不知道如何做到这一点。我只是想在热图中绘制单元格的值使用plotly

library(RColorBrewer)
library(plotly)

data <- matrix(data=20, nrow = 10, ncol = 10)
data<- as.data.frame(data)
colnames(data) <- letters[1:10]
rownames(data) <- LETTERS[1:10]

pal <- colorRampPalette(brewer.pal(9, "YlOrRd"))(29)
pal[1] <-c("#FFFFFF")

plot_ly(x = colnames(data), y = rownames(data), z = data, type = "heatmap", colors = pal, height=700, width=700, xgap=10, ygap=10, showscale=TRUE)

当我尝试add_annotation或设置layout垫等,它打印的值对角线的矩阵...谢谢你提前。

sc4hvdpw

sc4hvdpw1#

使用下面的代码,我生成了下面的图。我用add_annotations在一个重新整形的 Dataframe 上添加了文本。

library(RColorBrewer)
library(plotly)
library(tidyverse)
library(reshape2)

data <- matrix(data=rnorm(100), nrow = 10, ncol = 10)
x <- letters[1:10]
y <- LETTERS[1:10]

df = data.frame(data)
colnames(df) = x
rownames(df) = y
df = df %>% 
  rownames_to_column("y") %>% 
  melt(id.vars = "y") %>% 
  mutate(value = paste0(round(value*100,2),"%"))

pal <- colorRampPalette(brewer.pal(9, "YlOrRd"))(29)
pal[1] <-c("#FFFFFF")

plot_ly(
         z = data, 
         x = x,
         y = y,
         text = data,
        type = "heatmap",
        hoverinfo='none',
        colors = pal) %>% 
  add_annotations(
    data = df,
    x = ~variable, 
    y = ~y, 
    text = ~value, 
    xref = 'x', 
    yref = 'y', 
    showarrow = FALSE, 
    font=list(color='black'))

相关问题