R/IRPtoCMPRMP.R

Defines functions plotRMP_gg plotCMP_gg .plot_membership_profile plotLRD_gg plotLCD_gg .plot_student_distribution plotTRP_gg plotFRP_gg plotIRP_gg

Documented in plotCMP_gg plotFRP_gg plotIRP_gg plotLCD_gg plotLRD_gg .plot_membership_profile plotRMP_gg .plot_student_distribution plotTRP_gg

#' @title Plot Item Reference Profile (IRP) from exametrika
#'
#' @description
#' This function takes exametrika output as input and generates
#' Item Reference Profile (IRP) plots using ggplot2. IRP shows the
#' probability of a correct response for each item at each latent
#' class or rank level.
#'
#' @param data An object of class \code{c("exametrika", "LCA")},
#'   \code{c("exametrika", "LRA")}, or \code{c("exametrika", "LDLRA")}.
#' @param title Logical or character. If \code{TRUE} (default), display an
#'   auto-generated title. If \code{FALSE}, no title. If a character string,
#'   use it as a custom title (only for single-item plots).
#' @param colors Character vector. Color(s) for points and lines.
#'   If \code{NULL} (default), a colorblind-friendly palette is used.
#' @param linetype Character or numeric specifying the line type.
#'   Default is \code{"dashed"}.
#' @param show_legend Logical. If \code{TRUE}, display the legend.
#'   Default is \code{FALSE}.
#' @param legend_position Character. Position of the legend.
#'   One of \code{"right"} (default), \code{"top"}, \code{"bottom"},
#'   \code{"left"}, \code{"none"}.
#'
#' @return A list of ggplot objects, one for each item. Each plot shows the
#'   correct response rate across latent classes or ranks.
#'
#' @details
#' The Item Reference Profile visualizes how item difficulty varies across
#' latent classes (LCA) or ranks (LRA, LDLRA). Items with monotonically
#' increasing profiles indicate good discrimination between classes/ranks.
#'
#' @examplesIf requireNamespace("exametrika", quietly = TRUE)
#' library(exametrika)
#' result <- LRA(J15S500, nrank = 5)
#' plots <- plotIRP_gg(result)
#' plots[[1]] # Show IRP for the first item
#'
#' @seealso \code{\link{plotFRP_gg}}, \code{\link{plotTRP_gg}}
#'
#' @importFrom ggplot2 ggplot
#' @importFrom ggplot2 ylim
#' @importFrom ggplot2 geom_point
#' @importFrom ggplot2 geom_line
#' @importFrom ggplot2 scale_x_continuous
#' @importFrom ggplot2 labs theme
#' @export

plotIRP_gg <- function(data,
                       title = TRUE,
                       colors = NULL,
                       linetype = "dashed",
                       show_legend = FALSE,
                       legend_position = "right") {
  model_class <- .validate_exametrika(data, c("LCA", "LRA", "LDLRA"))
  xlabel <- if (model_class == "LCA") "Latent Class" else "Latent Rank"

  # Color setup
  if (is.null(colors)) {
    use_color <- .gg_exametrika_palette(1)[1]
  } else {
    use_color <- colors[1]
  }

  n_cls <- ncol(data$IRP)

  if (n_cls < 2 || n_cls > 20) {
    stop("Invalid number of classes or Ranks")
  }

  plots <- list()

  for (i in 1:nrow(data$IRP)) {
    x <- data.frame(
      CRR = c(data$IRP[i, ]),
      rank = c(1:n_cls)
    )

    # Title setup
    plot_title <- .resolve_title(title, paste0("Item Reference Profile, ", rownames(data$IRP)[i]))

    p <- ggplot(x, aes(x = rank, y = CRR)) +
      scale_y_continuous(limits = c(0, 1), breaks = seq(0, 1, 0.25)) +
      geom_point(color = use_color) +
      geom_line(linetype = linetype, color = use_color) +
      scale_x_continuous(breaks = seq(1, n_cls, 1)) +
      labs(
        title = plot_title,
        x = xlabel,
        y = "Correct Response Rate"
      )

    # Legend control
    p <- .apply_legend(p, show_legend, legend_position)

    plots[[i]] <- p
  }

  return(plots)
}


