使用tikzDevice中的tikzAnnotate注释ggplot2图形

lea*_*rnr 7 r ggplot2

我想用来在文档中tikzDevice包含带注释的ggplot2图形Latex.

tikzAnnotatehelp有一个如何将它与基本图形一起使用的示例,但是如何将它与基于网格的绘图包一起使用ggplot2?挑战似乎是tikz节点的定位.

playwith包有一个功能convertToDevicePixels(http://code.google.com/p/playwith/source/browse/trunk/R/gridwork.R)似乎与grconvertX/grconvertY类似,但我无法让它工作无论是.

将不胜感激任何有关如何进行的指示.

tikz使用基本图形注释示例

library(tikzDevice)
library(ggplot2)
options(tikzLatexPackages = c(getOption('tikzLatexPackages'),
                "\\usetikzlibrary{shapes.arrows}"))
tikz(standAlone=TRUE)

print(plot(15:20, 5:10))
#print(qplot(15:20, 5:10))

x <- grconvertX(17,,'device')
y <- grconvertY(7,,'device')
#px <- playwith::convertToDevicePixels(17, 7)
#x <- px$x
#y <- px$y

tikzAnnotate(paste('\\node[single arrow,anchor=tip,draw,fill=green] at (',
                x,',',y,') {Look over here!};'))
dev.off()
Run Code Online (Sandbox Code Playgroud)

结果图像

Sha*_*pie 7

目前,tikzAnnotate仅适用于基本图形.当tikzAnnotate第一次写,有问题grid的图形是,我们需要指定x的一种方式,y坐标相对于设备画布的绝对左下角. grid从视口方面来看,在许多情况下,图形的最终坐标系似乎在通过print函数前往设备之前是未知的.

拥有这个功能会很棒,但我无法找到一种实现它的好方法,因此该功能被搁置了.如果有人有关于良好实施的详细信息,请随时开始讨论邮件列表(现在在Google网上论坛上有一个备用门户网站),它将进入TODO列表.

更好的是,实现该功能并在GitHub上打开对项目的拉取请求.这保证使该功能的发布速度比它在我的TODO列表中保存数月快9000倍.


更新

我有一些时间来处理这个问题,我想出了一个函数,用于将当前视口中的网格坐标转换为绝对设备坐标:

gridToDevice <- function(x = 0, y = 0, units = 'native') {
  # Converts a coordinate pair from the current viewport to an "absolute
  # location" measured in device units from the lower left corner. This is done
  # by first casting to inches in the current viewport and then using the
  # current.transform() matrix to obtain inches in the device canvas.
  x <- convertX(unit(x, units), unitTo = 'inches', valueOnly = TRUE)
  y <- convertY(unit(y, units), unitTo = 'inches', valueOnly = TRUE)

  transCoords <- c(x,y,1) %*% current.transform()
  transCoords <- (transCoords / transCoords[3])

  return(
    # Finally, cast from inches to native device units
    c(
      grconvertX(transCoords[1], from = 'inches', to ='device'),
      grconvertY(transCoords[2], from = 'inches', to ='device')
    )
  )

}
Run Code Online (Sandbox Code Playgroud)

使用这个缺失的部分,可以tikzAnnotate用来标记gridlattice绘图:

require(tikzDevice)
require(grid)
options(tikzLatexPackages = c(getOption('tikzLatexPackages'),
                "\\usetikzlibrary{shapes.arrows}"))

tikz(standAlone=TRUE)

xs <- 15:20
ys <- 5:10

pushViewport(plotViewport())
pushViewport(dataViewport(xs,ys))

grobs <- gList(grid.rect(),grid.xaxis(),grid.yaxis(),grid.points(xs, ys))

coords <- gridToDevice(17, 7)
tikzAnnotate(paste('\\node[single arrow,anchor=tip,draw,fill=green,left=1em]',
  'at (', coords[1],',',coords[2],') {Look over here!};'))

dev.off()
Run Code Online (Sandbox Code Playgroud)

这给出了以下输出:

网格图形的TikZ注释


还有一些工作要做,例如:

  • 创建可以添加到网格图形的"注释grob".

  • 确定如何将此类对象添加到ggplot.

这些功能预计将在0.7版本tikzDevice.