R/gg.sn.R

Defines functions plot2D.SymmModulated plot.selm plot.fitdistr.grouped plot.SECdistrBv plot.SECdistrMv plot.SECdistrUv

Documented in plot2D.SymmModulated plot.fitdistr.grouped plot.SECdistrMv plot.SECdistrUv plot.selm

#  file gg.sn/R/gg.sn.R  
#  This file is a component of the package 'gg.sn' for R
#  copyright (C) 2022-2026 Adelchi Azzalini
#
#
plot.SECdistrUv <- function(x, range, probs, main, npt=251, data=NULL, plot.it=TRUE, ...)
{# plot density of object x (class SECdistrUv) using ggplot2
  obj <- x
  h <- label <- NULL # makes no sense, but it avoids NOTE at pkg check stage
  lc.family <- tolower(slot(obj, "family"))
  if(lc.family == "esn") lc.family <- "sn"
  dp <- slot(obj, "dp")
  d.fn <- get(paste("d", lc.family, sep=""), inherits = TRUE)
  q.fn <- get(paste("q", lc.family, sep=""), inherits = TRUE)
  if(missing(probs)) probs <- c(0.05, 0.25, 0.5, 0.75, 0.95)
  if(!is.numeric(data)) data <- NULL
  q <- if(is.null(probs)) NULL else q.fn(probs, dp=dp)
  col.annote <- "gray70"
  if(missing(range)) {
    q0 <- q.fn(c(0.05, 0.2, 0.8, 0.95), dp=dp)
    dq <- diff(q0)
    range <- c(q0[1]- 1.5*dq[1], q0[length(q0)] +  1.5*dq[length(dq)])
    if(!is.null(q)) {
      range[1] <- min(range[1], min(q))
      range[2] <- max(range[2], max(q))
      }
    if(!is.null(data)) {
      range[1] <- min(range[1], min(data))
      range[2] <- max(range[2], max(data))
    }}
  dots <- list(...)
  nmdots <- names(dots)  
  topline <- if(obj@name == "") "" else	
    paste("Probability density of ", obj@name, "\n", sep="")
  if(missing(main))  main <- paste(topline, obj@family," distribution",
     ", dp = (",paste(format(dp), collapse=", "),")",sep="") 
  x <- seq(min(range), max(range), length=npt)
  pdf <- d.fn(x, dp=dp)
  xLab <- if("xlab" %in% nmdots) dots$xlab else slot(obj, "name")
  yLab <- if("ylab" %in% nmdots) dots$ylab else "probability density"
  yLim <- if("ylim" %in% nmdots) dots$ylim else c(0, max(pdf))
  col  <- if("col" %in% nmdots) dots$col else "blue"
  lty  <- if("lty" %in% nmdots) dots$lty else par("lty")
  lwd  <- if("lwd" %in% nmdots) dots$lwd else par("lwd")*0.5
  pdf.df <- data.frame(x=x, pdf=pdf, zero=0)
  gg <- (ggplot(data=pdf.df, aes(x, pdf)) + xlab(xLab) + ylab(yLab)
         + xlim(range[1], range[2]) 
         + ylim(yLim[1], yLim[2])
         + geom_line(colour=col, linetype=lty, linewidth=lwd) 
         + geom_abline(intercept=0, slope=0, colour="gray80")
        )
  if(!is.null(q)) {
    q.df <- data.frame(q, h=rep(max(pdf)/100, length(q)), label=format(probs))
    # browser()
    gg <- (gg 
            + geom_point(data=q.df, aes(q, h), pch=6, size=1, colour=col.annote) 
            + geom_text(data=q.df, aes(q, h, label=label), colour=col.annote,
                size=3, vjust = "outward", nudge_y=-q.df$h)
            )
    }
  if(!is.null(data)) {
    side <- if(is.null(q)) "b" else "t"  
    data.df <- data.frame(x=c(data))
    gg <- gg + geom_rug(data=data.df, aes(x,x), sides=side, colour=col.annote)
    }
  if (!is.null(main)) {
    # font.m <- if("font.main" %in% nmdots) dots$font.main else par("font.main") 
    # cex.m <- if("cex.main" %in% nmdots) dots$cex.main else par("cex.main") 
    ### title(main, line=2, cex.main=cex.m, font.main=font.m)
    gg <- gg + labs(title=main)
    }  
  if(plot.it) print(gg)          
  invisible(list(object=obj, x=x, density=pdf, gg.obj=gg))
}
#----------------------
      
plot.SECdistrMv <- function(x, range, probs, npt, landmarks="auto",  main, 
      comp, compLabs, data = NULL, data.par=NULL, gap = 0.5, plot.it=TRUE, ...) 
{# plot density of object of class "SECdistrMv"  
  obj <- x
  if(slot(obj, "class") != "SECdistrMv") stop("object of wrong class")
  dp <- slot(obj, "dp")
  d <- length(dp$xi)
  if(missing(comp)) comp <- seq(1, d) 
  if(!all(comp %in% seq(1,d))) stop("illegal 'comp' value(s)")
  pd <- length(comp) # actual plotting dimension
  pobj <- if(pd == d) obj else marginalSECdistr(obj, comp=comp, drop=FALSE)
  name.pobj <- slot(obj, "name")
  if(pd < d) name.pobj <- paste(name.pobj,"[", paste(comp, collapse=","), "]", sep="")
  if(missing(probs)) probs <- c(0.25, 0.50, 0.75, 0.95)    
  if(any(probs <= 0) | any(probs >= 1)) stop("probs must be within (0,1)") 
  if(missing(npt)) npt <- rep(101, pd)
  if(missing(main))  { main <- if(pd == 1 | pd == 2)
      paste("Density function of", name.pobj) else
      paste("Bivariate densities of", name.pobj) 
      }
  compNames <- slot(pobj, "compNames")
  if(missing(compLabs)) compLabs <- compNames
  if(length(compLabs) != pd) stop("wrong length of 'compLabs' vector")
  family <- toupper(obj@family)
  lc.family <- tolower(family)
  if(lc.family == "esn") lc.family <- "sn"
  if(missing(range)) {
    range <- matrix(NA, 2, pd)
    q.fn <- get(paste("q", lc.family, sep=""), inherits=TRUE)
    for(j in 1:pd) {
      # 2026-05-15: next block of lines has been modified 
      marg <- marginalSECdistr(pobj, comp=j, drop=TRUE)
      q <- q.fn(c(0.01, 0.99), dp=marg@dp)
      range[,j] <- range(pretty(q))      
      if(!is.null(data)) {
        # q <- quantile(data[,j], probs=c(0.005, 0.995))
        range[1,j] <- min(range[1,j], min(data[,j]))
        range[2,j] <- max(range[2,j], max(data[,j]))
        range[,j] <- range(pretty(range[,j]))
        }
      }
    }
  dots <- list(...)
  nmdots <- names(dots)  
  col <- if("col" %in% nmdots) dots$col else "blue"
  lty <- if("lty" %in% nmdots) dots$lty else par("lty")
  lwd <- if("lwd" %in% nmdots) dots$lwd else par("lwd")*0.5
  cex <- if("cex" %in% nmdots) dots$cex else par("cex")
  pch <- if("pch" %in% nmdots) dots$cex else par("pch")
  
  if(pd == 1) {  
    message("Since dimension=1, plot as a univariate distribution")
    objUv <- marginalSECdistr(pobj, comp=comp, drop=TRUE)
    out <- plot(objUv, data=data, ...)
    }
  if(pd == 2) {
    p <- plot.SECdistrBv(pobj, range, probs, npt, compNames,  
                           compLabs, landmarks, data, data.par, main, ...)
    if(plot.it) print(p$gg.obj)                       
    out <- list(object=pobj, gg.obj=p$gg.obj)
    } 
  if(pd > 2) {
    out <- list(object=pobj)
    count <- 1
    for (i in comp) 
      for (j in comp) {
        count <- count + 1
        if(i == j) {
          span <- range[,i]
          variable.df <- data.frame(x=span, y=span, label=compLabs[i]) 
          v.name <- compLabs[i]
          # if(!is.null(main)) v.name <- paste(main, v.name, sep ="\n")
          gg.i <- (ggplot(data=variable.df, aes(x=x, y=x)) 
                 + xlim(span) + ylim(span)
                 + xlab(NULL) + ylab(NULL)
                 # + coord_cartesian(clip="off")
                 + annotate("text", label=v.name, colour='blue', size=5,
                     x=mean(span), # xmin=min(span), xmax=max(span),
                     y=mean(span)) # ymin=min(span), ymax=max(span))
                 + theme(panel.grid.minor = element_blank())   
                 + theme(panel.grid.major = element_blank())   
                 # + theme_classic()
                )
                
          out[[count]] <- list()
          names(out)[count] <- paste("diagonal component", compNames[i])
          gg.all <- if(i==1) gg.i else {gg.all + gg.i}
        } else {
        ji <- c(j,i)  
        marg <- marginalSECdistr(pobj, comp=ji) 
        plot.ji <- plot.SECdistrBv(x=marg, range=range[,ji], probs=probs,
                npt=npt[ji], compNames= compNames[ji], compLabs=NULL, 
                landmarks=landmarks, data=data[,ji],  data.par=data.par, 
                main=NULL, ...)   
        out[[count]] <- plot.ji
        names(out)[count] <- paste("plot of components (", j, ",", i, ")")
        # if(i==comp[1]) axis(3) ; if(j==length(comp)) axis(4)
        # if(j==comp[1]) axis(2) ; if(i==length(comp)) axis(1)    
        gg.all <- (gg.all + plot.ji$gg.obj 
                   # +  theme(axis.ticks = element_line(size = 0), 
                   #          axis.text=element_text(size=0))
                  )  
        }
      }
    gg.all <- (gg.all + plot_layout(ncol=pd, nrow=pd) 
               + plot_annotation(title=main, 
                  theme = theme(plot.title = element_text(size = cex)))
               )
    if(plot.it) print(gg.all)
    out$gg.obj <- gg.all  
    }
  invisible(out)
}
#----------------------
plot.SECdistrBv <- function(x, range, probs, npt=rep(101,2), compNames,   
             compLabs, landmarks, data=NULL, data.par, main, ...)
{# builds plot of a BiVariate SEC distribution, but does NOT actually plot it
  obj <- x
  y <- label <- NULL # makes no sense, but it avoids NOTE at pkg check stage
  dp <- slot(obj, "dp")
  family <- slot(obj, "family")
  lc.family <- tolower(family)
  if(lc.family == "esn") lc.family <- "sn"
  d.fn <- get(paste("dm", lc.family, sep=""), inherits=TRUE) # density funct
  n1 <- npt[1]
  n2 <- npt[2]
  x1 <- seq(min(range[,1]), max(range[,1]), length=n1)
  x2 <- seq(min(range[,2]), max(range[,2]), length=n2)
  x1.x2 <- cbind(rep(x1, n2), as.vector(matrix(x2, n1, n2, byrow=TRUE)))
  X <- matrix(x1.x2, n1 * n2, 2, byrow = FALSE)
  # pdf <- matrix(d.fn(X, dp=dp), n1, n2)
  pdf.col <- d.fn(X, dp=dp)
  pdf <-  matrix(pdf.col, n1, n2)
  Omega <- dp[[2]]
  Omega.bar <- cov2cor(Omega)
  alpha <- dp[[3]]
  alpha.star <- sqrt(sum(alpha * as.vector(Omega.bar %*% alpha)))
  omega <- sqrt(diag(Omega))
  if(lc.family == "sn") {
    k.tau <- if (length(dp) == 4) (zeta(2,dp[[4]])*pi)^2/4 else 1
    log.levels <- (log(1-probs) - log(2*pi)- 0.5*log(1-Omega.bar[1,2]^2)
                   + k.tau * log(1+exp(-1.544/alpha.star))) - sum(log(omega))
    }
  if(lc.family == "st" | lc.family == "sc") {
    nu <- if(lc.family == "st") obj@dp[[4]] else 1
    l.nu <- (-1.3/nu - 4.93)
    if(alpha.star > 0) {
      h <- 100 * log(exp(((1.005*alpha.star-0.045)* l.nu -1.5)/alpha.star)+1) 
      K <-  h *(1.005*alpha.star-0.1)*(1+nu)/(alpha.star * nu) }  else K <- 0
    qF <- qf(probs, 2, nu)
    log.levels <- (lgamma(nu/2+1) -lgamma(nu/2) - log(pi*nu) 
           -0.5*log(1-Omega.bar[1,2]^2) - (nu/2+1)*log(2*qF/nu + 1)  + K
           -sum(log(omega)))
    } 
  oo <- options()
  on.exit(options(oo))
  d.levels <- exp(log.levels)  
  names(d.levels) <- as.character(probs)
  pdf.df <- data.frame(x=X[,1], y=X[,2], pdf=pdf.col)
  dots <- list(...)
  nmdots <- names(dots)  
  xLab <- if("xlab" %in% nmdots) dots$xlab else slot(obj, "name")
  yLab <- if("ylab" %in% nmdots) dots$ylab else "probability density"
  yLim <- if("ylim" %in% nmdots) dots$ylim else c(0, max(pdf))
  col  <- if("col" %in% nmdots) dots$col else "blue"
  lty  <- if("lty" %in% nmdots) dots$lty else par("lty")
  lwd  <- if("lwd" %in% nmdots) dots$lwd else par("lwd")*0.5
  gg <- (ggplot(pdf.df, aes(x = x, y = y, z = pdf)) 
           + geom_contour(breaks=d.levels, colour=col, linetype=lty, linewidth=lwd)  
           + xlab(compLabs[1]) + ylab(compLabs[2]) 
           + xlim(range[,1]) + ylim(range[,2])
           # + theme(plot.margin=unit(rep(0,4), "pt"))
        )
  # to put labels on contour curves, use geom_label_contour {metR} (?)      
  if(!is.null(data)) {
    col <- if(!is.null(data.par$col)) data.par$col else par()$col
    pch <- if(!is.null(data.par$pch)) data.par$pch else par()$pch
    cex <- if(!is.null(data.par$cex)) data.par$cex else par()$cex
    data.df <- data.frame(x=data[,1], y=data[,2])
    # non si capisce perché voglia aes(...z=NULL), ma altrimenti non va!
    gg <- gg + geom_point(data=data.df, aes(x=data[,1], y=data[,2], z=NULL), 
           colour=col, size=cex, shape=pch)
    # if(!is.null(id.i <- data.par$id.i)) 
    #  text(data[id.i,1], data[id.i,2], id.i, cex=cex/1.5, pos=1)
    }
  if(landmarks != "") {
    if(landmarks == "auto") { 
      mean.type <-  "proper"  
      if(lc.family == "sc") mean.type <- "pseudo"      
      if(lc.family == "st") { if(dp[[4]] <= 1)  mean.type <- "pseudo"}
     }
    else 
    mean.type <- landmarks
    landmarks.label <- 
       c("origin", "mode", if(mean.type == "proper")  "mean" else "mean~")
    cp <- sn:::dp2cpMv(dp, family, cp.type=mean.type, upto=1)
    mode <- sn:::modeSECdistrMv(dp, family)
    x.pts <- c(dp$xi[1], mode[1], cp[[1]][1])
    y.pts <- c(dp$xi[2], mode[2], cp[[1]][2])
    # points(x.pts, y.pts, ...)
    points.df <- data.frame(x.pts, y.pts, label=landmarks.label)
    col <- if(!is.null(list(...)$col)) list(...)$col else par()$col
    gg <- (gg 
            + geom_point(data=points.df, aes(x=x.pts, y=y.pts, z=NULL), 
                size=2, shape=1, colour=col) 
            + geom_line(data=points.df, aes(x=x.pts, y=y.pts, z=NULL), 
                linetype=2, colour=col)
            +  geom_text(data=points.df, aes(x=x.pts, y=y.pts, z=NULL, label=label),
                 size=2, colour=col, hjust=1.2, vjust=0.5)  
          )         
    }  
  if(missing(main)) main <- paste("Density function of", slot(obj, "name"))  
  if(!is.null(main)) gg <- gg + labs(title=main)  
  cL <- grDevices::contourLines(x1, x2, pdf, levels=d.levels)
  if(length(cL) == length(probs)) 
    for(j in 1:length(probs)) cL[[j]]$prob <- probs[j]
  # print(gg)

  invisible(list(x=x1, y=x2, names=compNames, density=pdf, contourLines=cL, gg.obj=gg))
}    
#----------------------
plot.fitdistr.grouped <- function(x, freq=FALSE,   
   col="grey70", border="grey60", pdfcol="blue", main, sub=NULL,
   xlab, ylab, xlim, ylim, axes=TRUE, labels=FALSE, ...) 
{
  x.name <- deparse(substitute(x)) 
  object <- x
  y <- NULL # makes no sense, but it avoids NOTE at pkg check stage
  input <- object$input
  breaks <- if(all(is.finite(input$breaks))) input$breaks 
    else {
      warning("Inf(s) in 'breaks' are replaced by constructed values")
      input$breaks.plot }
  widths <- diff(breaks)     
  if(freq & var(widths) > 0 ) 
    stop("Arguments not suitable for plot.histogram; rather use 'freq=FALSE'")  
  width <- if(var(widths) == 0) widths[1] else NA
  dp <- object$param
  if(missing(xlim)) xlim <- range(pretty(breaks))  
  x <- x.pdf <- seq(xlim[1], xlim[2], length=201)
  if(missing(main)) main <- paste(
    x.name, ": histogram and fitted", object$family, "family for grouped data")
  if(missing(xlab)) xlab <- "" 
  if(missing(ylab)) ylab <- if(freq) "frequencies" else "density function" 
  pdf <- if(input$family == "t") dt((x - dp[1])/dp[2], dp[3]) 
    else {
      dp.char <- paste(paste("dp[", 1:length(dp), "]", sep=""),  collapse=", ")
      pdf.char <- paste("d", input$family.bn, "(x, ", dp.char, ")", sep="")
      eval(parse(text=pdf.char))
      }
  counts <- input$counts
  n <- sum(counts)
  rel.freq <- counts/(n*widths) 
  if(missing(ylim)) ylim=c(0, max(rel.freq, pdf) * if(freq) n*width else 1)   
  r <- structure(list(breaks = breaks, counts = counts, density = rel.freq, 
         mids = NULL, xname = NULL), class = "histogram")
  br <- r$breaks
  mids <- (br[-1]+br[-length(br)])/2
  y.distr <- if(freq) r$counts else r$density
  distr.df <- data.frame(x=mids, y=y.distr)
  gg <- (ggplot(distr.df, aes(x, y, width=diff(r$breaks))) 
        + geom_col(fill=col, col=border) + xlab(xlab) + ylab(ylab)
        )
  y.pdf <- if(freq) n*width*pdf else pdf  
  pdf.df <- data.frame(x.pdf, y.pdf)
  gg <- gg + geom_line(data=pdf.df, aes(x=x.pdf, y=y.pdf, width=NULL), colour=pdfcol)
  if(!is.null(main)) gg <- gg + labs(title=main, subtitle=sub) 
  print(gg)     
  invisible(list(hist=r, x=x.pdf, y=y.pdf, gg.obj=gg))
}
#------------------------------------------
# plotting selm, mselm objects
#
plot.selm <- function(x, param.type="CP", which = c(1:4), caption, 
    panel = NULL, main = "", 
    ask = prod(par("mfcol")) < length(which) && dev.interactive(), ..., 
    id.n = 3, labels.id = names(x@residuals.dp), 
    cex.id = 0.75, identline = TRUE, add.smooth = getOption("add.smooth"), 
    label.pos = c(4, 2), cex.caption = 1) 
{
    if(!(is(x, "selm"))) stop("object not of class 'selm'")
    show <- rep(FALSE, 4)
    show[which] <- TRUE
    dots <- list(...)
    nmdots <- names(dots)  
    p <- slot(x, "size")["p"]
    if(missing(caption))  { caption <-  if(p> 1) 
      c("Residuals vs Fitted Values", 
        "Residual values and fitted error distribution", 
        "Q-Q plot of (scaled DP residuals)^2",
        "P-P plot of (scaled DP residuals)^2") else
      c("Boxplot of observed values", 
        "Empirical values and fitted distribution", 
        "Q-Q plot of (scaled DP residuals)^2",
        "P-P plot of (scaled DP residuals)^2")}
    all.par <- slot(x, "param")
    y.name <- names(slot(x, "input")$model[1])
    param.type <- tolower(param.type)  
    param <- all.par[[param.type]]
    if(is.null(param)) { message(paste(
        "Requested param.type='", param.type, "' evaluates to NULL.", sep=""))
      if(param.type == "pseudo-cp" & x@family== "SN") 
        message("Pseudo-CP makes no sense for SN family")
      if(param.type == "cp" & x@family== "SC")
        message("CP makes no sense for SC family")
      if(param.type == "cp" & x@family== "ST")
        message("CP of ST family requires nu>4")  
      stop("Consider another choice of param.type (DP or pseudo-CP)")
      }
    r <- residuals(x, param.type)
    r.lab <- paste(toupper(param.type), "residuals")
    dp <- if(length(all.par$fixed) > 0) all.par$dp.complete else all.par$dp
    nu. <- switch(x@family, ST = dp[p+3], SN = Inf, SC=1)  
    rs <- slot(x,"residuals.dp")/dp[p+1]
    rs2 <- rs^2
    n <- slot(x, "size")["n.obs"]
    yh <- fitted(x, param.type)    
    w <- weights(x)
    if (!is.null(w)) {
        wind <- (w != 0)
        r <- r[wind]
        yh <- yh[wind]
        w <- w[wind]
        labels.id <- labels.id[wind]
    }
    else w <- rep(1,n)
    rw <- n*w/slot(x,"size")["nw.obs"]
    cex.pts <- rw * if("cex" %in% nmdots) dots$cex else par("cex")
    col <- if("col" %in% nmdots) dots$col else par("col")
    col.line <- "blue"
    if (is.null(id.n)) 
        id.n <- 0
    else {
        id.n <- as.integer(id.n)
        if (id.n < 0 || id.n > n) 
            stop(gettextf("'id.n' must be in {1,..,%d}", n), domain = NA)
    }
    if (id.n > 0) {
        if (is.null(labels.id)) 
            labels.id <- paste(1:n)
        iid <- 1:id.n
        # show.r <- sort.list(abs(r), decreasing = TRUE)[iid]        
        show.rs <- sort.list(rs2, decreasing = TRUE)[iid]
        # rs2.lab <- paste("(scaled DP residuals)^2")
        text.id <- function(xy.df, ind, adj.x = TRUE) {
          # xy.df deve contenere le variabili (x,y,labels.id)
            x <- xy.df[, "x"]
            y <- xy.df[, "y"]
            labpos <- if (adj.x) 
                label.pos[1 + as.numeric(x > mean(range(x)))]
            else 3
            geom_text(data=xy.df[,ind], aes(label=labels.id))
        }
    }
    one.fig <- prod(par("mfcol")) == 1 
    pause <- ask & one.fig & sum(which(which %in% 1:4) > 1) 
    do.plot <- function() {
        if(one.fig) 
        { if(pause) readline("Hit <Return> to see next plot:")
           print(gg)
         }    else { 
           gg.all <- if(exists("gg.all")) gg.all + gg  else gg } 
        invisible(if(one.fig) gg else gg.all)  
        }  
    if (show[1]) {
      if(all(is.na(r)) & p>1)  message(paste("CP residuals not available;",
         "consider param.type='DP' or 'pseudo-CP'"))
      else { 
        if(p == 1){ 
          y <- as.numeric(slot(x, "input")$model[[1]]) # (x@residuals.dp + x@fitted.values.dp)  
          y.df <- data.frame(x=y)
          gg <- (ggplot(data=y.df, aes(x)) 
                 + geom_boxplot(fill="gray80", col=col.line, outlier.colour=col.line)
                 + labs(y=NULL, x=y.name)
                 )
          }
        else { # p>1 
          ylim <- range(r, na.rm = TRUE)
          res.df <- data.frame(yh, r, labels.id=labels.id)
          gg <- (ggplot(res.df, aes(x=yh, y=r))
               + geom_point(colour=col, size=cex.id)
               + labs(x="Fitted values", y=r.lab)
               )
          if(add.smooth) (gg <- gg 
              + geom_smooth(method="loess", formula="y~x", span=2/3, se=FALSE)
               )
          if (id.n > 0) {
            # y.id <- r[show.rs]
            # id.labels <- as.character(show.rs)
            # browser()
            gg <- (gg 
                  + geom_text(data=res.df[show.rs,], aes(label=labels.id), 
                       size=3*cex.pts[show.rs], nudge_y = -diff(range(yh))/20)
                  )
          }
        gg <- gg + geom_abline(intercept=0, slope=0, colour="gray70", linetype=2)
        } }
      gg <- (gg + plot_annotation(title=caption[1], 
              theme = theme(plot.title = element_text(size = 12*cex.caption))))
      gg.all <- do.plot()               
      }
    if (show[2]) {
      if(all(is.na(r)) & p>1) message(
        "CP residuals not available; consider param.type='DP' or 'pseudo-CP'")
      else {
        if (p == 1){
          y <-  (x@residuals.dp + x@fitted.values.dp) 
          dp0 <- dp
          xlab= y.name }
        else {
          y <- r
          dp0 <- as.numeric(c(dp[1]-param[1], dp[-(1:p)]))
          xlab=r.lab
        }
        h <- hist(rep(y, w), plot=FALSE)
        extr <- extendrange(x=h$breaks)
        x.pts <- seq(max(extr), min(extr), length=251) 
        d.fn <- get(paste("d", tolower(x@family), sep=""), inherits = TRUE)
        pdf <- d.fn(x.pts, dp=dp0)
        hist.df <- data.frame(x=h$mids, y=h$density, width=diff(h$breaks))
        gg <- (ggplot(hist.df, aes(x, y, width=diff(h$breaks))) 
               + geom_col(fill="gray75", col="gray60")  
               + xlim(extr) + xlab(xlab)
        )
        data.df <- data.frame(x=y)
        gg <- gg + geom_rug(data=data.df, aes(x, y=NULL, width=NULL), colour=col, 
              length = unit(0.02, "npc"))
        pdf.df <- data.frame(x=x.pts, y= pdf)
        gg <- gg + geom_line(data=pdf.df, aes(x, y, width=NULL), colour=col.line)
        gg <- (gg + plot_annotation(title=caption[2], 
              theme = theme(plot.title = element_text(size = 12*cex.caption))))        
        gg.all <- do.plot()      
      }}
    if (show[3]) {
      ylim <- c(0, max(pretty(rs2)))
      q <- qf((1:n)/(n+1), 1, nu.)
      qq.df <- data.frame(x=q, y=sort(rs2), labels.id=labels.id)
      gg <- (ggplot(qq.df, aes(x,y)) 
             + geom_point(colour=col, size=cex.pts)
             + xlab("Theoretical values") + ylab("Empirical values")
             + ylim(ylim))
      if(identline) (gg <- gg 
            + geom_abline(intercept=0, slope=1, linetype=2, colour="gray70"))      
      if(id.n > 0){
         id.labels <- as.character(show.rs)  
         gg <- (gg + geom_text(data=qq.df[n+1-iid,], aes(label=labels.id), 
                       size=3*cex.id, nudge_y = -diff(range(rs2))/40)
                )
         }
      gg <- (gg + plot_annotation(title=caption[3], 
              theme = theme(plot.title = element_text(size = 12*cex.caption))))
      gg.all <- do.plot()           
    }
    if (show[4]) {
      p <- (1:n)/(n+1)
      pr <- pf(sort(rs2), 1, nu.)
      pp.df <- data.frame(x=p, y=pr, labels.id=labels.id)
      gg <- (ggplot(pp.df, aes(x,y))  + geom_point(colour=col, size=cex.pts)
            + xlab("Theoretical values") + ylab("Empirical values")
            + xlim(c(0,1)) + ylim(c(0,1))  )
      if(identline) (gg <- gg 
            + geom_abline(intercept=0, slope=1, linetype=2, colour="gray70"))      
      if(id.n > 0){
         id.labels <- as.character(show.rs)
         gg <- (gg + geom_text(data=pp.df[n+1-iid,], aes(label=labels.id), 
                       size=3*cex.id, nudge_y = -1/40)
                )
         }
      gg <- (gg + plot_annotation(title=caption[4], 
              theme = theme(plot.title = element_text(size = 12*cex.caption))))
      gg.all <- do.plot()             
    } 
    if(!one.fig)  {
       gg.all <- (gg.all + plot_layout(ncol=2) + plot_annotation(title=main))
       print(gg.all)
       }
    invisible()
  }

