Dealing with geom_text size

Viewed 93

I'm building a heatmap using ggplot2 geom_tile and adding some text to each cell as follows:

enter image description here

The code I'm using is below. But as the number of tiles in the heatmap change I need to adjust the text size. Is there someway to get the tile size and use that to set the text size? Or autoscale the text? Or even build an image of the text and scale that as an overlay on the tile?

  text.size.corr  =  0.9
  text.vjust.corr = -0.6
  text.size.misc  =  0.4
  text.vjust.misc =  0.8
  text.lineheight.misc = 0.8
  
  ggheatmap =
    ggplot(res2.flat, 
           aes(column, row, fill=cor)
           )+  
      geom_tile(color = "white") +
      geom_text( aes( column, row, label=cor ),   # add Corr  value
                 color = "black", 
                 size = text.size.corr,
                 vjust= text.vjust.corr
                 ) +
      geom_text( aes( column, row, label=glue("{row}:{column}\np={formatPvalue(p)}\nn={n}") ), # p value
             color = "black", 
             size = text.size.misc,
             vjust= text.vjust.misc,
             lineheight = text.lineheight.misc
             ) +
1 Answers

There is ggfittext:

library(tidyverse)
library(ggfittext)

data <- tribble(
  ~x, ~y, ~value, ~p, ~n,
  1, 1, 0.78, 0.05, 132,
  1, 2, 0.67, 0.04, 421,
  2, 1, 0.72, 0.01, 400,
  2, 2, 0.23, 0.01, 300
)

data %>%
  ggplot(aes(x, y)) +
  geom_tile(aes(fill = value)) +
  geom_fit_text(aes(label = paste0(p, "\n", n)), size = 1e3)

Created on 2021-12-10 by the reprex package (v2.0.1)

Related