#' @title Plot Field Reference Profile (FRP) from exametrika
#'
#' @description
#' This function takes exametrika output as input and generates a
#' Field Reference Profile (FRP) plot using ggplot2. For binary data,
#' it displays correct response rates. For polytomous data, it shows
#' expected scores calculated using the specified statistic.
#'
#' @param data An object from exametrika: Biclustering, nominalBiclustering,
#'   ordinalBiclustering, ratedBiclustering, IRM, LDB, or BINET output.
#' @param stat Character. Statistic to use for polytomous data:
#'   \code{"mean"} (default), \code{"median"}, or \code{"mode"}.
#'   Ignored for binary data.
#' @param fields Integer vector specifying which fields to plot. Default is all fields.
#' @param title Logical or character. If \code{TRUE} (default), display automatic
#'   title. If \code{FALSE}, no title. If a character string, use it as the title.
#' @param colors Character vector. Colors for each field line.
#'   If \code{NULL} (default), uses the package default palette.
#' @param linetype Character or numeric. Line type for all lines.
#'   Default is \code{"solid"}.
#' @param show_legend Logical. If \code{TRUE} (default), display the legend.
#' @param legend_position Character. Position of the legend:
#'   \code{"right"} (default), \code{"top"}, \code{"bottom"},
#'   \code{"left"}, \code{"none"}.
#'
#' @return A single ggplot object with all selected fields.
#'
#' @details
#' The Field Reference Profile shows how response patterns vary across
#' latent classes/ranks for each field (cluster of items).
#'
#' For **binary data** (Biclustering, IRM, LDB, BINET):
#' \itemize{
#'   \item Y-axis: Correct Response Rate (0-1)
#'   \item Each line represents one field
#' }
#'
#' For **polytomous data** (nominalBiclustering, ordinalBiclustering, ratedBiclustering):
#' \itemize{
#'   \item Y-axis: Expected Score (calculated using \code{stat} parameter)
#'   \item \code{stat = "mean"}: Weighted average across categories (default)
#'   \item \code{stat = "median"}: Median category value
#'   \item \code{stat = "mode"}: Most probable category
#' }
#'
#' @examplesIf requireNamespace("exametrika", quietly = TRUE)
#' library(exametrika)
#'
#' # Binary biclustering
#' result_bin <- Biclustering(J35S515, ncls = 4, nfld = 3)
#' plot <- plotFRP_gg(result_bin)
#'
#' \donttest{
#' # Ordinal biclustering with mean (default)
#' result_ord <- Biclustering(J35S500, ncls = 4, nfld = 3)
#' plot_mean <- plotFRP_gg(result_ord, stat = "mean")
#'
#' # Using mode for polytomous data
#' plot_mode <- plotFRP_gg(result_ord,
#'   stat = "mode",
#'   title = "Field Reference Profile (Mode)",
#'   colors = c("red", "blue", "green")
#' )
#' }
#'
#' @seealso \code{\link{plotIRP_gg}}, \code{\link{plotTRP_gg}},
#'   \code{\link{plotCRV_gg}}, \code{\link{plotRRV_gg}}
#'
#' @importFrom ggplot2 ggplot aes geom_point geom_line scale_x_continuous scale_y_continuous labs theme scale_color_manual scale_linetype_manual
#' @export

