skellpco - 5 months ago 37

R Question

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)))

Answer

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