Search code examples
rr-lavaanr-qgraph

qgraph: multiple images at nodes


I have recently been using the Lavaan package in R for Structural Equations Modeling and use the semPlot package, which seems to piggyback off of qgraph, in generating path diagrams.

I have found that qgraph has support for plotting images (such as jpeg and png) as nodes.

My question is whether it is possible, and if so how, to graph a different image for each node in a path diagram. I would love to be able to use pictures of my study's items to fill in for the manifest variables on my path diagram. Thanks!


Solution

  • and thank you for checking out semPlot (which is still in a very developmental state). You can certainly do this. Indeed semPlot piggybacks off qgraph, in fact it is basically a frontend to qgraph and returns a qgraph object. You can send arguments to qgraph or plot the result again with different arguments. For example:

    library("lavaan")
    
    # Example 5.8 from mplus user guide:
    Data <- read.table("http://www.statmodel.com/usersguide/chap5/ex5.8.dat")
    names(Data) <- c(paste("y", 1:6, sep=""),
                     paste("x", 1:3, sep=""))
    
    # Model:
    model.Lavaan <- 'f1 =~ y1 + y2 + y3
    f2 =~ y4 + y5 + y6
    f1 + f2 ~ x1 + x2 + x3 '
    
    # Run Lavaan:
    library("lavaan")
    fit <- lavaan:::cfa(model.Lavaan, data=Data, std.lv=TRUE)
    
    # Download R logo:
    download.file("http://cran.r-project.org/Rlogo.jpg", file <- tempfile(fileext = ".jpg"), 
                  mode = "wb")
    
    # Plot path diagram and store qgraph object:
    Graph <- semPaths(fit,title=FALSE, curvePivot = TRUE)
    
    # plot qgraph again with images:
    qgraph(Graph, images = file, labels = FALSE)
    

    If you want to use a different image per node, you can give images a vector contaning the file names of the images for each node in the order of the nodes. To find out the node order you can do:

    # To see which nodes are which:
    Graph$graphAttributes$Nodes$labels