R网格包:如何创建具有多种颜色的textGrob并将其放置在视口的中心

时间:2020-02-28 20:18:50

标签: r r-grid grob

我需要类似以下内容的东西,但字符串中每个单词的颜色都不同:

library(grid)

grid.newpage()
pushViewport(viewport(width = unit(5, 'cm'), height = unit(5, 'cm')))
grid.rect()
grid.text(label = 'Hello, World!')

我尝试为每个段创建单个的笔触,然后将它们组合在一起,但是我不知道如何将结果放置在视口的中心:

grid.newpage()
pushViewport(viewport(width = unit(5, 'cm'), height = unit(5, 'cm')))
grid.rect()

grouped_grobs <-
    gList(textGrob(label = 'Hello',
                   x = unit(0.0, 'npc'),
                   y = unit(0.5, 'npc'),
                   just = c('left', 'center'),
                   gp = gpar(col='red')),
          textGrob(label = ',',
                   x = unit(1, 'strwidth', data = 'Hello'),
                   y = unit(0.5, 'npc'),
                   just = c('left', 'center'),
                   gp = gpar(col='black')),
          textGrob(label = 'World',
                   x = unit(1, 'strwidth', data = 'Hello, '),
                   y = unit(0.5, 'npc'),
                   just = c('left', 'center'),
                   gp = gpar(col='blue')),
          textGrob(label = '!',
                   x = unit(1, 'strwidth', data = 'Hello, World'),
                   y = unit(0.5, 'npc'),
                   just = c('left', 'center'),
                   gp = gpar(col='black')))

grid.draw(grouped_grobs)

我尝试过测量gList的宽度,也尝试过使用gTree,但是不知何故我被困在了这个看似简单的任务上。

在此先感谢您的帮助!

1 个答案:

答案 0 :(得分:1)

使用gridtext程序包可以更轻松地绘制彩色文本。例如

grid.newpage()
pushViewport(viewport(width = unit(5, 'cm'), height = unit(5, 'cm')))
grid.rect()

grid.draw(gridtext::richtext_grob(text = '<span style="color:red">Hello</span>, <span style="color:blue">World</span>!',
             x = unit(0.5, 'npc'),
             y = unit(0.5, 'npc'),
             hjust=.5))

会回来

enter image description here