How to write a text into plotly heat map in r?

别说谁变了你拦得住时间么 提交于 2019-12-04 16:56:00

You could add the text via add_annotations.

  • Specify the x and y coordinates (in the example below relative to x and y-axis via xref = 'x' and yref = 'y')
  • Add the text via text
  • Remove the default arrow with showarrow = FALSE

anno_x <- c(1, 5)
anno_y <- c(1, 5)
anno_text <- c('I like beer', 'I like CSGO')

p <- plot_ly(
  x = c(1:5), 
  y = c(1:5),
  z = matrix(rnorm(9), nrow = 5, ncol = 5),
  type='heatmap') %>% add_annotations(x = anno_x, y = anno_y, text = anno_text, xref = 'x', yref = 'y', showarrow = FALSE, font=list(color='black'))

p

First define the 5x5 text matrix, then add it to the data frame and then use add_annotations:

txt <- matrix(LETTERS[1:25], nrow=5) # define your 5x5 text matrix
df$txt <- txt[as.matrix(df[,1:2])]
library(plotly)
plot_ly(z = ~df$MonetaryClass, 
        x = ~df$RecencyClass, 
        y = ~df$FrequencyClass, 
        type = "heatmap") %>% 
  colorbar(title = 'Monetary Class',
           limits = c(1,5), 
           tickmode = 'array', 
           tickvals = c(1,2,3,4,5)) %>%
  layout(title = "RFM Analyse",
         xaxis = list(title = 'Recency Class',
                      tickmode = 'array',
                      tickvals = c(1, 2,3,4,5),
                      ticktext = c(1, 2, 3, 4, 5)
         ),
         yaxis = list(title = 'Frequency Class',
                      tickmode = 'array',
                      tickvals = c(1, 2,3,4,5),
                      ticktext = c(1, 2, 3, 4, 5)
         )
  ) %>%
  add_annotations(x = df$RecencyClass,
                  y = df$FrequencyClass,
                  text = df$txt, 
                  showarrow = FALSE,
                  ax = 20,
                  ay = -20)

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!