将textGrob转换为imageGrob / rasterGrob?

时间:2013-11-26 07:56:58

标签: r ggplot2 r-grid

如果这非常简单,请道歉。其实我希望它会是!

我正在尝试从文本中动态创建图像,然后我可以调整大小并绘图(拉伸或压扁)以生成图案类型的图形。

我开始使用图片(我使用png()ggplot()生成)并将其绘制为annotation_custom()

require(ggplot2)
require(grid)
require(gridExtra)
qplot(c(0,10),c(0,10)) + 
annotation_custom(rasterGrob(image=readPNG("1999.png"),x=0,y=0,height=1,width=1,just=c("left","bottom")),
              xmin=0,xmax=5,ymin=0,ymax=7.5)

生产:

enter image description here

这很好,但是如果它们的大小不同,使用png()动态创建图像是很尴尬的,加上它很笨笨来保存它们,所以我试着看看我是否可以使用textGrob :

myText<-"1000"
myTextGrob<-textGrob(myText,just=c("left","bottom"),gp=gpar(fontsize="100",col="red",fontfamily="Showcard Gothic"))
qplot(c(0,10),c(0,10))+annotation_custom(myTextGrob,0,0,0,0)

得到了这个,这很好,除了....

textGrob

......似乎无法伸展和放松以与rasterGrob相同的方式偏斜它,所以我的问题是 - 是否可以创建textGrob并将其强制转换为rasterGrob?或者是否有另一种解决方案让我倾斜/拉伸textGrob?

提前致谢!

1 个答案:

答案 0 :(得分:2)

如果不创建临时文件,这似乎并不容易。您可以使用带有grImport包的矢量路径,而不是光栅文件。导入文本有两种选择,

  • 作为路径;它的工作原理(下面的例子),但是没有明显的方法可以绕过带有中间文件的ps到xml的转换步骤

  • 作为文本字符串;在这种情况下,xml要短得多,可以直接从R创建,但遗憾的是我找不到独立转换两个轴的方法。


library(grImport)

scale_text <- function(text="hello world", scale=4, tmp=tempfile()){
  tmp.ps <- paste0(tmp, ".ps")
  tmp.xml <- paste0(tmp, ".xml")
  string.ps <- paste0('%!PS
                    /Courier             % name the desired font
                    20 selectfont        % choose the size in points and establish 
                    % the font as the current one
                    1 ', scale, ' scale            % scale axis
                    72 500 moveto        % position the current point at 
                    % coordinates 72, 500 (the origin is at the 
                    % lower-left corner of the page)
                    (', text, ') show  % stroke the text in parentheses
                    showpage             % print all on the page
                    ')
  cat(string.ps, file=tmp.ps)
  PostScriptTrace(tmp.ps, tmp.xml)
  readPicture(tmp.xml)
}


hello <- scale_text()
grid.newpage()
grid.picture(hello)

enter image description here