如果您找到可以使用的 SVG 图像,也可以使用grImport
包以将文件转换为 XML,然后可以轻松使用 R 进行修改。
例如,如果您想使用这个文件,你可以添加一些fill
使用 Illustrator/Gimp 或其他任何工具对图像进行形状处理然后使用将其转换为 XMLgrImport:
library(grImport)
PostScriptTrace("yourimage.ps")
这将创建一个yourimage.ps.xml
文件。如果您愿意,可以修改ids
XML 中的填充路径节点的名称,以便更轻松地访问它们以更改颜色。
例如,我在 SVG 文件上制作了 14 个身体部位,并将它们的 id 更改为名称而不是数字,您可以在此处找到 XML:带有身体部位 XML 的人体 SVG
要改变身体部位的颜色,你只需改变rgb
的一部分fill
nodes:
library(grImport)
library(XML)
library(gridExtra)
#function to change the rgb color of the xml paths
changeColor<-function(bodypart,color){
node<-xpathSApply(doc, paste("//path[@id='",bodypart,"']/context/rgb",sep=""))[[1]]
rgbCol<-col2rgb(color)
xmlAttrs(node)["r"]=rgbCol[1]/255
xmlAttrs(node)["g"]=rgbCol[2]/255
xmlAttrs(node)["b"]=rgbCol[3]/255
}
#read the xml image
doc<-xmlParse("Human_body_front_and_side.ps.xml")
#these are the different parts you can change
bodyparts<-c("head","hand-right","hand-left","foot-left","foot-right","lowerleg-left","lowerleg-right",
"upperleg-left","upperleg-right","torso","forearm-right","forearm-left","upperarm-right","upperarm-left")
#color the bodyparts with random color
mapply(function(x,y){changeColor(x,y)},bodyparts,sample(colours(), 14))
#load the XML as a picture
body<-readPicture(saveXML(doc))
#plot it
grid.arrange(pictureGrob(body), ncol=1)
我得到这样的东西:
![enter image description here](https://i.stack.imgur.com/ApVdB.png)