Search code examples
rplotr-lavaan

Overlays with lavaan and graph_sem


I am having trouble generating readable plots from Lavaan in R. I have a fitted model that I try to plot with graph_sem from the tidySEM library. The plots I generate have all of the independent variables overlaid which limits readability (please see attached sreenshot). I would like to have the dependent variable (called X1) on one layer, and all of the independent variables (X2-X6) on another one.

code:

library(lavaan)
library(tidySEM)

data = data.frame(replicate(7,sample(0:1,1000,rep=TRUE)))
head(data)

model <- '

# Model data here
X1 ~ X2 + X3 + X4 + X5  + X6

'

model_fit.sem <- sem(model, data=data, group = 'X7')
summary(model_fit.sem)

graph_sem(model_fit.sem, sig = 0.05)

Result: enter image description here


Solution

  • You can specify a layout in graph_sem

    library(lavaan)
    library(tidySEM)
    
    model <- 'X1 ~ X2 + X3 + X4 + X5 + X6'
    
    sem(model, data, group = "X7") %>%
      graph_sem(layout = get_layout("",   "",   "X1", "",   "",
                                    "",   "",   "",   "",   "",
                                    "X2", "X3", "X4", "X5", "X6", rows = 3))
    

    enter image description here