plotFRP_gg <- function(data,
                       stat = "mean",
                       fields = NULL,
                       title = TRUE,
                       colors = NULL,
                       linetype = "solid",
                       show_legend = TRUE,
                       legend_position = "right") {
  # Class validation
  valid_classes <- c(
    "Biclustering", "nominalBiclustering", "ordinalBiclustering",
    "ratedBiclustering", "IRM", "LDB", "BINET"
  )
  .validate_exametrika(data, valid_classes)

  # Validate stat parameter
  if (!stat %in% c("mean", "median", "mode")) {
    stop("'stat' must be one of: 'mean', 'median', 'mode'")
  }

  # Check FRP data existence
  if (!"FRP" %in% names(data)) {
    stop("FRP data not found in the input object.")
  }

  # Data type detection: 2D (binary) or 3D (polytomous)
  is_polytomous <- length(dim(data$FRP)) == 3

  if (is_polytomous) {
    # === Polytomous data (nominalBiclustering, ordinalBiclustering) ===
    BCRM <- data$FRP # [field, class, category]
    nfld <- dim(BCRM)[1]
    ncls <- dim(BCRM)[2]
    maxQ <- dim(BCRM)[3]

    # Field selection
    if (is.null(fields)) {
      selected_fields <- 1:nfld
    } else {
      if (!is.numeric(fields) || any(fields < 1 | fields > nfld)) {
        stop("'fields' must be a numeric vector with values between 1 and ", nfld)
      }
      selected_fields <- fields
    }

    # Expected score calculation
    expected_scores <- matrix(0, nrow = length(selected_fields), ncol = ncls)
    rownames(expected_scores) <- paste0("Field ", selected_fields)

    for (idx in seq_along(selected_fields)) {
      f <- selected_fields[idx]
      for (cc in 1:ncls) {
        probs <- BCRM[f, cc, ] # Category probability vector
        categories <- 1:maxQ

        if (stat == "mean") {
          # Weighted average
          expected_scores[idx, cc] <- sum(categories * probs)
        } else if (stat == "median") {
          # Compute median from cumulative probabilities
          cum_probs <- cumsum(probs)
          median_cat <- min(which(cum_probs >= 0.5))
          expected_scores[idx, cc] <- median_cat
        } else if (stat == "mode") {
          # Mode (category with the highest probability)
          mode_cat <- which.max(probs)
          expected_scores[idx, cc] <- mode_cat
        }
      }
    }

    y_label <- switch(stat,
      "mean" = "Expected Score (Mean)",
      "median" = "Expected Score (Median)",
      "mode" = "Expected Score (Mode)"
    )
  } else {
    # === Binary data (Biclustering, IRM, LDB, BINET) ===
    FRP_matrix <- data$FRP # [field, class]
    nfld <- nrow(FRP_matrix)
    ncls <- ncol(FRP_matrix)

    # Field selection
    if (is.null(fields)) {
      selected_fields <- 1:nfld
    } else {
      if (!is.numeric(fields) || any(fields < 1 | fields > nfld)) {
        stop("'fields' must be a numeric vector with values between 1 and ", nfld)
      }
      selected_fields <- fields
    }

    expected_scores <- FRP_matrix[selected_fields, , drop = FALSE]
    rownames(expected_scores) <- paste0("Field ", selected_fields)
    y_label <- "Correct Response Rate"
  }

  # Build data frame
  plot_data_list <- list()
  for (idx in seq_along(selected_fields)) {
    for (cc in 1:ncls) {
      plot_data_list[[length(plot_data_list) + 1]] <- data.frame(
        Field = rownames(expected_scores)[idx],
        ClassRank = cc,
        Value = expected_scores[idx, cc]
      )
    }
  }
  long_data <- do.call(rbind, plot_data_list)

  # Convert Field to factor (preserve order)
  long_data$Field <- factor(long_data$Field, levels = unique(long_data$Field))

  # Color setup
  n_fields <- length(selected_fields)
  if (is.null(colors)) {
    colors <- .gg_exametrika_palette(n_fields)
  }

  # Get msg (Class or Rank)
  msg <- if ("msg" %in% names(data)) data$msg else "Class"

  # Build plot
  p <- ggplot(long_data, aes(x = ClassRank, y = Value, color = Field, group = Field)) +
    geom_line(linewidth = 0.8, linetype = linetype) +
    geom_point(size = 2) +
    scale_x_continuous(breaks = 1:ncls) +
    scale_y_continuous(breaks = seq(0, ceiling(max(long_data$Value)), by = 0.25)) +
    labs(
      x = paste("Latent", msg),
      y = y_label,
      color = "Field"
    )

  # Color scale setup
  p <- p + scale_color_manual(values = colors)

  # Title setup
  if (is.logical(title)) {
    if (title) {
      if (is_polytomous) {
        title_text <- paste0(
          "Field Reference Profile (",
          toupper(substring(stat, 1, 1)),
          substring(stat, 2), ")"
        )
      } else {
        title_text <- "Field Reference Profile"
      }
      p <- p + labs(title = title_text)
    }
  } else if (is.character(title)) {
    p <- p + labs(title = title)
  }

  # Legend control
  p <- .apply_legend(p, show_legend, legend_position)

  return(p)
}

