在gglot2中将SVG图像用作符号 [英] Use SVG images as symbols in gglot2
问题描述
我想将存储在外部文件(例如SVG)中的矢量图形用作 ggplot2
图中的绘图符号.例如按照grImport插图的示例进行操作(图8)
此示例导入自定义shapefile,然后使用 lattice
例如
xyplot(V8〜V7,data = flower,xlab ="Height",ylab =分开距离",panel = function(x,y,...){grid.symbols(PSflower,x,y,units ="native",大小=单位(5,"mm"))})
来自 grImport
包的 grid.symbols()
,而 PSflower
是由 grImport导入其他位置的Picture对象
ggimage
包接近完成此操作,但是它将图像转换为绘图以下的栅格,这是我要避免的事情.
有什么办法可以在 ggplot2
中实现类似的功能吗?
标记
这是我想出的解决方案-效果很好.您也可以使用 grImport
做类似的技巧.关键是要确保grob的标准化绘图坐标与ggplot的原始坐标相匹配.
#Setup图书馆(grImport2)库(ggplot2)图书馆(秤)src.file<-system.file("SVG","lwd-rsvg.svg",package ="grImport2")img<-readPicture(src.file)#现在创建一些数据d<-data.frame(x = 1:5,y = 1:5)#需要指定绘图的xlims和ylims-这可以让我们计算#normalized绘图坐标xlims<-c(0,6)ylims<-c(0,6)#使用symbolGrob创建绘图点sym.grob<-symbolsGrob(img,x = rescale(d $ x,from = xlims),y = rescale(d $ y,from = ylims),default.units ="npc",大小= 0.3)#阴谋ggplot(d,aes(x,y))+geom_point()+注解_自定义(sym.grob)+coord_cartesian(xlim = xlims,ylim = ylims,expand = FALSE)#别忘了这个!
I would like to use vector graphics stored in external files (e.g. SVG) as my plotting symbols in a ggplot2
figure. e.g. following this example from the grImport vignette (Fig. 8) https://cran.r-project.org/web/packages/grImport/vignettes/import.pdf
This example imports a custom shapefile and then plots it using lattice
e.g.
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"))})
with grid.symbols()
coming from the grImport
package and PSflower
being a Picture object imported elsewhere by grImport
.
The ggimage
package gets close to doing this, but it converts the image to a raster below plotting, which is what I'm trying to avoid.
Is there any way I could implement something similar in ggplot2
?
Mark
This is the solution that I came up with - seems to work pretty well. You can also do a similar trick with grImport
. The key is making sure that the normalised plot coordinates of the grob matches up with the native coordinates of 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!
这篇关于在gglot2中将SVG图像用作符号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!