我在向iGraph中的顶点有条件地分配图像(png)时遇到了困难。例如,我想绘制如果col.2 =='a',则image =='1.png'。我已经能够将顶点绘制为png,但图像与顶点ID不正确对应。非常感谢任何帮助或建议!这是一个最小的例子:
#minimal example
#(1)plot graph.data frame from three unqiue columns ('col.1', 'col.2', 'col.3')
#(2)create two new columns to include png files ('nodes1.tmp', 'nodes2.tmp')
#(3)assign images to vertices conditional on categories ('Groups' and 'Members')
#required
library(igraph)
library(png)
#import data from files
my_data <- read.csv(file="my_data.csv")
#load two different sets of images
images_1 <- list.files("dir/folder1", pattern=".png$") #loads .pngs for groups
images_2 <- list.files("dir/folder2", pattern=".png$") #loads .pngs for members
#assign the vectors
col.1 <- my_data$[,1] #nodes (groups)
col.2 <- my_data$[,2] #nodes (members)
col.3 <- my_data$[,3] #weights (gender)
col.4 <- my_data$[,4] #subets (age)
#bind vectors to data.frame (two new cols for images will be added)
df1 <- data.frame(cbind(col.1, col.2, col.3, col.4))
#create image vectors
all_images <- cbind(images_1, images_2)
nodes1.tmp <- as.character(my_data$[,5]) # new col for groups images
nodes2.tmp <- as.character(my_data$[,6]) # new col for members images
#populate nodes1.tmp column with .pngs, conditional on col.1 (groups)
nodes1.tmp <- ifelse(col.1 %in% "Name1", images_1[1],
ifelse (col.1 %in% "Name2", images_1[2], NA))
#populate nodes2.tmp column with .pngs, conditional on col.2 (members)
nodes2.tmp <- ifelse(col.2=='a', images_1[1],
ifelse(col.2=='b', images_2[2],
ifelse(col.2=='c', images_2[3],
ifelse(col.2=='d', images_2[4],
ifelse(col.2=='e', images_2[5],
ifelse(col.2=='f', images_2[6], NA))))))
#read all pngs
all_rasters <- cbind(nodes1.tmp, nodes2.tmp)
rasters <- lapply(all_rasters, readPNG)
unlist(rasters)
#Subset df1 based on "Group1"
df2 <- subset(df1, df1$col.1 %in% "Group1")
#create graph data frame
df2.m <- as.matrix(df2)
#edge list from col.5 and col.6 (images columns)
g_edglst.1 <- graph.edgelist(df2.m[,c(5,6)], directed = F)
#weights from col.3 (gender)
E(g_edglst.1)$weight=as.character(g_edglst.1[,3])
V(g_edglst.1)$raster <- rasters[1:length(V(g_edglst.1))]
E(g_edglst.1)$color <- ifelse((g_edglst.1)$list.3 %in% "m", "red", "darkslategrey") #colour-code edges based on gender m/f
plot(g_edglst.1, vertex.label = V(g_edglst.1)$name, layout=layout.auto,
vertex.shape="raster")