#' @title Plot Test Reference Profile (TRP) from exametrika
#'
#' @description
#' This function takes exametrika output as input and generates a
#' Test Reference Profile (TRP) plot using ggplot2. TRP shows the
#' number of students in each latent class/rank (bar graph) and the
#' expected test score for each class/rank (line graph).
#'
#' @param data An object from exametrika: LCA, LRA, Biclustering,
#'   nominalBiclustering, ordinalBiclustering, ratedBiclustering,
#'   IRM, LDLRA, LDB, or BINET output.
#' @param Num_Students Logical. If \code{TRUE} (default), display the
#'   number of students on each bar.
#' @param title Logical or character. If \code{TRUE} (default), display the
#'   auto-generated title. If \code{FALSE}, no title. If a character string,
#'   use it as a custom title.
#' @param colors Character vector of length 2. First element is the bar fill
#'   color, second is the line/point color. If \code{NULL} (default), uses
#'   gray for bars and black for line/points.
#' @param linetype Character or numeric specifying the line type for the
#'   expected score line. Default is \code{"dashed"}.
#' @param show_legend Logical. If \code{TRUE}, display the legend.
#'   Default is \code{FALSE}.
#' @param legend_position Character. Position of the legend.
#'   One of \code{"right"} (default), \code{"top"}, \code{"bottom"},
#'   \code{"left"}, \code{"none"}.
#'
#' @return A single ggplot object with dual y-axes showing both the
#'   student distribution and expected scores.
#'
#' @details
#' The Test Reference Profile provides an overview of the latent structure.
#' The bar graph shows how students are distributed across classes/ranks,
#' while the line graph shows the expected test score for each class/rank.
#' In well-fitted models, expected scores should increase monotonically
#' with class/rank number.
#'
#' @examplesIf requireNamespace("exametrika", quietly = TRUE)
#' library(exametrika)
#' result <- LRA(J15S500, nrank = 5)
#' plot <- plotTRP_gg(result)
#' plot
#'
#' @seealso \code{\link{plotIRP_gg}}, \code{\link{plotLCD_gg}},
#'   \code{\link{plotLRD_gg}}
#'
#' @importFrom ggplot2 ggplot
#' @importFrom ggplot2 geom_bar
#' @importFrom ggplot2 geom_point
#' @importFrom ggplot2 geom_line
#' @importFrom ggplot2 scale_x_continuous
#' @importFrom ggplot2 scale_y_continuous
#' @importFrom ggplot2 annotate
#' @importFrom ggplot2 theme
#' @importFrom ggplot2 labs
#' @export

plotTRP_gg <- function(data,
                       Num_Students = TRUE,
                       title = TRUE,
                       colors = NULL,
                       linetype = "dashed",
                       show_legend = FALSE,
                       legend_position = "right") {
  # Class validation
  valid_classes <- c(
    "LCA", "LRA", "Biclustering", "nominalBiclustering",
    "ordinalBiclustering", "ratedBiclustering", "IRM", "LDLRA", "LDB", "BINET"
  )
  .validate_exametrika(data, valid_classes)

  # Get xlabel from msg field (Class or Rank), consistent with plotFRP_gg
  msg <- if ("msg" %in% names(data)) data$msg else "Class"
  xlabel <- paste("Latent", msg)

  # Student distribution: rank models prefer LRD, class models prefer LCD (with fallback)
  if (msg == "Rank") {
    dist_data <- .first_non_null(data$LRD, data$LCD)
  } else {
    dist_data <- .first_non_null(data$LCD, data$LRD)
  }
  if (is.null(dist_data)) {
    stop("No LCD or LRD data found in the input object.")
  }

  x1 <- data.frame(
    LC = seq_along(dist_data),
    Num = c(dist_data)
  )

  x2 <- data.frame(
    LC = seq_along(data$TRP),
    ES = c(data$TRP)
  )


  yaxis1 <- c(0, max(x1$Num))
  yaxis2 <- c(0, max(x2$ES))

  if (isTRUE(Num_Students)) {
    Num_label <- c(x1$Num)
  } else {
    Num_label <- ""
  }

  # Color setup
  if (is.null(colors)) {
    bar_fill <- "gray"
    line_color <- "black"
  } else {
    bar_fill <- colors[1]
    line_color <- if (length(colors) >= 2) colors[2] else "black"
  }

  # Title setup
  plot_title <- .resolve_title(title, "Test Reference Profile")


  plot <- ggplot(x1, aes(x = LC, y = Num)) +
    geom_bar(
      stat = "identity",
      fill = bar_fill,
      colour = "black"
    ) +
    geom_point(aes(y = .variable_scaler(x2$ES, yaxis1, yaxis2)),
      size = 2.1, color = line_color
    ) +
    geom_line(aes(y = .variable_scaler(x2$ES, yaxis1, yaxis2)),
      linetype = linetype, color = line_color
    ) +
    scale_x_continuous(breaks = seq_along(data$TRP)) +
    scale_y_continuous(
      name = "Number of Students",
      sec.axis = sec_axis(transform = ~ (.axis_scaler(
        ., yaxis1, yaxis2
      )), name = "Expected Score")
    ) +
    annotate(
      "text",
      x = x1$LC,
      y = x1$Num - (median(x1$Num) * 0.05),
      label = Num_label
    ) +
    theme(axis.title.y.right = element_text(angle = 90, vjust = 0.5)) +
    labs(
      title = plot_title,
      x = xlabel
    )

  # Legend control
  plot <- .apply_legend(plot, show_legend, legend_position)

  return(plot)
}


