Home > OS >  R Plotly Heatmap Conditional Annotation with ifelse?
R Plotly Heatmap Conditional Annotation with ifelse?

Time:12-10

Follwoing: enter image description here

For example, if I swap the conditions for the colors in the function:

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()

Now you can see the text a lot better:

enter image description here

By the way, you could also call the plot as it is and use that(last_plot()) to rerender it with the new text colors.

Both plotly and ggplot2 have the function last_plot(); make sure you're calling the plotly version if you use this method.

CodePudding user response:

Just an idea, you can also use a heatplot like this if you want to show a thresholded map:

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

enter image description here

  • Related