Highcharter: heatmap display non-numeric datalables

56 views Asked by At

I'm trying to figure out how to display non-numeric labels on the heatmap. Sample code:

library(highcharter)    
data <- data.frame(
      X = rep(c(1:20),3),
      Y = c(rep(c("A"), 20), rep(c("B"), 20), rep(c("C"), 20)),
      Label = rep(c("V","W","X", "Y", "Z"), 6),
      Value = round(rnorm(60))
    )
    

data %>%
  hchart(type = "heatmap", hcaes(x = X, y = Y, value = Label, color = Value)) %>%
  hc_plotOptions(
    series = list(
      dataLabels = list(enabled = TRUE
      ))) %>%
  hc_chart(
    zoomType = "x"
  ) 

I could create what I wanted with Plotly, but it gets very slow for the larger plots, and I would like to manually assign colours to values/labels.

library(plotly)
plot_ly(
  x = data$X,
  y = data$Y,
  z = data$Value,
  type = "heatmap",
  colors = color_scheme,
  # colorbar = list(len=20, limits = c(-100, 100)),
  showscale=FALSE
) %>%
  add_annotations(
    data = data,
    x = ~X, 
    y = ~Y, 
    text = ~Label, 
    xref = 'x', 
    yref = 'y', 
    showarrow = FALSE, 
    font=list(color='black')) 
1

There are 1 answers

0
Near Lin On

The option dataLabels is used to label the value, you could use labels in hc_annotations instead. First, create a dataframe for annotation:

data2 <- data |>
  mutate(
    x = X,
    y = case_when(
      Y == "A" ~ 0, # y needs to be numeric to index the position
      Y == "B" ~ 1,
      Y == "C" ~ 2
    ),
    text = Label
  ) |>
  select(x, y, text)

And you can draw your heatmap.

data |>
  hchart(type = "heatmap", hcaes(x = X, y = Y, value = Value)) |>
  hc_annotations(list(labels = df_to_annotations_labels(data2))) |>
  hc_chart(zoomType = "x")