#' Shared worker for plotLCD_gg / plotLRD_gg
#'
#' The two exported functions draw the same student-distribution plot;
#' they differ only in which model family is the "native" one (class vs
#' rank) and therefore in which direction the redirect warning fires.
#'
#' @param prefer Either "class" (plotLCD_gg) or "rank" (plotLRD_gg).
#' @inheritParams plotLCD_gg
#' @return A ggplot object.
#' @keywords internal

.plot_student_distribution <- function(data, Num_Students, title, colors,
                                       linetype, show_legend, legend_position,
                                       prefer) {
  class_models <- c("LCA", "BINET")
  rank_models <- c(
    "LRA", "Biclustering", "ordinalBiclustering",
    "nominalBiclustering", "ratedBiclustering", "LDLRA", "LDB"
  )
  .validate_exametrika(data, c(class_models, rank_models))

  # mode TRUE = class model, FALSE = rank model (a biclustering fit is
  # decided by its msg: "B" gives classes, "R" ranks)
  mode <- .is_class_model(data, class_models)
  xlabel <- if (mode) "Latent Class" else "Latent Rank"

  # Warn when the model family does not match the called function
  if (mode && prefer == "rank") {
    warning(
      "The input data was supposed to be visualized with The Latent Class Distribution, so I will plot the LCD."
    )
  } else if (!mode && prefer == "class") {
    warning(
      "The input data was supposed to be visualized with The Latent Rank Distribution, so I will plot the LRD."
    )
  }

  # Student distribution: class models prefer LCD, rank models prefer LRD (with fallback)
  if (mode) {
    dist_data <- .first_non_null(data$LCD, data$LRD)
    freq_data <- .first_non_null(data$CMD, data$RMD)
  } else {
    dist_data <- .first_non_null(data$LRD, data$LCD)
    freq_data <- .first_non_null(data$RMD, data$CMD)
  }

  x1 <- data.frame(
    LC = seq_along(dist_data),
    Num = c(dist_data)
  )

  x2 <- data.frame(
    LC = seq_along(freq_data),
    Fre = c(freq_data)
  )

  yaxis1 <- c(0, max(x1$Num))
  yaxis2 <- c(0, max(x2$Fre))

  if (isTRUE(Num_Students)) {
    Num_label <- c(x1$Num)
  } else {
    Num_label <- ""
  }

  # Color setup
  if (is.null(colors)) {
    bar_fill <- "gray"
    line_color <- "black"
  } else {
    bar_fill <- colors[1]
    line_color <- if (length(colors) >= 2) colors[2] else "black"
  }

  # Title setup
  auto_title <- if (mode) "Latent Class Distribution" else "Latent Rank Distribution"
  plot_title <- .resolve_title(title, auto_title)

  plot <- ggplot(x1, aes(x = LC, y = Num)) +
    geom_bar(
      stat = "identity",
      fill = bar_fill,
      colour = "black"
    ) +
    geom_point(aes(y = .variable_scaler(x2$Fre, yaxis1, yaxis2)),
      size = 2.1, color = line_color
    ) +
    geom_line(aes(y = .variable_scaler(x2$Fre, yaxis1, yaxis2)),
      linetype = linetype, color = line_color
    ) +
    scale_x_continuous(breaks = seq_along(dist_data)) +
    scale_y_continuous(
      name = "Number of Students",
      sec.axis = sec_axis(transform = ~ (.axis_scaler(
        ., yaxis1, yaxis2
      )), name = "Frequency")
    ) +
    annotate(
      "text",
      x = x1$LC,
      y = x1$Num - (median(x1$Num) * 0.05),
      label = Num_label
    ) +
    theme(axis.title.y.right = element_text(angle = 90, vjust = 0.5)) +
    labs(
      title = plot_title,
      x = xlabel
    )

  # Legend control
  .apply_legend(plot, show_legend, legend_position)
}


