R igraph, how to plot vertices with mix of shapes and raster?

谁都会走 提交于 2019-12-06 08:44:33

问题


I'm trying to plot a graph with R and igraph, using a mix of shapes and raster images for the vertices. I've modified the igraph example below to reproduce my problem. Can someone see what is wrong? You'll need a png file to test the script.

library(png)
library(igraph)

img.1 <- readPNG(system.file("img", "Rlogo.png", package="png")) 

shapes <- setdiff(shapes(), "")

g <- make_ring(length(shapes))

V(g)$shape <- shapes

#change the rectangle variants to raster
V(g)$shape[grepl("rect",V(g)$shape)] <- "raster"
#give every vertex the same image, regardless of shape
V(g)$raster <- replicate(vcount(g), img.1, simplify=FALSE)

plot(g,
    vertex.size=15, vertex.size2=15,
    vertex.pie=lapply(shapes, function(x) if (x=="pie") 2:6 else 0),
    vertex.pie.color=list(heat.colors(5)))

回答1:


This seems to be one way, but it needs a bit of manual tweaking to fit the rasters.

library(png)
library(igraph)

# Your code
img.1 <- readPNG(system.file("img", "Rlogo.png", package="png")) 
shapes <- setdiff(shapes(), "")
g <- make_ring(length(shapes))
V(g)$shape <- shapes

# Change some shapes to user defined         
V(g)$shape[grepl("rect",V(g)$shape)] <- "myimg"

# Using idea from http://igraph.org/r/doc/shapes.html
# define function for image 
# manually tweaked the x any y to increase size of image
myimg <- function(coords, v=NULL, params) {
           vertex.size <- 1/200 * params("vertex", "size")
           if (length(vertex.size) != 1 && !is.null(v)) {
             vertex.size <- vertex.size[v]
           }
           rasterImage(img.1, 
             coords[,1]-vertex.size, coords[,2]-vertex.size, 
             coords[,1]+vertex.size, coords[,2]+vertex.size)
           }

# add shape
add_shape("myimg",  plot=myimg)

# plot
plot(g, vertex.size=seq(5, 5*length(shapes), 5), vertex.size2=seq(5, 5*length(shapes), 5)
    vertex.pie=lapply(shapes, function(x) if (x=="pie") 2:6 else 0),
    vertex.pie.color=list(heat.colors(5)))

To give

I dare say there is a more igraph approach to this



来源:https://stackoverflow.com/questions/40120912/r-igraph-how-to-plot-vertices-with-mix-of-shapes-and-raster

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!