plot.mselm <- function (x, param.type="CP", which, caption, 
    panel = NULL, main = "", 
    # sub.caption = NULL, 
    ask = prod(par("mfcol")) < length(which) && dev.interactive(), ..., 
    id.n = 3, labels.id = names(x@residuals.dp), 
    cex.id = 0.75, identline = TRUE, add.smooth = getOption("add.smooth"), 
    label.pos = c(4, 2), cex.caption = 1) 
  { 
    p <- slot(x,"size")["p"]
    if(missing(which)) which <- if(p == 1) c(1,3,4) else 2:4
    show <- rep(FALSE, 4)
    show[which] <- TRUE
    if(!show[2]) param.type <- "DP"   # CP-residuals only used for show[2]
    lc.param.type <- tolower(param.type)
    param.type <- switch(lc.param.type, 
      "dp"="DP", "op"="OP", "cp"="CP", "pseudo-cp"="pseudo-CP")  
    if(param.type == "OP") stop("this method does not support OP option")
    if(missing(caption)) caption <- 
       c("Observed values and fitted distribution", 
       paste("Distribution of", param.type, "residual values"),
       "Q-Q plot of Mahalanobis distances",
       "P-P plot of Mahalanobis distances")
    all.par <- slot(x, "param")
    param <- all.par[[lc.param.type]]
    dots <- list(...)
    nmdots <- names(dots)  
    if(is.null(param)) { message(paste(
        "Requested param.type='", param.type, "' evaluates to NULL.", sep=""))
      if(param.type == "pseudo-cp" & x@family== "SN") 
        message("Pseudo-CP makes no sense for SN family")
      if(param.type == "cp" & x@family== "SC")
        message("CP makes no sense for SC family")
      if(param.type == "cp" & x@family== "ST")
        message("CP of ST family requires nu>4")  
      stop("Consider another choice of param.type, e.g. param.type='DP'")
      }
    r <- residuals(x, lc.param.type)
    r.lab <- paste(param.type, "residuals")
    dp <- if(length(all.par$fixed) > 0) all.par$dp.complete else all.par$dp
    cp <- dp2cp(dp, family=x@family, cp.type="auto") 
    nu. <- switch(x@family, ST = dp$nu, SN = Inf, SC=1)     
    n <- slot(x,"size")["n.obs"]
    d  <- x@size["d"]
    yh <- fitted(x, param.type)    
    w <- weights(x)
    if (!is.null(w)) {
        wind <- w != 0
        r <- r[wind]
        yh <- yh[wind]
        w <- w[wind]
        labels.id <- labels.id[wind]
    }
    else w <- rep(1,n)
    rw <- n*w/slot(x,"size")["nw.obs"]
    col <- if("col" %in% nmdots) dots$col else par("col")
    pch <- if("pch" %in% nmdots) dots$pch else par("pch")
    cex.pts <- rw * if("cex" %in% nmdots) dots$cex else par("cex")
    if (is.null(id.n)) 
        id.n <- 0
    else {
        id.n <- as.integer(id.n)
        if (id.n < 0 || id.n > n) 
            stop(gettextf("'id.n' must be in {1,..,%d}", n), domain = NA)
    }
    Omega.inv <- solve(dp$Omega)
    r.dp <- t(slot(x, "residuals.dp"))
    rs2 <- colSums((Omega.inv %*% r.dp) * r.dp)
    if (id.n > 0) {
		if (is.null(labels.id)) labels.id <- paste(1:n)
		iid <- 1:id.n
		show.r <- sort.list(abs(r), decreasing = TRUE)[iid]		
		show.rs <- sort.list(rs2, decreasing = TRUE)[iid]
		text.id <- function(xy.df, ind, adj.x = TRUE) {
		    # xy.df deve contenere le variabili (x,y,labels.id)
	        x <- xy.df[, "x"]
            y <- xy.df[, "y"]
            labpos <- if (adj.x) 
                label.pos[1 + as.numeric(x > mean(range(x)))]
            else 3
            geom_text(data=xy.df[,ind], aes(label=labels.id))			
		} 
      } else show.rs <- NULL
    one.fig <- prod(par("mfcol")) == 1
    pause <- ask & one.fig & sum(which(which %in% 1:4) > 1) 
    do.plot <- function() {
        if(one.fig) 
        { if(pause) readline("Hit <Return> to see next plot:")
           print(gg)
         }    else { 
           gg.all <- if(exists("gg.all")) gg.all + gg  else gg } 
        invisible(if(one.fig) gg else gg.all)  
        }  
    if (show[1]) { # data scatter matrix and fitted curves (only if p=1)
      if(p == 1) {
        y <- (x@residuals.dp + x@fitted.values.dp)  
        fitted.distr <- makeSECdistr(dp, family=slot(x, "family"), 
          name="fitted distribution", compNames=colnames(x@param$dp[[1]]))
        data.par <- list(col=dots$col, pch=pch, cex=cex.pts, id.i=show.rs)
        SECplot <- plot.SECdistrMv(fitted.distr, landmarks="", data=y, main=main, 
             data.par=data.par, plot.it=FALSE, ...)  # previously it included cex=sqrt(rw)
        # text.id(..) se d=1, ma se d>1 si deve fare per ogni pannello (?!)
        gg <- SECplot$gg.obj
        gg <- (gg + plot_annotation(title=caption[1], 
              theme = theme(plot.title = element_text(size = 12*cex.caption))))     
        gg.all <- do.plot()         
        } else  
      message(paste("plot of (observed data, fitted distribution)",
              "makes no sense if covariates 'x' exist; consider 'which=2'"))
      }
    if (show[2]) { # scatter matrix of residuals and fitted curves
      dp0 <- dp
      dp0[[1]] <-  as.numeric((dp[[1]]-param[[1]])[1,])
      data.par <- list(col=dots$col, pch=dots$pch, cex=dots$cex, id.i=show.rs)
      resid.distr <- makeSECdistr(dp0, family=x@family, 
         name="Residual distribution", compNames=colnames(x@residuals.dp))
      SECplot <- plot.SECdistrMv(resid.distr, landmarks="", data=residuals(x, param.type), 
         main=main, data.par=data.par, plot.it=FALSE, ...)
      gg <-  SECplot$gg.obj   
      gg <- (gg + plot_annotation(title=caption[2], 
              theme = theme(plot.title = element_text(size = 12*cex.caption)))) 
      gg.all <- do.plot()                 
      }
    if (show[3]) { # QQ-plot
      q <- qf((1:n)/(n+1), d, nu.) * d
      ylim <- c(0, max(pretty(rs2)))
      qq.df <- data.frame(x=q, y=sort(rs2), labels.id=labels.id)
      gg <- (ggplot(qq.df, aes(x,y)) 
            + geom_point(colour=col, size=cex.pts, shape=pch)
            + xlab("Theoretical values") + ylab("Empirical values")
            + ylim(ylim))
      if(identline) (gg <- gg 
            + geom_abline(intercept=0, slope=1, linetype=2, colour="gray70"))      
      # if (one.fig) title(sub = sub.caption, ...)
      if(id.n > 0){
         id.labels <- as.character(show.rs)
         gg <- (gg + geom_text(data=qq.df[n+1-iid,], aes(label=labels.id), 
                       size=3*cex.pts[show.rs], nudge_y = -diff(range(rs2))/40)
                )
         }
      gg <- (gg + plot_annotation(title=caption[3], 
              theme = theme(plot.title = element_text(size = 12*cex.caption))))
     gg.all <- do.plot()        
      }
    if (show[4]) { # PP-plot
      p <- pf(rs2/d, d, nu.)
      p0 <- (1:n)/(n+1) 
      pp.df <- data.frame(x=p0, y=sort(p), labels.id=labels.id)
      gg <- (ggplot(pp.df, aes(x,y))  
            + geom_point(colour=col, size=cex.pts, shape=pch)
            + xlab("Theoretical values") + ylab("Empirical values")
            + xlim(c(0,1)) + ylim(c(0,1))  )
      if(identline) (gg <- gg 
            + geom_abline(intercept=0, slope=1, linetype=2, colour="gray70"))      
      # if (one.fig) title(sub = sub.caption, ...)
      if(id.n > 0){
         # text.id(q[n+1-iid], rs2[show.rs], show.rs) 
         id.labels <- as.character(show.rs)
         gg <- (gg + geom_text(data=pp.df[n+1-iid,], aes(label=labels.id), 
                       size=3*cex.pts[show.rs], nudge_y = -1/40)
                )
         }
      gg <- (gg + plot_annotation(title=caption[4], 
              theme = theme(plot.title = element_text(size = 12*cex.caption))))
      gg.all <- do.plot()     
      }         
    if(!one.fig)  {
       gg.all <- (gg.all + plot_layout(ncol=2) + plot_annotation(title=main))
       print(gg.all)
       } 
    invisible()
  }
 
