【发布时间】:2013-11-07 20:57:03
【问题描述】:
我正在尝试在使用 WMS(Geoserver)创建的地图(矢量图形)上覆盖半透明的 ggplot 地图。
我可以使用 grImport 包(命令 PostScriptTrace、readPicture 和 pictureGrob)在 R 中导入 pdf。但现在我迷路了。我想将 ggplot 图像覆盖在 pdf 背景图像上。我可以指定 ggplot 使用 grob 作为背景图片吗?
感谢 baptiste 为我指明“annotation_custom()”的方向。 在他的帮助下,我设法为我的问题创建了一个更简单的示例:
library("cluster")
library("lattice")
library("ggplot2")
library("grImport")
sink("test.ps")
cat("%!PS\n")
cat("/petal {\n")
cat("newpath\n")
cat("0 0 moveto\n")
cat("-5 10 lineto\n")
cat("-10 20 10 20 5 10 curveto\n")
cat("5 10 lineto\n")
cat("closepath\n")
cat("0 setgray\n")
cat("fill\n")
cat("} def\n")
cat("20 20 translate\n")
cat("5 {\n")
cat("petal 72 rotate\n")
cat("} repeat\n")
cat("showpage")
sink()
PostScriptTrace("test.ps")
test.ps.xml <- readPicture("test.ps.xml")
test.grob <- pictureGrob(test.ps.xml)
# following the example from 'Importing Vector Graphics: The grImport Package for R' by Paul Murrell I can test the graphic and add the .ps to a lattice plot
xyplot(V8 ~ V7, data = flower,
xlab = "Height", ylab = "Distance Apart",
panel = function(x, y, ...) {
grid.symbols(test.ps.xml, x, y, units = "native", size = unit(5, "mm"))
}
)
# ... but I would like to add the .ps as a background image to a plot with ggplot2
polygon.df <- data.frame(
id = 1,
x = c(-60,60,60,-60,-60),
y = c(0,0,175,175,0)
)
ggplot() + annotation_custom(test.grob)+
geom_polygon(data=polygon.df, aes(x=x, y=y), alpha=.2, fill="blue") +
scale_x_continuous(limits=c(-70, 70), expand = c(0,0)) +
scale_y_continuous(limits=c(-10, 185), expand = c(0,0))
但 ps 图形并未绘制到 ggplot。我确定我错过了一些非常微不足道的事情。
编辑:以下确实显示了 grob:
qplot(x=polygon.df$x, y=polygon.df$y)+
annotation_custom(test.grob)
以下内容不显示 grob:
ggplot() + geom_point(data=polygon.df, aes(x=x, y=y)) +
annotation_custom(test.grob)
我不太明白为什么它用 qplot() 显示 grob,但用 ggplot() 不显示。
【问题讨论】:
-
你可以用
annotation_custom放置一个grob -
您好,感谢您的建议。我已经尝试过了,但失败了。我添加了一个最小的例子。如果我将 '+ annotation_custom(test.grob)' 添加到代码中,则绘图不会发生任何变化
-
不幸的是,这些 grobs 的行为似乎不符合标准
-
谢谢,我用“导入矢量图形:R 的 grImport 包 - Paul Murrell”中的一些示例测试了我的 grob。
library("cluster") xyplot(V8 ~ V7, data = flower, xlab = "Height", ylab = "Distance Apart", panel = function(x, y, ...) { grid.symbols(PSflower, x, y, units = "native", size = unit(5, "mm")) }) -
以上代码正确显示了grob。但是,我无法使用
annotation_custom在 ggplot 中显示甚至简单的 grobs。恐怕我不太明白如何使用annotation_custom。