簡體   English   中英

R Plotly 使用 ifelse 的熱圖條件注釋?

[英]R Plotly Heatmap Conditional Annotation with ifelse?

以下: R 熱圖:有條件地更改 label 文本顏色(ggplot2 或 plotly)

我認為下面的代碼會創建一個熱圖,如果值大於 5(因此在這種情況下,當 (X,Y)=(3,"C")),其注釋為白色,但它不起作用。 任何的想法?

謝謝!

df<-tibble(Y=c("A","B","C"),
           X=c(1,2,3),
           Z=c(1,5,10))
df %>%
  plot_ly(x = ~X, y=~Y, z=~Z, type='heatmap') %>%
  add_annotations(text = ~Z,
                  showarrow = FALSE,
                  font = list(color = ~ifelse(Z>5,'white','black')))

字體 colors 在 Plotly 中並未設計為動態字體。盡管add_annotations本質上理解您想要為Z中的每個值添加一個“add_annotation”,但它並不假定這就是您對字體顏色的含義。 但是,您仍然可以使用 UDF 即時更改它。

這個function重建plot,然后解析注解賦值colors。

that <- function(plt) {
  plt <- plotly_build(plt)      # build the plot to collect the data
  lapply(1:length(plt$x$layout$annotations), # loop through annotations
      function(j) {
        this <- plt$x$layout$annotations[[j]]             # collect annotation
        colr <- ifelse(this$text > 5, "white", "black")   # test for color
        plt$x$layout$annotations[[j]]$font$color <<- colr # assign color
      })
  plt       # return updated plot
}

您使用它的方式是將其通過管道傳輸到 plot 呼叫的末尾。 對於沒有特別指定顏色的情況,我沒有綁定例外。 換句話說,在你原來的plot電話里分配一個顏色,不管是什么顏色都行。

df %>%
  plot_ly(x = ~X, y = ~Y, z = ~Z, type = 'heatmap') %>%
  add_annotations(text = ~Z,
                  showarrow = FALSE,
                  font = list(color = "black")) %>% that() # <- I'm new!

我使用了您選擇的顏色序列,但我認為這與您真正想要的相反。

在此處輸入圖像描述

例如,如果我在 function 中交換 colors 的條件:

that <- function(plt) {
  plt <- plotly_build(plt)      # build the plot to collect the data
  lapply(1:length(plt$x$layout$annotations), # loop through annotations
      function(j) {
        this <- plt$x$layout$annotations[[j]]             # collect annotation
        colr <- ifelse(this$text > 5, "black", "white")   # test for color
        plt$x$layout$annotations[[j]]$font$color <<- colr # assign color
      })
  plt       # return updated plot
}

df %>%
  plot_ly(x = ~X, y = ~Y, z = ~Z, type = 'heatmap') %>%
  add_annotations(text = ~Z,
                  showarrow = FALSE,
                  font = list(color = "black")) %>% that()

現在您可以更好地看到文本:

在此處輸入圖像描述

順便說一下,您也可以按原樣調用 plot 並使用that(last_plot())用新文本 colors 重新呈現它。

plotlyggplot2都有 function last_plot() 如果您使用此方法,請確保您調用的是plotly版本。

只是一個想法,如果你想顯示一個閾值 map,你也可以使用這樣的熱圖:

ggplot(df, mapping = aes(x = X, y = Y, fill = Z>5, fill_max = 5)) + geom_tile()

在此處輸入圖像描述

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM