sfcheung/semptools

A function to "expand" or "contract" a diagram

sfcheung opened this issue · 1 comments

Note

This function will do something like the following example. Can be used when the resulting diagram has too much blank area.;

Perhaps we can also write a function to shift the center of a diagram.

library(semptools)
library(lavaan)
#> This is lavaan 0.6-16
#> lavaan is FREE software! Please report any bugs.
library(semPlot)

expand_layout <- function(layout,
                          left = 1,
                          top = 1,
                          right = 1,
                          bottom = 1) {
    i_left   <- layout[, 1] < 0
    i_top    <- layout[, 2] > 0
    i_right  <- layout[, 1] > 0
    i_bottom <- layout[, 2] < 0
    layout[i_left,   1] <- layout[i_left,   1] * left
    layout[i_top,    2] <- layout[i_top,    2] * top
    layout[i_right,  1] <- layout[i_right,  1] * right
    layout[i_bottom, 2] <- layout[i_bottom, 2] * bottom
    layout
  }

mod <-
  'f1 =~ x01 + x02 + x03
   f3 =~ x08 + x09 + x10
   f4 =~ x11 + x12 + x13 + x14
   f3 ~ f1 + x04
   f4 ~ f3 + x05'
fit_sem <- lavaan::sem(mod, sem_example)
p <- semPaths(fit_sem, whatLabels="est",
        sizeMan = 5,
        nCharNodes = 0, nCharEdges = 0,
        edge.width = 0.8, node.width = 0.7,
        edge.label.cex = 0.6,
        mar = c(10,10,10,10),
        DoNotPlot = TRUE)
indicator_order  <- c("x04", "x05", "x01", "x02", "x03",
                      "x11", "x12", "x13", "x14", "x08", "x09", "x10")
indicator_factor <- c("x04", "x05", "f1",  "f1",  "f1",
                      "f4",  "f4",  "f4",  "f4",  "f3",  "f3",  "f3")
factor_layout <- matrix(c( "f1",  "f3", "f4",
                          "x04", "x05",  NA), byrow = TRUE, 2, 3)
factor_point_to <- matrix(c("left", "up", "right",
                                NA,   NA,      NA), byrow = TRUE, 2, 3)
p2 <- set_sem_layout(p,
                    indicator_order = indicator_order,
                    indicator_factor = indicator_factor,
                    factor_layout = factor_layout,
                    factor_point_to = factor_point_to)

plot(p2)
rect(-1, -1, 1, 1)
rect(-1.5, -1.5, 1.5, 1.5)

p3 <- p2
p3$layout <- expand_layout(p3$layout,
                           bottom = 2)
plot(p3)
rect(-1, -1, 1, 1)
rect(-1.5, -1.5, 1.5, 1.5)

Created on 2023-10-15 with reprex v2.0.2

Added rescale_layout() in 0.2.11.1.

#153