在 glot2 中使用 SVG 图像作为符号

Mar*_*yne 5 r ggplot2 grimport ggimage

我想使用存储在外部文件(例如 SVG)中的矢量图形作为图中的绘图符号ggplot2。例如,按照 grImport vignette 中的示例(图 8)https://cran.r-project.org/web/packages/grImport/vignettes/import.pdf

在此输入图像描述

此示例导入​​自定义 shapefile,然后使用lattice例如绘制它

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"))})
Run Code Online (Sandbox Code Playgroud)

grid.symbols()来自grImport包并且是PSflower由 . 在别处导入的 Picture 对象grImport

ggimage包接近执行此操作,但它将图像转换为绘图下方的光栅,这是我试图避免的。

有什么方法可以实现类似的东西ggplot2吗?

标记

Mar*_*yne 2

这是我想出的解决方案 - 似乎效果很好。您也可以使用 执行类似的操作grImport。关键是确保 grob 的归一化绘图坐标与 ggplot 的本机坐标相匹配。

#Setup
library(grImport2)
library(ggplot2)
library(scales)
src.file <- system.file("SVG", "lwd-rsvg.svg", package="grImport2")
img <- readPicture(src.file)

#Now createa some data
d <- data.frame(x=1:5,y=1:5)

#Need to specify xlims and ylims of plot - this lets us calculate the
#normalised plot coordinates
xlims <- c(0,6)
ylims <- c(0,6)

#Create the plot points using symbolsGrob
sym.grob <- symbolsGrob(img,
                        x=rescale(d$x,from=xlims),
                        y=rescale(d$y,from=ylims),
                        default.units="npc",
                        size=0.3)

#Plot
ggplot(d,aes(x,y))+
  geom_point()+
  annotation_custom(sym.grob)+
  coord_cartesian(xlim=xlims,ylim=ylims,expand=FALSE) #Don't forget this!
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述