#' @title Plot Latent Class Distribution (LCD) from exametrika
#'
#' @description
#' This function takes exametrika output as input and generates a
#' Latent Class Distribution (LCD) plot using ggplot2. LCD shows the
#' number of students in each latent class and the class membership
#' distribution.
#'
#' @param data An object of class \code{c("exametrika", "LCA")} or
#'   \code{c("exametrika", "BINET")}. If LRA or Biclustering output
#'   is provided, LRD will be plotted instead with a warning.
#' @param Num_Students Logical. If \code{TRUE} (default), display the
#'   number of students on each bar.
#' @param title Logical or character. If \code{TRUE} (default), display the
#'   auto-generated title. If \code{FALSE}, no title. If a character string,
#'   use it as a custom title.
#' @param colors Character vector of length 2. First element is the bar fill
#'   color, second is the line/point color. If \code{NULL} (default), uses
#'   gray for bars and black for line/points.
#' @param linetype Character or numeric specifying the line type for the
#'   frequency line. Default is \code{"dashed"}.
#' @param show_legend Logical. If \code{TRUE}, display the legend.
#'   Default is \code{FALSE}.
#' @param legend_position Character. Position of the legend.
#'   One of \code{"right"} (default), \code{"top"}, \code{"bottom"},
#'   \code{"left"}, \code{"none"}.
#'
#' @return A single ggplot object with dual y-axes showing both the
#'   student count and membership frequency.
#'
#' @details
#' The Latent Class Distribution shows how students are distributed
#' across latent classes. The bar graph shows the number of students
#' assigned to each class, and the line graph shows the cumulative
#' class membership distribution.
#'
#' @examplesIf requireNamespace("exametrika", quietly = TRUE)
#' library(exametrika)
#' result <- LCA(J15S500, ncls = 5)
#' plot <- plotLCD_gg(result)
#' plot
#'
#' @seealso \code{\link{plotLRD_gg}}, \code{\link{plotTRP_gg}}
#'
#' @importFrom ggplot2 ggplot
#' @importFrom ggplot2 geom_bar
#' @importFrom ggplot2 geom_point
#' @importFrom ggplot2 geom_line
#' @importFrom ggplot2 scale_x_continuous
#' @importFrom ggplot2 scale_y_continuous
#' @importFrom ggplot2 annotate
#' @importFrom ggplot2 theme
#' @importFrom ggplot2 labs
#' @export

plotLCD_gg <- function(data,
                       Num_Students = TRUE,
                       title = TRUE,
                       colors = NULL,
                       linetype = "dashed",
                       show_legend = FALSE,
                       legend_position = "right") {
  .plot_student_distribution(
    data, Num_Students, title, colors, linetype, show_legend,
    legend_position,
    prefer = "class"
  )
}

#' @title Plot Latent Rank Distribution (LRD) from exametrika
#'
#' @description
#' This function takes exametrika output as input and generates a
#' Latent Rank Distribution (LRD) plot using ggplot2. LRD shows the
#' number of students in each latent rank and the rank membership
#' distribution.
#'
#' @param data An object of class \code{c("exametrika", "LRA")},
#'   \code{c("exametrika", "Biclustering")}, \code{c("exametrika", "LDLRA")},
#'   or \code{c("exametrika", "LDB")}. If LCA or BINET output is provided,
#'   LCD will be plotted instead with a warning.
#' @param Num_Students Logical. If \code{TRUE} (default), display the
#'   number of students on each bar.
#' @param title Logical or character. If \code{TRUE} (default), display the
#'   auto-generated title. If \code{FALSE}, no title. If a character string,
#'   use it as a custom title.
#' @param colors Character vector of length 2. First element is the bar fill
#'   color, second is the line/point color. If \code{NULL} (default), uses
#'   gray for bars and black for line/points.
#' @param linetype Character or numeric specifying the line type for the
#'   frequency line. Default is \code{"dashed"}.
#' @param show_legend Logical. If \code{TRUE}, display the legend.
#'   Default is \code{FALSE}.
#' @param legend_position Character. Position of the legend.
#'   One of \code{"right"} (default), \code{"top"}, \code{"bottom"},
#'   \code{"left"}, \code{"none"}.
#'
#' @return A single ggplot object with dual y-axes showing both the
#'   student count and membership frequency.
#'
#' @details
#' The Latent Rank Distribution shows how students are distributed
#' across latent ranks. Unlike latent classes, ranks have an ordinal
#' interpretation where higher ranks indicate higher ability levels.
#'
#' @examplesIf requireNamespace("exametrika", quietly = TRUE)
#' library(exametrika)
#' result <- LRA(J15S500, nrank = 5)
#' plot <- plotLRD_gg(result)
#' plot
#'
#' @seealso \code{\link{plotLCD_gg}}, \code{\link{plotTRP_gg}}
#'
#' @importFrom ggplot2 ggplot
#' @importFrom ggplot2 geom_bar
#' @importFrom ggplot2 geom_point
#' @importFrom ggplot2 geom_line
#' @importFrom ggplot2 scale_x_continuous
#' @importFrom ggplot2 scale_y_continuous
#' @importFrom ggplot2 annotate
#' @importFrom ggplot2 theme
#' @importFrom ggplot2 labs
#' @export

