简体   繁体   English

更改绘图热图中的颜色条标签 (R)

[英]Changing the colorbar labels in a plotly heatmap (R)

I am working with survey data where a person responds from 'not' to 'absolutely' in response to being asked whether one variable affects another.我正在处理调查数据,其中一个人在被问及一个变量是否影响另一个变量时从“不是”到“绝对”做出回应。 The responses are mapped to numbers, and a mean response is calculated.响应被映射到数字,并计算平均响应。

I am presenting these mean values in a heatmap (x and y are lists with the same variable names).我在热图中显示这些平均值(x 和 y 是具有相同变量名称的列表)。 I would like the colour of squares in the heatmap to reflect the numerical mean, but I would like the labels on the colorbar to reflect the actual response text (eg 'not', 'lowly, 'moderately', 'highly', 'very highly') and to limit the tick marks to positions 0,1,2,3,4.我希望热图中方块的颜色反映数字平均值,但我希望颜色条上的标签反映实际的响应文本(例如“不”、“低”、“中等”、“高度”、“非常”高度')并将刻度线限制在位置 0、1、2、3、4。

I'm not sure this can be done with plotly.我不确定这可以用 plotly 来完成。 I was able to do it with ggiraph, but this is going into Shiny and ggiraph has its own issues there - in plotly I have more control over display size and I couldn't get ggiraph to render large enough.我能够用 ggiraph 做到这一点,但是这将进入 Shiny 并且 ggiraph 在那里有自己的问题 - 在情节上,我对显示尺寸有更多的控制,但我无法让 ggiraph 渲染得足够大。

Minimal code is below, and so is the output.下面是最少的代码,输出也是如此。

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

在此处输入图片说明

You could use ggplot and ggplotly for more flexibility.您可以使用ggplotggplotly以获得更大的灵活性。 But you first need to tranform your data into long data.frame:但是您首先需要将您的数据转换为长 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)

在此处输入图片说明

The function scale_fill_continuous allows you to specify manually your labels for different breaks.函数scale_fill_continuous允许您为不同的中断手动指定标签。 You have a lot of possibilities to tweak your graph with ggplot您有很多可能性可以使用ggplot调整图形

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM