R/arraytoLDPSR.R

Defines functions plotFieldPIRP_gg plotArray_gg .extract_legend

Documented in .extract_legend plotArray_gg plotFieldPIRP_gg

#' Pull the guide box out of a ggplot
#'
#' Used to share one legend between the two array panels instead of drawing
#' the same one twice. Returns NULL when the plot carries no legend.
#'
#' @param p A ggplot object, already themed with the wanted legend position so
#'   that the guide box has the matching orientation.
#' @return A grob, or NULL.
#' @keywords internal

.extract_legend <- function(p) {
  g <- ggplot2::ggplotGrob(p)
  idx <- which(vapply(g$grobs, function(x) grepl("^guide-box", x$name), logical(1)))
  for (i in idx) {
    box <- g$grobs[[i]]
    # ggplot2 lays out a guide box on every side; all but one are empty
    if (!inherits(box, "zeroGrob")) {
      inner <- if (!is.null(box$grobs)) box$grobs else box$children
      if (length(inner) > 0) {
        return(box)
      }
    }
  }
  return(NULL)
}


#' @title Plot Array from exametrika
#'
#' @description
#' This function takes exametrika output as input and generates
#' array plots using ggplot2. Array plots visualize the response
#' patterns of students (rows) across items (columns), showing both
#' the original data and the clustered/reordered data.
#'
#' Supports both binary (0/1) and multi-valued (ordinal/nominal) data.
#'
#' @param data An object of class \code{c("exametrika", "Biclustering")},
#'   \code{c("exametrika", "nominalBiclustering")},
#'   \code{c("exametrika", "ordinalBiclustering")},
#'   \code{c("exametrika", "ratedBiclustering")},
#'   \code{c("exametrika", "IRM")}, \code{c("exametrika", "LDB")}, or
#'   \code{c("exametrika", "BINET")}.
#' @param Original Logical. If \code{TRUE} (default), plot the original
#'   (unsorted) response data.
#' @param Clustered Logical. If \code{TRUE} (default), plot the clustered
#'   (sorted by class and field) response data.
#' @param Clustered_lines Logical. If \code{TRUE} (default), draw lines
#'   on the clustered plot to indicate class and field boundaries.
#' @param Clustered_lines_color Character. Color of the boundary lines.
#'   If \code{NULL} (default), uses \code{"red"} for binary data or
#'   \code{"white"} for multi-valued data.
#' @param title Logical or character. If \code{TRUE} (default), display
#'   auto-generated titles. If \code{FALSE}, no titles. If a character
#'   string, use it as a custom title prefix.
#' @param colors Character vector of colors. Supply either one colour per
#'   valid category, in which case missing data keeps the default colour, or
#'   one colour per level including missing data, in which case the first
#'   element is used for missing. Default NULL uses a sequential ramp for
#'   ordered categories and black and white for binary data.
#'   If \code{NULL} (default), uses white/black for binary data or a
#'   colorblind-friendly palette for multi-valued data.
#' @param show_legend Logical. If \code{TRUE}, display the legend.
#'   Default is \code{FALSE} for binary data, \code{TRUE} for multi-valued.
#' @param legend_position Character. Position of the legend. Defaults to
#'   "bottom": the array panels are tall, so a legend beside them wastes width.
#'   When both panels are drawn the legend is shared, not repeated.
#'   One of \code{"right"} (default), \code{"top"}, \code{"bottom"},
#'   \code{"left"}, \code{"none"}.
#' @param border Logical or character. If \code{TRUE}, draw a rectangular
#'   border around each panel so that the original and clustered panels
#'   are visually separated. If \code{FALSE} (default), no border is
#'   drawn (the v1.1.0 behavior). A character string is used as the
#'   border color (default color is \code{"black"}).
#' @param border_linewidth Numeric. Line width of the panel border.
#'   Default is \code{0.5}.
#'
#' @return When both \code{Original} and \code{Clustered} are \code{TRUE},
#'   a gtable (grid arrangement of the two panels side by side, drawn as a
#'   side effect). Otherwise, a list containing the single requested
#'   ggplot object.
#'
#' @details
#' The array plot provides a visual representation of the biclustering
#' result. For binary data, black cells indicate correct responses (1)
#' and white cells indicate incorrect responses (0). For multi-valued
#' data, different colors represent different response categories.
#'
#' In a well-fitted model, the clustered plot should show a clear block
#' diagonal pattern where high-ability students (bottom rows) answer
#' difficult items (right columns) correctly.
#'
#' @examplesIf requireNamespace("exametrika", quietly = TRUE)
#' library(exametrika)
#' result <- Biclustering(J35S515, nfld = 5, ncls = 6)
#'
#' # Basic usage
#' plotArray_gg(result)
#'
#' # Custom boundary line color
#' plotArray_gg(result, Clustered_lines_color = "blue")
#'
#' # Multi-valued data with custom colors
#' synthetic_data <- matrix(sample(0:3, 50 * 20, replace = TRUE), nrow = 50, ncol = 20)
#' result_multi <- Biclustering(synthetic_data, nfld = 4, ncls = 5)
#' plotArray_gg(result_multi, show_legend = TRUE, Clustered_lines_color = "darkgreen")
#'
#' @seealso \code{\link{plotFRP_gg}}, \code{\link{plotTRP_gg}}
#'
#' @importFrom ggplot2 ggplot aes geom_tile scale_fill_manual labs theme element_text element_blank element_rect geom_hline geom_vline margin scale_x_continuous scale_y_continuous
#' @importFrom gridExtra grid.arrange
#' @export

