我想弄清楚如何在 ggplot 中使用 grconvertX/grconvertX 。我的最终目标是向ggplot2图(也可能是lattice) with grid.text
and grid.lines
从用户坐标到设备坐标。我知道可以用 grobs 来完成,但我想知道是否有更简单的方法。
以下代码允许我将值从用户坐标传递到 ndc 坐标,并使用这些值来注释绘图grid.text
.
graphics.off() # close graphics windows
library(grid)
library(gridBase)
test= data.frame(
x = c(1,2,3),
y = c(12,10,3),
n = c(75,76,73)
)
par(mar = c(13,5,2,3))
plot(test$y ~ test$x,type="b", ann=F)
for (i in 1:nrow(test))
{
X=grconvertX(i , from="user", to="ndc")
grid.text(x=X, y =0.2, label=paste("GRID.text at\nuser.x=", i, "\n", "ndc.x=", (signif( X, 5)) ) )
grid.lines(x=c(X, X), y = c(0.28, 0.33) )
}
#add some code to save as PDF ...
该代码基于我之前的一篇文章中的解决方案:混合 X 和 Y 坐标系。您可以看到原始绘图中的 x 坐标如何转换为 ndc。这种方法的优点是我可以使用 Y 的设备坐标。
我以为我可以轻松地做同样的事情ggplot2(并且可能在lattice).
library(ggplot2)
graphics.off() # close graphics windows
qplot(x=x, y=y, data=test)+geom_line()+ opts(plot.margin = unit(c(1,3,8,1), "lines"))
for (i in 1:nrow(test))
{
X=grconvertX(i , from="user", to="ndc")
grid.text(x=X, y =0.2, label=paste("GRID.text at\nuser.x=", i, "\n", "ndc.x=", (signif( X, 5)) ) )
grid.lines(x=c(X, X), y = c(0.28, 0.33) )
}
#add some code to save as PDF...
但是,它无法正常工作。坐标好像有点偏差。垂直线和文本与绘图上的刻度标签不对应。有人能告诉我如何修复它吗?预先非常感谢。