plotLRD_gg <- function(data,
                       Num_Students = TRUE,
                       title = TRUE,
                       colors = NULL,
                       linetype = "dashed",
                       show_legend = FALSE,
                       legend_position = "right") {
  .plot_student_distribution(
    data, Num_Students, title, colors, linetype, show_legend,
    legend_position,
    prefer = "rank"
  )
}


#' Shared worker for plotCMP_gg / plotRMP_gg
#'
#' The two exported functions draw the same per-student membership plot;
#' they differ only in which model family is the "native" one (class vs
#' rank) and therefore in which direction the redirect warning fires.
#'
#' @param prefer Either "class" (plotCMP_gg) or "rank" (plotRMP_gg).
#' @inheritParams plotCMP_gg
#' @return A list of ggplot objects, one per student.
#' @keywords internal

.plot_membership_profile <- function(data, title, colors, linetype,
                                     show_legend, legend_position, prefer) {
  class_models <- c("LCA", "BINET")
  rank_models <- c(
    "LRA", "LRAordinal", "LRArated", "Biclustering", "ordinalBiclustering",
    "nominalBiclustering", "ratedBiclustering", "LDB", "LDLRA"
  )
  .validate_exametrika(data, c(class_models, rank_models))

  is_class_model <- .is_class_model(data, class_models)
  xlabel <- if (is_class_model) "Class" else "Rank"

  # LCA output has unnamed students: give them zero-padded names
  if (inherits(data, "LCA")) {
    dig <- nchar(nrow(data$Students))
    rownames(data$Students) <- paste0(
      "Student ", formatC(seq_len(nrow(data$Students)), width = dig, flag = "0")
    )
  }

  # Warn when the model family does not match the called function
  if (is_class_model && prefer == "rank") {
    warning(
      "The input data was supposed to be visualized with The Class Membership Profile, so I will plot the CMP."
    )
  } else if (!is_class_model && prefer == "class") {
    warning(
      "The input data was supposed to be visualized with The Rank Membership Profile, so I will plot the RMP."
    )
  }

  # Unordered models report n_class, ranked ones n_rank
  n_cls <- .first_non_null(data$n_class, data$n_rank)

  if (is.null(n_cls) || n_cls < 2 || n_cls > 20) {
    stop("Invalid number of Class or Rank")
  }

  # Color setup
  if (is.null(colors)) {
    use_color <- .gg_exametrika_palette(1)[1]
  } else {
    use_color <- colors[1]
  }

  # Get Membership columns by name (prevent column index mismatch)
  membership_cols <- grep("^Membership", colnames(data$Students))
  if (length(membership_cols) == 0) {
    stop("No 'Membership' columns found in data$Students")
  }

  plots <- list()

  for (i in 1:nrow(data$Students)) {
    x <- data.frame(
      Membership = as.numeric(data$Students[i, membership_cols]),
      rank = seq_along(membership_cols)
    )

    # Title setup
    plot_title <- .resolve_title(
      title,
      paste0(xlabel, " Membership Profile, ", rownames(data$Students)[i])
    )

    p <- ggplot(x, aes(x = rank, y = Membership)) +
      scale_y_continuous(limits = c(0, 1), breaks = seq(0, 1, 0.25)) +
      geom_point(color = use_color) +
      geom_line(linetype = linetype, color = use_color) +
      scale_x_continuous(breaks = seq_along(membership_cols)) +
      labs(
        title = plot_title,
        x = paste0("Latent ", xlabel),
        y = "Membership"
      )

    plots[[i]] <- .apply_legend(p, show_legend, legend_position)
  }

  return(plots)
}


