【问题标题】:Diagonal annotations in Plotly's categorical heatmapPlotly 分类热图中的对角线注释
【发布时间】:2018-10-19 22:52:21
【问题描述】:

考虑使用以下 R sn-p 来渲染带有分类轴的热图:

library(plotly)

x <- c("Blue", "Red")
y <- c("One", "Two")

plot_ly(x = x, y = y, z = c(1:4)) %>%
    add_heatmap(
        opacity = 0.9
    ) %>%
    add_annotations(
        text = c(1:4),
        showarrow = FALSE
    )

这会呈现以下热图:

注释似乎从左下角单元格开始呈对角分布且不均匀。 1 和 3 位于左下角单元格中,2 和 4 位于右上角。为什么是这样?我的注释文本应该如何组织才能更直观地排序(水平或垂直)?

【问题讨论】:

  • 欢迎来到 Stackoverflow!如果您提供minimal reproducible example,您获得答案的机会会更高。在你的情况下,给我们corrs的值。
  • 嗨马克西米利安,感谢您的欢迎!抱歉省略了 corrs,我发帖时认为内容不相关。我已更新 OP 以包含数据框的内容。
  • 别担心!这是关于 Stackoverflow 的 R 问题的一个很好的主题:stackoverflow.com/questions/5963269/…
  • 谢谢,马克斯。我已经更新了我的问题中的示例,使其更加简洁且易于复制。

标签: r plotly r-plotly


【解决方案1】:

我只能推测这个问题,但在提供的图像中,您可以看到 Plotly 只使用了 4 个 z 值中的两个值。右侧的色阶是从 1 到 2,而不是 1 到 4。这很可能是因为您只提供了两个 x 和 y 值。

  • 使用数据框

    df <- expand.grid(x, y)
    df <- transform(df, text = paste(Var1, Var2, sep='_'))
    
    print(df)
    
    Var1 Var2     text
    1 Blue  One Blue_One
    2  Red  One  Red_One
    3 Blue  Two Blue_Two
    4  Red  Two  Red_Two
    
  • 您现在可以轻松使用add_annotations

    add_annotations(x = df$Var1,
                    y = df$Var2,
                    text = df$text)
    

为了得到下面的情节

完整代码

library(plotly)

x <- c("Blue", "Red")
y <- c("One", "Two")
df <- expand.grid(x, y)
df <- transform(df, text = paste(Var1, Var2, sep='_'))

p <- plot_ly(x = df$Var1, 
             y = df$Var2, 
             z = c(1:4)
             ) %>%
  add_heatmap(opacity = 0.9
              ) %>% 
  add_annotations(x = df$Var1,
                  y = df$Var2,
                  text = df$text)

p

或者,您可以遍历您的值并为每个值添加注释。

library(plotly)

x <- c("Blue", "Red")
y <- c("One", "Two")

p <- plot_ly(x = x, 
             y = y, 
             z = c(1:4)
             ) %>%
  add_heatmap(opacity = 0.9)

for (val_x in x)
{
  for (val_y in y)
  {
    p <- add_annotations(p, 
                         x = val_x,
                         y = val_y,
                         text = paste(val_x, val_y, sep = '_'))
  }
}

p

【讨论】:

  • 谢谢,马克西米利安!您的回答为我指明了正确的方向。我最终使用了 reshape 库中的 melt() 来创建要传入的注释。
猜你喜欢
  • 1970-01-01
  • 2020-11-28
  • 2021-09-22
  • 1970-01-01
  • 2021-09-16
  • 1970-01-01
  • 1970-01-01
  • 2022-01-20
  • 2019-01-27
相关资源
最近更新 更多