Diff of /R/AdjustAlphaScale.R [000000] .. [0f2269]

Switch to unified view

a b/R/AdjustAlphaScale.R
1
#' Adjust Alpha Scale for Data Visualization
2
#'
3
#' This function dynamically adjusts the transparency scale for visualizations,
4
#' especially useful when the range of data values varies significantly across different sources.
5
#' It modifies the transparency scale based on the range of values present in the data,
6
#' ensuring that the visualization accurately reflects variations within the data.
7
#'
8
#' @importFrom ggplot2 scale_alpha_continuous guide_legend ggplot geom_point
9
#' @param data A data frame containing the values for which the alpha scale is to be adjusted.
10
#' @param name Character string that will be used as the title of the legend in the plot.
11
#' @param range Numeric vector of length 2 specifying the range of alpha values, defaults to c(0.2, 0.8).
12
#' @return A ggplot2 alpha scale adjustment layer.
13
#' @export
14
#'
15
#' @examples
16
#' # Assuming 'data' is a DataFrame with a 'value' column
17
#' plot_data <- data.frame(value = c(10, 20, 30, 40, 50))
18
#' ggplot2::ggplot(plot_data, ggplot2::aes(x = 1:nrow(plot_data), y = value)) +
19
#'   ggplot2::geom_point(ggplot2::aes(alpha = value)) +
20
#'   adjust_alpha_scale(plot_data, "Transparency Scale")
21
#'
22
adjust_alpha_scale <- function(data, name, range = c(0.2, 0.8)) {
23
  min_val <- min(data$value, na.rm = TRUE)  # Calculate minimum value, excluding NA
24
  max_val <- max(data$value, na.rm = TRUE)  # Calculate maximum value, excluding NA
25
26
  # Apply scale_alpha_continuous from 'ggplot2' to adjust transparency
27
  scale_alpha_continuous(
28
    name = name,  # Legend title
29
    limits = c(min_val, max_val),  # Set the data range for alpha scaling
30
    range = range,  # Set the alpha transparency range
31
    guide = guide_legend(keywidth = 0.65, keyheight = 0.35, order = 2)  # Customize legend appearance
32
  )
33
}