plotArray_gg <- function(data,
                         Original = TRUE,
                         Clustered = TRUE,
                         Clustered_lines = TRUE,
                         Clustered_lines_color = NULL,
                         title = TRUE,
                         colors = NULL,
                         show_legend = NULL,
                         legend_position = "bottom",
                         border = FALSE,
                         border_linewidth = 0.5) {
  # Border color resolution
  if (is.logical(border)) {
    draw_border <- isTRUE(border)
    border_color <- "black"
  } else if (is.character(border)) {
    draw_border <- TRUE
    border_color <- border
  } else {
    draw_border <- FALSE
    border_color <- "black"
  }
  # Check input class
  valid_classes <- c(
    "Biclustering", "nominalBiclustering", "ordinalBiclustering",
    "ratedBiclustering", "IRM", "LDB", "BINET"
  )
  .validate_exametrika(data, valid_classes)

  # Detect data values and categories
  raw_data <- if (!is.null(data$U)) data$U else data$Q
  all_values <- sort(unique(as.vector(as.matrix(raw_data))))

  # Separate missing values (-1) from valid values
  has_missing <- -1 %in% all_values
  valid_values <- all_values[all_values != -1]
  n_valid_categories <- length(valid_values)

  # Determine total categories (for boundary line color decision)
  n_categories <- length(all_values)

  # Set default boundary line color based on number of valid categories
  if (is.null(Clustered_lines_color)) {
    if (n_valid_categories > 2) {
      # The sequential ramp is light at the bottom end, so white lines would
      # disappear into the palest cells. A dark red reads against every step.
      Clustered_lines_color <- "#B00020"
    } else if (n_valid_categories <= 2 && !has_missing) {
      # Binary data: red lines for better visibility on black/white
      Clustered_lines_color <- "red"
    } else {
      # Two categories plus missing: the qualitative fills are dark enough
      Clustered_lines_color <- "white"
    }
  }

  # Set default colors based on number of valid categories
  if (is.null(colors)) {
    if (n_valid_categories == 2 && !has_missing) {
      # Binary data: white (0) and black (1)
      valid_colors <- c("#FFFFFF", "#000000")
    } else if (n_valid_categories > 2) {
      # Ordered categories: a sequential ramp, so that the category index is
      # readable as lightness. A qualitative palette hides the ordering.
      valid_colors <- .gg_exametrika_sequential(n_valid_categories)
    } else {
      # Two valid categories alongside missing data: keep the qualitative
      # palette, since a two-step ramp would be hard to tell apart.
      valid_colors <- c("#E69F00", "#0173B2")[1:n_valid_categories]
    }

    # Assign colors to all values (including -1 if present)
    use_colors <- character(n_categories)
    for (i in seq_along(all_values)) {
      if (all_values[i] == -1) {
        # Grey, not black: against a sequential ramp black reads as the
        # darkest category rather than as missing.
        use_colors[i] <- if (n_valid_categories > 2) "#9E9E9E" else "#000000"
      } else {
        # Find position in valid_values
        valid_idx <- which(valid_values == all_values[i])
        use_colors[i] <- valid_colors[valid_idx]
      }
    }
  } else {
    # A supplied vector is read by its length. Missing data occupies a slot of
    # its own, so a vector with one colour per valid category would otherwise
    # be shifted by one and the last category would wrap around.
    if (has_missing && length(colors) == n_valid_categories) {
      use_colors <- character(n_categories)
      for (i in seq_along(all_values)) {
        if (all_values[i] == -1) {
          use_colors[i] <- if (n_valid_categories > 2) "#9E9E9E" else "#000000"
        } else {
          use_colors[i] <- colors[which(valid_values == all_values[i])]
        }
      }
    } else {
      use_colors <- .resolve_colors(colors, n_categories)
    }
  }

  # Create labels for legend (NA for -1, numbers for others)
  value_labels <- ifelse(all_values == -1, "NA", as.character(all_values))

  # Set default legend visibility based on data type
  if (is.null(show_legend)) {
    show_legend <- n_categories > 2
  }

  plots <- list()

  if (Original == TRUE) {
    itemn <- NULL
    for (i in 1:ncol(raw_data)) {
      itemn <- c(itemn, rep(i, nrow(raw_data)))
    }

    rown <- rep(1:nrow(raw_data), ncol(raw_data))
    response_val <- as.vector(as.matrix(raw_data))

    plot_data <- data.frame(
      itemn = itemn,
      rown = rown,
      value = factor(response_val, levels = all_values)
    )

    # Set title
    if (is.logical(title) && title) {
      title1 <- "Original Data"
    } else if (is.logical(title) && !title) {
      title1 <- NULL
    } else if (is.character(title)) {
      title1 <- paste(title, "- Original Data")
    }

    original_plot <- ggplot(plot_data, aes(x = itemn, y = rown, fill = value)) +
      geom_tile() +
      scale_fill_manual(
        values = setNames(use_colors, all_values),
        labels = value_labels,
        name = "Response",
        drop = FALSE
      ) +
      scale_x_continuous(expand = c(0, 0), limits = c(0.5, ncol(raw_data) + 0.5)) +
      scale_y_continuous(expand = c(0, 0), limits = c(0.5, nrow(raw_data) + 0.5)) +
      labs(title = title1) +
      theme(
        plot.title = element_text(
          hjust = 0.5,
          size = 11,
          margin = margin(t = 5, b = 5)
        ),
        axis.ticks = element_blank(),
        axis.text = element_blank(),
        axis.title = element_blank(),
        axis.line = element_blank(),
        panel.background = element_blank(),
        plot.margin = margin(t = 5, r = 5, b = 5, l = 5)
      )

    # Panel border
    if (draw_border) {
      original_plot <- original_plot + theme(
        panel.border = element_rect(
          color = border_color, fill = NA, linewidth = border_linewidth
        )
      )
    }

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

    plots[[1]] <- original_plot
  }

  if (Clustered == TRUE) {
    # Sort data to match exametrika's original implementation
    # order(decreasing = FALSE) puts smaller class numbers first in the data
    # But we reverse rown so smaller classes appear at top visually
    case_order <- order(data$ClassEstimated, decreasing = FALSE)
    field_order <- order(data$FieldEstimated, decreasing = FALSE)
    sorted <- raw_data[case_order, field_order]

    itemn <- NULL
    for (i in 1:ncol(sorted)) {
      itemn <- c(itemn, rep(i, nrow(sorted)))
    }

    # Reverse row numbers so that:
    # - sorted[1, ] (smallest ClassEstimated) -> rown = nrow (top visually)
    # - sorted[nrow, ] (largest ClassEstimated) -> rown = 1 (bottom visually)
    rown <- rep(nrow(sorted):1, ncol(sorted))
    response_val <- as.vector(as.matrix(sorted))

    plot_data <- data.frame(
      itemn = itemn,
      rown = rown,
      value = factor(response_val, levels = all_values)
    )

    # Set title
    if (is.logical(title) && title) {
      title2 <- "Clustered Data"
    } else if (is.logical(title) && !title) {
      title2 <- NULL
    } else if (is.character(title)) {
      title2 <- paste(title, "- Clustered Data")
    }

    clustered_plot <- ggplot(plot_data, aes(x = itemn, y = rown, fill = value)) +
      geom_tile() +
      scale_fill_manual(
        values = setNames(use_colors, all_values),
        labels = value_labels,
        name = "Response",
        drop = FALSE
      ) +
      scale_x_continuous(expand = c(0, 0), limits = c(0.5, ncol(sorted) + 0.5)) +
      scale_y_continuous(expand = c(0, 0), limits = c(0.5, nrow(sorted) + 0.5)) +
      labs(title = title2) +
      theme(
        plot.title = element_text(
          hjust = 0.5,
          size = 11,
          margin = margin(t = 5, b = 5)
        ),
        axis.ticks = element_blank(),
        axis.text = element_blank(),
        axis.title = element_blank(),
        axis.line = element_blank(),
        panel.background = element_blank(),
        plot.margin = margin(t = 5, r = 5, b = 5, l = 5)
      )

    # Panel border
    if (draw_border) {
      clustered_plot <- clustered_plot + theme(
        panel.border = element_rect(
          color = border_color, fill = NA, linewidth = border_linewidth
        )
      )
    }

    # Add class/field boundary lines
    if (Clustered_lines == TRUE) {
      # Calculate boundary positions based on sorted data
      sorted_class <- data$ClassEstimated[case_order]
      sorted_field <- data$FieldEstimated[field_order]

      # Class-side count: models name it n_class or n_rank depending on
      # whether the groups are ordered, so both are consulted.
      n_class <- .first_non_null(
        data$n_class, data$n_rank,
        length(unique(data$ClassEstimated))
      )
      n_field <- .first_non_null(data$n_field, length(unique(data$FieldEstimated)))

      # Use explicit factor levels so that empty classes/fields do not
      # drop out of the table (which would leave NA in the breaks)
      class_breaks <- cumsum(table(factor(sorted_class, levels = seq_len(n_class))))
      field_breaks <- cumsum(table(factor(sorted_field, levels = seq_len(n_field))))

      h <- class_breaks[seq_len(n_class - 1)]
      v <- field_breaks[seq_len(n_field - 1)]

      # Since rown is reversed (nrow:1), we need to adjust h positions
      # h gives positions in sorted data (1-indexed from top)
      # We need positions in ggplot2 coordinates where rown goes from nrow (top) to 1 (bottom)
      h_adjusted <- nrow(sorted) - h

      # Lines should be placed at boundaries between cells (x.5 positions)
      clustered_plot <- clustered_plot +
        geom_hline(yintercept = h_adjusted + 0.5, color = Clustered_lines_color, linewidth = 0.5) +
        geom_vline(xintercept = v + 0.5, color = Clustered_lines_color, linewidth = 0.5)
    }

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

    plots[[length(plots) + 1]] <- clustered_plot
  }

  if (Original == TRUE && Clustered == TRUE) {
    # Both panels share one scale, so draw the legend once beside or below the
    # pair rather than repeating it inside each panel.
    shared_legend <- if (isTRUE(show_legend)) .extract_legend(plots[[1]]) else NULL
    if (is.null(shared_legend)) {
      plots <- grid.arrange(plots[[1]], plots[[2]], nrow = 1)
    } else {
      panels <- gridExtra::arrangeGrob(
        plots[[1]] + ggplot2::theme(legend.position = "none"),
        plots[[2]] + ggplot2::theme(legend.position = "none"),
        nrow = 1
      )
      vertical <- legend_position %in% c("bottom", "top")
      parts <- list(panels, shared_legend)
      flip <- legend_position %in% c("top", "left")
      if (flip) {
        parts <- rev(parts)
      }
      # Give the guide box exactly the room it asks for; a fixed ratio clips
      # the legend title at some figure sizes.
      if (vertical) {
        legend_size <- if (!is.null(shared_legend$heights)) {
          sum(shared_legend$heights)
        } else {
          grid::unit(1, "lines")
        }
        panel_size <- grid::unit(1, "null")
        plots <- grid.arrange(
          grobs = parts, nrow = 2,
          heights = if (flip) {
            grid::unit.c(legend_size, panel_size)
          } else {
            grid::unit.c(panel_size, legend_size)
          }
        )
      } else {
        legend_size <- if (!is.null(shared_legend$widths)) {
          sum(shared_legend$widths)
        } else {
          grid::unit(4, "lines")
        }
        panel_size <- grid::unit(1, "null")
        plots <- grid.arrange(
          grobs = parts, ncol = 2,
          widths = if (flip) {
            grid::unit.c(legend_size, panel_size)
          } else {
            grid::unit.c(panel_size, legend_size)
          }
        )
      }
    }
  }

  return(plots)
}


