r - 处理 geom_text 大小

标签 r ggplot2

我正在使用 ggplot2 geom_tile 构建热图,并向每个单元格添加一些文本,如下所示:

enter image description here

我正在使用的代码如下。但随着热图中图 block 数量的变化,我需要调整文本大小。有没有办法获取图 block 大小并使用它来设置文本大小?或者自动缩放文本?或者甚至构建文本图像并将其缩放为图 block 上的叠加层?

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

最佳答案

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)

reprex package 于 2021 年 12 月 10 日创建(v2.0.1)

关于r - 处理 geom_text 大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70305422/

相关文章:

r - 为什么 xts 实现为矩阵而不是数据框?

R:根据多列中的值从数据框中删除行

r - 是否可以在查看器 Pane 中查看 HTML 表格?

r - Python的R等价形式,从x导入y为z。

r - 如何在 R ggplot 的 geom_label 框中将文本居中?

r - 在 ggplot 的 geom_rug 中使用的数据与我在其余情节中使用的数据不同

r - 如何使用 grid.arrange 循环保存多个 ggplot 图表

r - 错误 ".onLoad failed in loadNamespace() for ' tcltk'"

r - 如何更改ggplot2中图例文本的大小?

r - 使用堆叠条形图时,ggplot2 条形图带有误差条