3

抱歉,如果这很简单。其实我希望会!

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

我开始使用图像(我使用png()and生成的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)

生产:

在此处输入图像描述

这很好,但是如果它们的大小不同,使用动态创建图像会很尴尬,而且将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)

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

文本格罗布

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

提前致谢!

4

1 回答 1

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)

在此处输入图像描述

于 2013-12-04T12:44:32.920 回答