#' @title Plot Field PIRP (Parent Item Reference Profile) from exametrika
#'
#' @description
#' This function takes exametrika LDB output as input and generates
#' Field PIRP (Parent Item Reference Profile) plots using ggplot2.
#' Field PIRP shows the correct response rate for each field as a
#' function of the number-right score in parent fields.
#'
#' @param data An object of class \code{c("exametrika", "LDB")}.
#' @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 prefix (rank number will be appended).
#' @param colors Character vector. Colors for each field line.
#'   If \code{NULL} (default), uses black for all lines (with text labels
#'   for field identification).
#' @param linetype Character or numeric specifying the line type.
#'   Default is \code{"solid"}.
#' @param show_legend Logical. If \code{TRUE}, display the legend.
#'   Default is \code{FALSE} (uses text labels instead).
#' @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 rank. Each plot shows
#'   the correct response rate curves for all fields at that rank level.
#'
#' @details
#' In Local Dependence Biclustering (LDB), items in a field may depend
#' on performance in parent fields. The Field PIRP visualizes this
#' dependency by showing how the correct response rate in each field
#' changes based on the number of correct responses in parent fields.
#'
#' Note: Warning messages about NA values may appear during plotting
#' but the behavior is normal.
#'
#' @examplesIf requireNamespace("exametrika", quietly = TRUE)
#' \donttest{
#' library(exametrika)
#' # LDB requires field configuration and edge structure
#' conf <- c(
#'   1, 6, 6, 8, 9, 9, 4, 7, 7, 7, 5, 8, 9, 10, 10, 9, 9,
#'   10, 10, 10, 2, 2, 3, 3, 5, 5, 6, 9, 9, 10, 1, 1, 7, 9, 10
#' )
#' edges_data <- data.frame(
#'   "From Field (Parent) >>>" = c(6, 4, 5, 1, 1, 4, 3, 4, 6, 2, 4, 4, 3, 6, 4, 1, 7, 9, 6, 7),
#'   ">>> To Field (Child)" = c(8, 7, 8, 7, 2, 5, 5, 8, 8, 4, 6, 7, 5, 8, 5, 8, 10, 10, 8, 9),
#'   "At Class/Rank (Locus)" = c(2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5)
#' )
#' tmp_file <- tempfile(fileext = ".csv")
#' write.csv(edges_data, file = tmp_file, row.names = FALSE)
#' result <- LDB(J35S515, ncls = 5, conf = conf, adj_file = tmp_file)
#' unlink(tmp_file)
#' plots <- plotFieldPIRP_gg(result)
#' plots[[1]] # Show Field PIRP for rank 1
#' }
#'
#' @seealso \code{\link{plotFRP_gg}}, \code{\link{plotArray_gg}}
#'
#' @importFrom ggplot2 ggplot aes
#' @importFrom ggplot2 ylim
#' @importFrom ggplot2 geom_line
#' @importFrom ggplot2 geom_text
#' @importFrom ggplot2 scale_x_continuous
#' @importFrom ggplot2 scale_color_manual
#' @importFrom ggplot2 labs theme
#' @export

