【问题标题】:Changing the colorbar labels in a plotly heatmap (R)更改绘图热图中的颜色条标签 (R)
【发布时间】:2020-12-26 10:15:41
【问题描述】:

我正在处理调查数据,当被问及一个变量是否影响另一个变量时,一个人的回答从“不”到“绝对”。将响应映射到数字,并计算平均响应。

我在热图中呈现这些平均值(x 和 y 是具有相同变量名称的列表)。我希望热图中正方形的颜色能够反映数值平均值,但我希望颜色栏上的标签能够反映实际的响应文本(例如,'not'、'lowly、'moderately'、'highly'、'very高度')并将刻度线限制在位置 0,1,2,3,4。

我不确定这是否可以通过 plotly 来完成。我可以用 ggiraph 做到这一点,但这会进入 Shiny 并且 ggiraph 在那里有自己的问题 - 在情节上,我可以更好地控制显示尺寸,我无法让 ggiraph 渲染得足够大。

下面是最少的代码,输出也是。

library(plotly)
library(tidyr)

M <- matrix(c(NA, 1,3, 2, NA, 4, 3, 0, NA), nrow = 3, ncol = 3)
names_M <- c('var1', 'var2', 'var3')


val_to_char <- function(x) {
        if(is.na(x)) {return(x)}
        else if(x < 0.5) {return('not')}
        else if(x < 1.5) {return('lowly')}
        else if(x < 2.5) {return('moderately')}
        else if(x < 3.5) {return('highly')}
        else {return('very high')}
      }
      
labels <- apply(M, c(1,2), val_to_char)

   
fig <- plot_ly()
fig <- fig %>%
  add_trace(
    type = 'heatmap',
    x = names_M, y = names_M, z = M, text = labels,
    hovertemplate = '<extra></extra> Row: %{y}</br></br>Col: %{x}</br>Avg response: %{text}'
  )

fig

【问题讨论】:

    标签: r plotly heatmap colorbar


    【解决方案1】:

    您可以使用ggplotggplotly 以获得更大的灵活性。但是你首先需要将你的数据转换成长data.frame:

    M <- as.data.frame.matrix(matrix(c(NA, 1,3, 2, NA, 4, 3, 0, NA), nrow = 3, ncol = 3))
    names(M) <- c('var1', 'var2', 'var3')
    
    
    p <- M %>%
    pivot_longer(.,paste0("var",1:3),names_to = "x",values_to = "z") %>%
      mutate(y = rep(paste0("var",1:3),each = 3)) %>%
      ggplot(aes(x,y,fill = z))+
      geom_tile() +
      scale_fill_continuous(breaks = 0:4,labels = c("not","lowly","moderatly","highly","very high"))
    
    
    ggplotly(p)
    

    scale_fill_continuous 函数允许您手动指定不同中断的标签。使用ggplot

    调整图表有很多可能性

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-07-20
      • 2012-10-23
      • 1970-01-01
      • 2019-06-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-11
      相关资源
      最近更新 更多