首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在ggplot2中使用pdf/ps作为背景图片?

如何在ggplot2中使用pdf/ps作为背景图片?
EN

Stack Overflow用户
提问于 2013-11-08 04:57:03
回答 1查看 906关注 0票数 2

我正尝试在我用WMS (Geoserver)创建的地图(矢量图形)上叠加一个半透明的ggplot地图。

我可以用grImport包(命令PostScriptTrace、readPicture和pictureGrob)导入R中的pdf。但现在我迷路了。我想将ggplot图像覆盖在pdf背景图像上。我可以指定ggplot来使用grob作为背景图像吗?

感谢baptiste为我指明了"annotation_custom()“的方向。在他的帮助下,我成功地为我的问题创建了一个更简单的示例:

代码语言:javascript
复制
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:

代码语言:javascript
复制
qplot(x=polygon.df$x, y=polygon.df$y)+ 
annotation_custom(test.grob)

文件夹没有显示grob:

代码语言:javascript
复制
ggplot() + geom_point(data=polygon.df, aes(x=x, y=y)) +
annotation_custom(test.grob)

我不太明白为什么它可以用qplot()来显示grob,而不能用ggplot()。

EN

回答 1

Stack Overflow用户

发布于 2013-11-09 00:11:18

annotation_custom有很多buggy,也许它不能处理pictureGrob。您可以尝试以下技巧将grob添加到gtable中,

代码语言:javascript
复制
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)

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/19846546

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档