#' @title Plot Class Membership Profile (CMP) from exametrika
#'
#' @description
#' This function takes exametrika output as input and generates
#' Class Membership Profile (CMP) plots using ggplot2. CMP shows
#' each student's membership probability across all latent classes.
#'
#' @param data An object of class \code{c("exametrika", "LCA")} or
#'   \code{c("exametrika", "BINET")}. If LRA, Biclustering, LDLRA, or LDB
#'   output is provided, RMP will be plotted instead with a warning.
#' @param title Logical or character. If \code{TRUE} (default), display an
#'   auto-generated title. If \code{FALSE}, no title. If a character string,
#'   use it as a custom title (only for single-student plots).
#' @param colors Character vector. Color(s) for points and lines.
#'   If \code{NULL} (default), a colorblind-friendly palette is used.
#' @param linetype Character or numeric specifying the line type.
#'   Default is \code{"dashed"}.
#' @param show_legend Logical. If \code{TRUE}, display the legend.
#'   Default is \code{FALSE}.
#' @param legend_position Character. Position of the legend.
#'   One of \code{"right"} (default), \code{"top"}, \code{"bottom"},
#'   \code{"left"}, \code{"none"}.
#'
#' @return A list of ggplot objects, one for each student. Each plot shows
#'   the membership probability across all latent classes.
#'
#' @details
#' The Class Membership Profile visualizes how strongly each student
#' belongs to each latent class. Students with high membership probability
#' in a single class are well-classified, while students with similar
#' probabilities across classes may be ambiguous cases.
#'
#' @examplesIf requireNamespace("exametrika", quietly = TRUE)
#' library(exametrika)
#' \donttest{
#' result <- LCA(J15S500, ncls = 5)
#' plots <- plotCMP_gg(result)
#' plots[[1]] # Show CMP for the first student
#' }
#'
#' @seealso \code{\link{plotRMP_gg}}, \code{\link{plotLCD_gg}}
#'
#' @importFrom ggplot2 ggplot
#' @importFrom ggplot2 ylim
#' @importFrom ggplot2 geom_point
#' @importFrom ggplot2 geom_line
#' @importFrom ggplot2 scale_x_continuous
#' @importFrom ggplot2 labs theme
#' @export


plotCMP_gg <- function(data,
                       title = TRUE,
                       colors = NULL,
                       linetype = "dashed",
                       show_legend = FALSE,
                       legend_position = "right") {
  .plot_membership_profile(
    data, title, colors, linetype, show_legend, legend_position,
    prefer = "class"
  )
}

#' @title Plot Rank Membership Profile (RMP) from exametrika
#'
#' @description
#' This function takes exametrika output as input and generates
#' Rank Membership Profile (RMP) plots using ggplot2. RMP shows
#' each student's membership probability across all latent ranks.
#'
#' @param data An object of class \code{c("exametrika", "LRA")},
#'   \code{c("exametrika", "Biclustering")}, \code{c("exametrika", "LDLRA")},
#'   or \code{c("exametrika", "LDB")}. If LCA or BINET output is provided,
#'   CMP will be plotted instead with a warning.
#' @param title Logical or character. If \code{TRUE} (default), display an
#'   auto-generated title. If \code{FALSE}, no title. If a character string,
#'   use it as a custom title (only for single-student plots).
#' @param colors Character vector. Color(s) for points and lines.
#'   If \code{NULL} (default), a colorblind-friendly palette is used.
#' @param linetype Character or numeric specifying the line type.
#'   Default is \code{"dashed"}.
#' @param show_legend Logical. If \code{TRUE}, display the legend.
#'   Default is \code{FALSE}.
#' @param legend_position Character. Position of the legend.
#'   One of \code{"right"} (default), \code{"top"}, \code{"bottom"},
#'   \code{"left"}, \code{"none"}.
#'
#' @return A list of ggplot objects, one for each student. Each plot shows
#'   the membership probability across all latent ranks.
#'
#' @details
#' The Rank Membership Profile visualizes how strongly each student
#' belongs to each latent rank. Unlike class membership, rank membership
#' has an ordinal interpretation. Students with unimodal profiles
#' centered on a single rank are well-classified.
#'
#' @examplesIf requireNamespace("exametrika", quietly = TRUE)
#' library(exametrika)
#' \donttest{
#' result <- LRA(J15S500, nrank = 5)
#' plots <- plotRMP_gg(result)
#' plots[[1]] # Show RMP for the first student
#' }
#'
#' @seealso \code{\link{plotCMP_gg}}, \code{\link{plotLRD_gg}}
#'
#' @importFrom ggplot2 ggplot
#' @importFrom ggplot2 ylim
#' @importFrom ggplot2 geom_point
#' @importFrom ggplot2 geom_line
#' @importFrom ggplot2 scale_x_continuous
#' @importFrom ggplot2 labs theme
#' @export

plotRMP_gg <- function(data,
                       title = TRUE,
                       colors = NULL,
                       linetype = "dashed",
                       show_legend = FALSE,
                       legend_position = "right") {
  .plot_membership_profile(
    data, title, colors, linetype, show_legend, legend_position,
    prefer = "rank"
  )
}

Try the ggExametrika package in your browser

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

ggExametrika documentation built on Nov. 25, 2026, 9:07 a.m.