1

I have a small network generated from the igraph package and I would like to plot this with an image in the background.

I used this document to find how to overlay an image over a graph:

library('png')
 
img.3 =readPNG("D:/R_Files/tiger.png") 

plot(net2, vertex.shape="raster", vertex.label=NA,
vertex.size=16, vertex.size2=16, edge.width=2)

rasterImage(img.3, xleft=0, xright=1.9, ybottom=0, ytop=1.5)

But this code snippet causes the image to hide the network plot, and I would like the network to be over the image, therefore acting as a background to the network. I haven't been able to find a way to do this - any ideas how or where to look for an answer?

Yolo_chicken
  • 1,221
  • 2
  • 12
  • 24
  • 1
    It's easier to help you if you include a simple [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) with sample input and desired output that can be used to test and verify possible solutions. – MrFlick Aug 24 '20 at 17:41

1 Answers1

1

You know how to put an image on top, so create the network graph as an image and put it on top. But be careful; you must make the background transparent.

Since you do not provide any graph or image, I will use something arbitrary. I have an image that is the outline of Africa and I will generate a random graph.

library('png')
library(igraph)

## Generate random graph, plot to png using transparent background.
set.seed(1234)
net2 = erdos.renyi.game(10, 0.28)
png("Network.png")
par(bg="transparent")
plot(net2, vertex.label=NA,
    vertex.size=16, vertex.size2=16, edge.width=2)
dev.off()

## Read in image background
net.img = readPNG("Network.png")
img.3 =readPNG("africa3.png")

## Create empty plot
plot(0, type = 'n', axes = FALSE, ann = FALSE, 
    xlim=c(0,1), ylim=c(0,1))

## Now add two images,  first the background, then the network overlay
rasterImage(img.3, xleft=-0.1, xright=1.1, ybottom=-0.1, ytop=1.1)
rasterImage(net.img,  xleft=-0.1, xright=1.1, ybottom=-0.1, ytop=1.1)

Africa Overlaid with a network

G5W
  • 36,531
  • 10
  • 47
  • 80