plotFieldPIRP_gg <- function(data,
                             title = TRUE,
                             colors = NULL,
                             linetype = "solid",
                             show_legend = FALSE,
                             legend_position = "right") {
  .validate_exametrika(data, "LDB")


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

  n_field <- data$n_field

  # Color setup
  if (is.null(colors)) {
    use_colors <- .gg_exametrika_palette(n_field)
  } else {
    use_colors <- rep_len(colors, n_field)
  }

  plots <- list()

  for (i in 1:n_cls) {
    field_data <- NULL

    plot_data <- NULL

    for (j in 1:n_field) {
      x <- data.frame(k = c(data$CCRR_table[j + (i - 1) * n_field, 3:ncol(data$CCRR_table)]))

      field_data <- data.frame(
        k = t(x),
        l = c(0:(ncol(
          data$CCRR_table
        ) - 3)),
        field = data$CCRR_table$Field[j + (i - 1) * n_field]
      )

      plot_data <- rbind(plot_data, field_data)
    }

    # Title setup
    if (is.logical(title) && title) {
      plot_title <- paste0("Rank ", i)
    } else if (is.logical(title) && !title) {
      plot_title <- NULL
    } else {
      plot_title <- paste0(title, " - Rank ", i)
    }

    p <- ggplot(plot_data, aes(
      x = l,
      y = k,
      group = field,
      color = field
    )) +
      scale_y_continuous(limits = c(0, 1), breaks = seq(0, 1, 0.25)) +
      scale_x_continuous(breaks = seq(0, max(plot_data$l), 1)) +
      geom_line(linetype = linetype) +
      geom_text(aes(x = l, y = k - 0.02, label = sub("\\D*", "", field)),
        show.legend = FALSE
      ) +
      scale_color_manual(values = use_colors) +
      labs(
        title = plot_title,
        x = "PIRP(Number-Right Score) in Parent Field(s) ",
        y = "Correct Response Rate",
        color = "Field"
      )

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

    plots[[i]] <- p
  }

  return(plots)
}

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.