我正尝试在我用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-graphic不会被绘制到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()。
发布于 2013-11-09 00:11:18
annotation_custom有很多buggy,也许它不能处理pictureGrob。您可以尝试以下技巧将grob添加到gtable中,
library(ggplot2)
library(gtable)
p <- qplot(1,1) + theme(panel.background=element_rect(fill=NA))
g <- ggplotGrob(p)
pos <- gtable_filter(g, "panel", trim=FALSE)$layout
g <- with(pos, gtable_add_grob(g, test.grob, t, l, b, r, z-1))
grid.newpage()
grid.draw(g)

https://stackoverflow.com/questions/19846546
复制相似问题