如何在R Shiny应用中自定义heatmaply热力图的悬浮提示
自定义heatmaply热力图的悬浮提示文本
你可以通过两种方式自定义heatmaply生成的热力图悬浮提示文本:
方法1:使用heatmaply自带的custom_hovertext参数
预先构造每个单元格的提示文本矩阵,直接传入该参数,适合需要灵活定制内容(比如添加额外信息)的场景。
library(shiny) library(heatmaply) library(plotly) ui <- fluidPage( plotlyOutput("heatmap") ) server <- function(input, output) { output$heatmap <- renderPlotly({ # 示例数据 mat <- matrix(rnorm(25), nrow = 5, ncol = 5) rownames(mat) <- paste0("行", 1:5) colnames(mat) <- paste0("列", 1:5) # 构造自定义提示文本矩阵 hover_text <- matrix( paste0("自定义行标签: ", rownames(mat)[row(mat)], "<br>", "自定义列标签: ", colnames(mat)[col(mat)], "<br>", "数值: ", round(mat, 2)), nrow = nrow(mat), ncol = ncol(mat) ) # 生成热力图并传入自定义提示文本 heatmaply(mat, custom_hovertext = hover_text) }) } shinyApp(ui, server)
方法2:修改plotly对象的hovertemplate
heatmaply返回的是plotly对象,可通过style()函数直接修改hovertemplate属性,适合快速替换默认格式的场景。
library(shiny) library(heatmaply) library(plotly) ui <- fluidPage( plotlyOutput("heatmap") ) server <- function(input, output) { output$heatmap <- renderPlotly({ # 示例数据 mat <- matrix(rnorm(25), nrow = 5, ncol = 5) rownames(mat) <- paste0("行", 1:5) colnames(mat) <- paste0("列", 1:5) # 生成基础热力图 p <- heatmaply(mat) # 自定义悬浮提示模板 p %>% style( hovertemplate = "行: %{y}<br>列: %{x}<br>数值: %{z}<extra></extra>" ) }) } shinyApp(ui, server)
注意事项
hovertemplate中的占位符对应关系:%{x}是列名,%{y}是行名,%{z}是单元格数值;<extra></extra>用于移除plotly默认的额外追踪信息。- 如果需要在提示中加入数据集外的额外信息,优先选择方法1。
内容的提问来源于stack exchange,提问作者nico
相关产品推荐
相关产品推荐