#----------------------------

plot2D.SymmModulated <- function(range, npt=rep(101,2), xi=c(0,0), Omega, f0, 
  G0, w, par.f0, par.G0, odd="check", ...)
{
  if(ncol(Omega)!=2 || nrow(Omega) != 2 || length(xi) !=2) 
    stop("Wrong dimension(s) of xi and/or Omega")
  x <- y <- NULL ## To please R CMD check
  ## https://cran.r-project.org/web/packages/future/vignettes/future-4-issues.html
  n1 <- npt[1]
  n2 <- npt[2]
  x1 <- seq(min(range[,1]), max(range[,1]), length=n1)
  x2 <- seq(min(range[,2]), max(range[,2]), length=n2)
  x1.x2 <- cbind(rep(x1, n2), as.vector(matrix(x2, n1, n2, byrow=TRUE)))
  X <- matrix(x1.x2, n1 * n2, 2, byrow = FALSE)
  dots <- list(...)
  nw <- names(formals(w))[-1]
  if(missing(par.f0)) par.f0 <- NULL
  if(missing(par.G0)) par.G0 <- NULL
  pdf.col <- do.call(dmSymmModulated, c(list(x=X, xi=xi, Omega=Omega, f0=f0, 
    G0=G0, w=w, par.f0=par.f0, par.G0=par.G0, odd=odd, log=FALSE), dots[nw])) 
  pdf <- matrix(pdf.col, n1, n2)
  pdf.df <- data.frame(x=X[,1], y=X[,2], pdf=pdf.col)
  dots[nw] <- NULL
  gg <- (ggplot(pdf.df, aes(x = x, y = y, z = pdf)) 
           + geom_contour()  
           # + xlab(compLabs[1]) + ylab(compLabs[2]) 
           + xlim(range[,1]) + ylim(range[,2])
        )
  print(gg)      
  invisible(list(x=x1, y=x2, density=pdf, gg.obj=gg))
  }

Try the gg.sn package in your browser

Any scripts or data that you put into this service are public.

gg.sn documentation built on Dec. 2, 2026, 5:07 p.m.