### Install scales R Package Source: https://github.com/r-lib/scales/blob/main/README.md This snippet shows how to install the 'scales' R package. It can be installed from CRAN or the development version from GitHub using 'pak'. ```r install.packages("scales") # Or the development version from Github: # install.packages("pak") pak::pak("r-lib/scales") ``` -------------------------------- ### Karen Package Example Execution Error Source: https://github.com/r-lib/scales/blob/main/revdep/problems.md This snippet shows an error encountered while running examples for the Karen package. The error occurs within the 'get.fit' function, specifically in a conditional statement where a missing value is encountered where TRUE/FALSE is needed, leading to the optimization failing. ```R Running examples in ‘Karen-Ex.R’ failed The error most likely occurred in: > ### Name: get.cdn > ### Title: Get the cell differentiation network from a fitted Kalman > ### Reaction Network. > ### Aliases: get.cdn > > ### ** Examples > ... n. of clones: 2 nSmooth = 0; error = 1000; r0 = 1; r1 = 1 Complete log-likelihood optimization... final value -nan stopped after 0 iterations DONE Error in if (f.old - f.new < 0 | (nSmoothingSteps > 0 & curr.opt$convergence %in% : missing value where TRUE/FALSE needed Calls: get.fit Execution halted ``` -------------------------------- ### Interpolation with qualitative palettes in R Source: https://github.com/r-lib/scales/blob/main/tests/testthat/_snaps/colour-mapping.md Shows an example where qualitative palettes can interpolate under certain conditions. It also demonstrates handling of a 'n too large' warning from `RColorBrewer::brewer.pal`. ```R result <- pal(letters[1:20]) ``` -------------------------------- ### Overhauled Examples for Scales Functions in R Source: https://github.com/r-lib/scales/blob/main/NEWS.md Updates all examples for breaks and labels functions to utilize new demo functions: `demo_continuous()`, `demo_discrete()`, and `demo_log10()`. This provides clearer demonstrations of how to use these functions with ggplot2. ```R library(scales) library(ggplot2) # Example using demo_continuous with ggplot2 demo_continuous( breaks = breaks_extended(n = 5), labels = labels_dollar() ) + geom_point(aes(y = value)) # Example using demo_log10 demo_log10( breaks = breaks_log10(), labels = labels_log(base = 10) ) + geom_point(aes(y = value)) ``` -------------------------------- ### Restoring Hue Palette Behavior with h.start in R Source: https://github.com/r-lib/scales/blob/main/NEWS.md Fixes an issue where `hue_pal()` did not respect the `h.start` argument. This ensures that the starting hue of the color palette is correctly applied. ```R library(scales) # Example: Setting the starting hue hue_pal(h.start = 180) # Example: Default behavior hue_pal() ``` -------------------------------- ### Handling skewed data with col_quantile in R Source: https://github.com/r-lib/scales/blob/main/tests/testthat/_snaps/colour-mapping.md Demonstrates how `col_quantile` handles skewed data. When the domain is explicitly provided (`x`), it warns that fewer unique colors can be allocated than requested due to skewness. When the domain is `NULL`, it produces the same warning. ```R x <- c(1:5, rep(10, 10)) col <- col_quantile("RdYlBu", domain = x, n = 7)(x) ``` ```R col <- col_quantile("RdYlBu", domain = NULL, n = 7)(x) ``` -------------------------------- ### R: Byte formatter with symbol designator 'k' Source: https://github.com/r-lib/scales/blob/main/tests/testthat/_snaps/label-bytes.md This example shows the `number_bytes` function in R-lib/scales when a symbol designator 'k' is provided. It illustrates the warning message indicating that 'k' will be changed to the default 'auto' and shows the resulting output. ```r number_bytes(c(50, 400, 502, NA), symbol = "k") ``` -------------------------------- ### R: Byte formatter with 'KiB' symbol and 'si' units Source: https://github.com/r-lib/scales/blob/main/tests/testthat/_snaps/label-bytes.md This example illustrates the `number_bytes` function when 'KiB' is provided as the symbol and 'si' units are specified. It includes the warning that 'KiB' is changed to 'auto' and the output formatted using SI units (kB, MB). ```r number_bytes(1024^(1:2), "KiB", units = "si") ``` -------------------------------- ### Handle NA for out-of-domain values with col_factor Source: https://github.com/r-lib/scales/blob/main/tests/testthat/_snaps/colour-mapping.md Demonstrates how `col_factor` assigns NA to values outside the specified domain when `na.color` is set to NA. This is useful for ensuring clarity when data falls outside expected ranges. ```R col_factor(bw, letters, na.color = NA)("foo") ``` -------------------------------- ### Handle NA for out-of-domain values with col_numeric Source: https://github.com/r-lib/scales/blob/main/tests/testthat/_snaps/colour-mapping.md Shows how `col_numeric` assigns NA to values outside the specified domain (e.g., -1 and 2 for a 0:1 domain) when `na.color` is set to NA. A warning indicates that these values are outside the scale. ```R col_numeric(bw, c(0, 1), na.color = NA)(-1) ``` ```R col_numeric(bw, c(0, 1), na.color = NA)(2) ``` -------------------------------- ### Factor matching in R color scales Source: https://github.com/r-lib/scales/blob/main/tests/testthat/_snaps/colour-mapping.md This snippet demonstrates that factors in R color scales match by name, not by position. A warning is issued if values are outside the color scale. ```R col <- pal(letters[10:20]) ``` -------------------------------- ### Handle NA for out-of-domain values with col_quantile Source: https://github.com/r-lib/scales/blob/main/tests/testthat/_snaps/colour-mapping.md Illustrates `col_quantile`'s behavior with values outside the defined domain (e.g., -1 and 2 for a 0:1 domain). It shows that these values are treated as NA when `na.color` is NA, accompanied by a warning. ```R col_quantile(bw, 0:1, na.color = NA)(-1) ``` ```R col_quantile(bw, 0:1, na.color = NA)(2) ``` -------------------------------- ### R: Byte formatter error for multi-element symbol vector Source: https://github.com/r-lib/scales/blob/main/tests/testthat/_snaps/label-bytes.md This example demonstrates the error generated by `number_bytes` when a symbol vector with multiple elements ('kB', 'MB') is passed. It highlights the validation error for the `symbol` length. ```r number_bytes(symbol = c("kB", "MB")) ``` -------------------------------- ### Interpolation behavior of qualitative palettes in R Source: https://github.com/r-lib/scales/blob/main/tests/testthat/_snaps/colour-mapping.md Illustrates that qualitative palettes in R, such as `pal`, do not interpolate by default. Values outside the scale are treated as NA, and a warning is generated. ```R pal(letters[6]) ``` -------------------------------- ### as.transform Error Handling with Non-Character Input (R) Source: https://github.com/r-lib/scales/blob/main/tests/testthat/_snaps/trans.md Demonstrates how the as.transform function in R generates an error when provided with a numeric input instead of a character vector or transform object. This ensures type safety and guides users toward correct usage. ```r as.transform(1) ``` -------------------------------- ### ggprism Package Test Errors Source: https://github.com/r-lib/scales/blob/main/revdep/problems.md This snippet captures the error output from running the 'tinytest.R' script for the ggprism package. It indicates that 4 out of 156 tests failed, with specific mismatches noted in 'test-add_pvalue.R' and 'test-scale_shape_prism.R'. A warning about the deprecation of the S3 guide system in ggplot2 is also present. ```R if ( requireNamespace("tinytest", quietly=TRUE) ){ tinytest::test_package("ggprism") } test-add_pvalue.R............. 0 tests test-add_pvalue.R............. 0 tests ... diff| 1 string mismatch ----- FAILED[data]: test-scale_shape_prism.R<20--20> call| expect_equal(class(p1), "function") diff| Lengths (1, 3) differ (string compare on first 1) diff| 1 string mismatch Error: 4 out of 156 tests failed In addition: Warning message: The S3 guide system was deprecated in ggplot2 3.5.0. ℹ It has been replaced by a ggproto system that can be extended. Execution halted ``` -------------------------------- ### trans Print Method for New Transformations (R) Source: https://github.com/r-lib/scales/blob/main/tests/testthat/_snaps/trans.md Shows the output of the print method for a new transformation created using new_transform. This demonstrates how the trans function provides a concise summary of the defined transformation, including its name and domain. ```r new_transform("test", transform = identity, inverse = identity) ``` -------------------------------- ### Create Qualitative Color Palettes with Brewer Source: https://context7.com/r-lib/scales/llms.txt Generates discrete color scales using ColorBrewer palettes, supporting sequential, diverging, and qualitative schemes. Allows customization by palette name, type, and direction. ```r library(scales) # Qualitative palette (default) pal_brewer(type = "qual", palette = "Set2")(5) # Sequential palette by name pal_brewer(type = "seq", palette = "Blues")(5) # Diverging palette pal_brewer(type = "div", palette = "RdYlBu")(7) # Reverse color order pal_brewer(palette = "Greens", direction = -1)(5) # Use with base R plotting colors <- pal_brewer(type = "qual", palette = "Dark2")(3) plot(1:3, 1:3, col = colors, pch = 19, cex = 3) # Use palette by numeric index instead of name pal_brewer(type = "qual", palette = 2)(4) # Visualize palette show_col(pal_brewer(type = "div", palette = "Spectral")(11)) ``` -------------------------------- ### Create Perceptually Uniform Color Palettes with Viridis Source: https://context7.com/r-lib/scales/llms.txt Generates perceptually uniform and colorblind-friendly color palettes using the Viridis scheme. Supports different options (magma, plasma, inferno, turbo), alpha transparency, and subsetting of the color range. ```r library(scales) # Default viridis palette pal_viridis()(10) # Different viridis options pal_viridis(option = "magma")(5) pal_viridis(option = "plasma")(5) pal_viridis(option = "inferno")(5) # Control alpha transparency pal_viridis(alpha = 0.5)(5) # Use subset of color range with begin and end pal_viridis(begin = 0.2, end = 0.8)(5) # Reverse direction pal_viridis(direction = -1)(5) # Visualize different options show_col(pal_viridis(option = "turbo")(20)) ``` -------------------------------- ### Karen Package Rd File Checking Note Source: https://github.com/r-lib/scales/blob/main/revdep/problems.md This snippet contains notes from checking the Rd files for the Karen package. It highlights multiple instances where 'Lost braces in \itemize' errors were detected, suggesting that \describe should be used instead for better formatting. ```R checkRd: (-1) get.fit.Rd:46: Lost braces in \itemize; meant \describe ? checkRd: (-1) get.fit.Rd:47: Lost braces in \itemize; meant \describe ? checkRd: (-1) get.fit.Rd:48-49: Lost braces in \itemize; meant \describe ? checkRd: (-1) get.fit.Rd:50-51: Lost braces in \itemize; meant \describe ? checkRd: (-1) get.fit.Rd:52-54: Lost braces in \itemize; meant \describe ? checkRd: (-1) get.fit.Rd:55: Lost braces in \itemize; meant \describe ? checkRd: (-1) get.fit.Rd:56: Lost braces in \itemize; meant \describe ? checkRd: (-1) get.fit.Rd:57-60: Lost braces in \itemize; meant \describe ? checkRd: (-1) get.fit.Rd:61-62: Lost braces in \itemize; meant \describe ? checkRd: (-1) get.fit.Rd:63-64: Lost braces in \itemize; meant \describe ? ... checkRd: (-1) get.fit.Rd:73: Lost braces in \itemize; \value handles \item{}{} directly checkRd: (-1) get.fit.Rd:74: Lost braces in \itemize; \value handles \item{}{} directly checkRd: (-1) get.fit.Rd:75: Lost braces in \itemize; \value handles \item{}{} directly checkRd: (-1) get.fit.Rd:76: Lost braces in \itemize; \value handles \item{}{} directly checkRd: (-1) get.fit.Rd:77: Lost braces in \itemize; \value handles \item{}{} directly checkRd: (-1) get.fit.Rd:78: Lost braces in \itemize; \value handles \item{}{} directly checkRd: (-1) get.fit.Rd:79: Lost braces in \itemize; \value handles \item{}{} directly checkRd: (-1) get.fit.Rd:80: Lost braces in \itemize; \value handles \item{}{} directly checkRd: (-1) get.sim.trajectories.Rd:66: Lost braces in \itemize; \value handles \item{}{} directly checkRd: (-1) get.sim.trajectories.Rd:67: Lost braces in \itemize; \value handles \item{}{} directly ``` -------------------------------- ### Karen Package Vignette Rebuilding Warning Source: https://github.com/r-lib/scales/blob/main/revdep/problems.md This snippet details a warning during the rebuilding of the 'Karen.ltx' vignette for the Karen package. The error indicates that the LaTeX file 'realboxes.sty' was not found, preventing the generation of a PDF output. ```LaTeX Error(s) in re-building vignettes: ... --- re-building ‘Karen.ltx’ using tex Error: processing vignette 'Karen.ltx' failed with diagnostics: Running 'texi2dvi' on 'Karen.ltx' failed. LaTeX errors: ! LaTeX Error: File `realboxes.sty' not found. Type X to quit or to proceed, or enter new name. (Default extension: sty) ... l.12 \usepackage {amssymb}^^M ! ==> Fatal error occurred, no output PDF file produced! --- failed re-building ‘Karen.ltx’ SUMMARY: processing the following file failed: ‘Karen.ltx’ Error: Vignette re-building failed. Execution halted ``` -------------------------------- ### Formatting Byte Sizes with label_bytes() in R Source: https://github.com/r-lib/scales/blob/main/NEWS.md Illustrates the use of `label_bytes()` to format byte sizes, ensuring correct unit selection based on the `scale` argument. This is particularly useful for displaying file sizes or network transfer rates. ```R library(scales) # Example formatting byte sizes label_bytes()(c(1024, 1048576, 1073741824)) # Example with a specific scale label_bytes(scale = 1000)(c(1000, 1000000, 1000000000)) ``` -------------------------------- ### Use scales Color Palettes Source: https://github.com/r-lib/scales/blob/main/README.md Shows how to use color palettes from the 'scales' package, such as `pal_viridis` and `pal_brewer`, for visualizations. It also demonstrates how to set these palettes as default colors for base R plotting functions using `palette()`. ```r library(scales) # pull a list of colours from any palette pal_viridis()(4) #> [1] "#440154FF" "#31688EFF" "#35B779FF" "#FDE725FF" # use in combination with baseR `palette()` to set new defaults palette(pal_brewer(palette = "Set2")(4)) par(mar = c(5, 5, 1, 1)) plot(Sepal.Length ~ Sepal.Width, data = iris, col = Species, pch = 20) ``` -------------------------------- ### Register Palettes in scales Source: https://github.com/r-lib/scales/blob/main/NEWS.md Demonstrates how to register palettes in the scales package using `set_palette()` and retrieve them using `get_palette()`. This allows for better management and organization of color palettes within the package. ```R # The scales package now keeps track of known palettes. These can be retrieved # using `get_palette()` or registered using `set_palette()` (#396). ``` -------------------------------- ### Creating Logarithmic Scales with label_log() in R Source: https://github.com/r-lib/scales/blob/main/NEWS.md Demonstrates the creation of logarithmic scales using `label_log()`, which displays the base and a superscript exponent. This is suitable for axes representing data with wide-ranging magnitudes. ```R library(scales) # Example of a base-10 logarithmic label label_log(base = 10)("1e6") # Example with a different base label_log(base = 2)(1024) ``` -------------------------------- ### as.transform Error Handling for Unknown Transforms (R) Source: https://github.com/r-lib/scales/blob/main/tests/testthat/_snaps/trans.md Illustrates the error message produced by as.transform when it cannot find a corresponding transform function for the given character input. This helps in debugging and identifying missing transformation definitions. ```r as.transform("x") ``` -------------------------------- ### R `transform_compose()`: Correct Domain Generation Source: https://github.com/r-lib/scales/blob/main/tests/testthat/_snaps/trans-compose.md Shows how to correctly use `transform_compose()` to generate a valid domain for a sequence of transformations. This is useful for data preprocessing and ensuring transformations are mathematically sound. ```r transform_compose("sqrt", "reverse", "log")$domain ``` -------------------------------- ### Reversing Color Palettes Source: https://github.com/r-lib/scales/blob/main/NEWS.md The 'reverse' parameter is now available for col_numeric(), col_bin(), col_quantile(), and col_factor(). This allows color palettes to be applied in the opposite order (high-to-low instead of low-to-high). ```r # Example usage for reverse parameter # col_numeric(palette = "viridis", domain = NULL, reverse = TRUE)(1:5) ``` -------------------------------- ### Binning Interval Closure with col_bin() and col_quantile() Source: https://github.com/r-lib/scales/blob/main/NEWS.md col_bin() and col_quantile() now accept a 'right' argument, which is passed to base::cut(). This argument determines whether the bin or quantile intervals are closed on the right (and open on the left) or vice versa. ```r # Example usage for 'right' argument # col_bin(bins = 3, right = FALSE)(1:10) # col_quantile(quantiles = 4, right = TRUE)(1:20) ``` -------------------------------- ### R: Byte formatter with 'kB' symbol and 'binary' units Source: https://github.com/r-lib/scales/blob/main/tests/testthat/_snaps/label-bytes.md This snippet demonstrates the `number_bytes` function with a 'kB' symbol and 'binary' units. It shows the warning that 'kB' will be changed to 'auto' and the output formatted in binary units (KiB, MiB). ```r number_bytes(1024^(1:2), "kB", units = "binary") ``` -------------------------------- ### Numeric and Binning Color Functions with Viridis Palettes Source: https://github.com/r-lib/scales/blob/main/NEWS.md col_numeric(), col_bin(), col_quantile(), and col_factor() now support viridis color palettes ('magma', 'inferno', 'plasma', 'viridis'). These can be specified using the 'palette' argument. ```r # Example usage for viridis palettes # col_numeric(palette = "viridis", domain = NULL)(1:5) # col_factor(palette = "magma", domain = c("A", "B", "C"))(letters[1:3]) ``` -------------------------------- ### Create and Apply Logarithmic Transformations Source: https://context7.com/r-lib/scales/llms.txt Creates and applies transformations, such as logarithmic, square root, and reverse transformations, to data. Includes automatic generation of breaks and labels for transformed data. ```r library(scales) # Built-in logarithmic transformation log_trans <- transform_log10() log_trans$transform(c(1, 10, 100, 1000)) log_trans$inverse(c(0, 1, 2, 3)) # Create custom transformation log_plus_3 <- new_transform( name = "log_plus_3", transform = function(x) log(x + 3), inverse = function(x) exp(x) - 3, breaks = breaks_log(), domain = c(-3, Inf) ) log_plus_3$transform(c(0, 7, 97)) log_plus_3$inverse(c(1.098612, 2.302585, 4.605170)) # Square root transformation sqrt_trans <- transform_sqrt() sqrt_trans$transform(c(0, 1, 4, 9, 16)) # Reverse transformation (for reversed axes) rev_trans <- transform_reverse() rev_trans$transform(c(1, 2, 3, 4, 5)) # Date transformation for temporal data date_trans <- transform_date() dates <- as.Date(c("2020-01-01", "2020-07-01", "2021-01-01")) date_trans$transform(dates) # Asinh transformation (handles negative values) asinh_trans <- transform_asinh() asinh_trans$transform(c(-100, -10, 0, 10, 100)) ``` -------------------------------- ### Composing Arbitrary Transformations with compose_trans() in R Source: https://github.com/r-lib/scales/blob/main/NEWS.md Illustrates how to combine multiple transformations sequentially using `compose_trans()`. This allows for the creation of complex scales, such as a reversed log-10 scale, by passing a character vector of transformer names. ```R library(scales) # Example: Reverse log-10 scale scale_y_continuous(trans = c("log10", "reverse")) # Example: Log base 2 then square root scale_x_continuous(trans = c("log2", "sqrt")) ``` -------------------------------- ### Handle Training on Factor Data in scales Source: https://github.com/r-lib/scales/blob/main/NEWS.md Describes how the `DiscreteRange` class now keeps track of whether it has been trained on factor data, with the new `fct` argument of `train_discrete()` used to prevent sorting of the range after multiple training passes. ```R # The `DiscreteRange` class now keeps track on whether it has been trained on # factor data. # Training on factor data no longer sorts the range after multiple training # passes if the new `fct` argument of `train_discrete()` is used (#383) ``` -------------------------------- ### Implement Labeling with Dictionaries in scales Source: https://github.com/r-lib/scales/blob/main/NEWS.md Introduces `label_dictionary()` for named lookup of labels. This function provides a way to map specific values to corresponding labels, enhancing the flexibility of data representation. ```R # New `label_dictionary()` for named lookup of labels (#458). ``` -------------------------------- ### Format Bytes with label_bytes() Source: https://github.com/r-lib/scales/blob/main/NEWS.md The label_bytes() function provides a convenient interface for formatting byte sizes. It supports SI, binary, and automatic units, always using 'B' as the symbol for bytes. Auto units dynamically determine the symbol based on the value. ```r label_bytes("auto_binary")(1024^(1:3)) #> [1] "1 kiB" "1 MiB" "1 GiB" ``` -------------------------------- ### Internationalizing Date and Time Labels with locale in R Source: https://github.com/r-lib/scales/blob/main/NEWS.md Shows how to specify the locale for generating day and month names using `label_date()` and `label_time()`. This enables internationalization of date and time labels in visualizations. ```R library(scales) # Example using a French locale label_date(locale = "fr_FR") # Example using a Spanish locale label_time(locale = "es_ES") ``` -------------------------------- ### Customizing Number Formatting with label_number() in R Source: https://github.com/r-lib/scales/blob/main/NEWS.md Demonstrates how to control the styling of positive and negative numbers, as well as apply custom scaling using prefixes and suffixes. This function is useful for creating human-readable labels for numerical axes in plots. ```R library(scales) # Example using style_positive and style_negative label_number(style_positive = "+", style_negative = "-") # Example using prefix and scale_cut for large numbers label_number(prefix = "$", scale_cut = cut_long_scale()) # Example mimicking deprecated label_number_si with short scale label_number(scale_cut = cut_scale_short()) # Example with SI prefixes label_number(scale_cut = cut_SI("m")) ``` -------------------------------- ### Controlling Negative Number Formatting with style_negative in R Source: https://github.com/r-lib/scales/blob/main/NEWS.md Introduces `style_negative` as the preferred method for formatting negative numbers, deprecating the `negative_parens` argument. This allows for consistent and customizable negative number representation. ```R library(scales) # Example: Using parens for negative numbers label_dollar(style_negative = "parens") # Example: Using a minus sign label_dollar(style_negative = "minus") ``` -------------------------------- ### Implement Color Manipulation Functions in scales Source: https://github.com/r-lib/scales/blob/main/NEWS.md Introduces color manipulation functions such as `col_shift()`, `col_saturate()`, `col_darker()`, `col_lighter()`, and `col_mix()`. These functions allow for programmatic adjustments to colors within the scales package. ```R # Added colour manipulation functions: `col_shift()`, `col_saturate()`, # `col_darker()`, `col_lighter()` and `col_mix()` (@teunbrand, #423) ``` -------------------------------- ### R: Validate byte unit designator Source: https://github.com/r-lib/scales/blob/main/tests/testthat/_snaps/label-bytes.md This snippet demonstrates how the `label_bytes` function in R-lib/scales handles unknown unit designators, resulting in an error. It highlights the expected units and the error message for invalid input. ```r label_bytes("unit")(0) ``` -------------------------------- ### Compose Label Formatting Functions in scales Source: https://github.com/r-lib/scales/blob/main/NEWS.md Introduces `compose_label()` to chain together label formatting functions. This function facilitates creating complex label formats by combining simpler formatting functions. ```R # New function `compose_label()` to chain together label formatting functions # (#462) ``` -------------------------------- ### Format Numbers with SI units using label_number_si() Source: https://github.com/r-lib/scales/blob/main/NEWS.md label_number_si() formats numeric vectors using standard SI abbreviations (K, M, G, T) for magnitudes. It scales and labels individual values based on their size. ```r # Example usage for label_number_si() # label_number_si()(c(1500, 2500000, 1.2e9)) #> [1] "1.5K" "2.5M" "1.2G" ``` -------------------------------- ### Correct Domain Types for Time and Date Transformations in R Source: https://github.com/r-lib/scales/blob/main/NEWS.md Fixes an issue where `time_trans()` and `date_trans()` had incorrect domain types, preventing transformations without errors. This ensures proper functionality for time and date-based scales. ```R library(scales) # Example: Using time transformation scale_x_continuous(trans = time_trans()) # Example: Using date transformation scale_y_continuous(trans = date_trans()) ``` -------------------------------- ### Define Custom Log Transformation with scales::new_transform Source: https://github.com/r-lib/scales/blob/main/README.md This snippet defines a new logarithmic transformation named 'logp' using the `new_transform` function from the scales package. It includes the forward transform, inverse transform, and break point generation. This is useful for creating custom scales in data visualization. ```r transform_logp3 <- new_transform( name = "logp", transform = function(x) log(x + 3), inverse = function(x) exp(x) - 3, breaks = log_breaks() ) ``` -------------------------------- ### Format P-values with label_pvalue() Source: https://github.com/r-lib/scales/blob/main/NEWS.md label_pvalue() formats p-values, reporting values close to 1 (based on accuracy) as '>0.99'. The prefixes used can be customized with the 'prefix' argument. ```r # Example usage for label_pvalue() # label_pvalue()(c(0.001, 0.05, 0.995), accuracy = 0.01) #> [1] "0.001" ">0.99" ``` -------------------------------- ### Handling Units in breaks_width() in R Source: https://github.com/r-lib/scales/blob/main/NEWS.md Shows how `breaks_width()` now supports various units, including time-based units like '3 months' in the `offset` argument. This improves flexibility when defining axis breaks based on time intervals. ```R library(scales) # Example with time units in offset breaks_width(offset = "3 months") # Example with other units breaks_width(width = "1 week", offset = "2 days") ``` -------------------------------- ### Format Numeric Values with Scales Source: https://context7.com/r-lib/scales/llms.txt Formats numeric values with customizable precision, thousands separators, and scaling. It supports automatic precision adjustment, comma separators, short scale suffixes (K, M, B, T), SI units, and custom prefix/suffix options. It also allows manual scaling for data in different units. ```r library(scales) # Basic number formatting with automatic precision x <- c(0.1, 1, 1000, 1000000) label_number()(x) # [1] "0.1" "1.0" "1 000.0" "1 000 000.0" # Format with comma separators label_comma()(x) # [1] "0.1" "1" "1,000" "1,000,000" # Scale large numbers with short scale suffixes (K, M, B, T) label_number(scale_cut = cut_short_scale())(c(1000, 1e6, 1e9, 1e12)) # [1] "1K" "1M" "1B" "1T" # Scale with SI units label_number(scale_cut = cut_si("g"))(c(0.001, 1, 1000)) # [1] "1 mg" "1 g" "1 kg" # Custom prefix/suffix and style options label_number( prefix = "$", suffix = " USD", big.mark = ",", decimal.mark = ".", style_positive = "plus", style_negative = "parens" )(c(-100, 0, 100)) # [1] "($100.00 USD)" "$0.00 USD" "+$100.00 USD" # Manual scaling for data in different units label_number(scale = 1/1000, suffix = "k")(c(1000, 5000, 10000)) # [1] "1k" "5k" "10k" ``` -------------------------------- ### R `transform_compose()`: No Transformers Error Source: https://github.com/r-lib/scales/blob/main/tests/testthat/_snaps/trans-compose.md Demonstrates the error produced by `transform_compose()` when no transformation functions are provided. This ensures that the function is used with at least one valid transformer. ```r transform_compose() ``` -------------------------------- ### R `transform_compose()`: Invalid Domain Sequence Error Source: https://github.com/r-lib/scales/blob/main/tests/testthat/_snaps/trans-compose.md Illustrates the error scenario where a sequence of transformations provided to `transform_compose()` results in an invalid domain. This helps users understand the constraints on combining transformation functions. ```r transform_compose("sqrt", "reverse", "log10") ``` -------------------------------- ### New Naming Scheme for Breaks and Labels in R Source: https://github.com/r-lib/scales/blob/main/NEWS.md Introduces a new naming convention for functions related to axis breaks and labels. Functions generating breaks from limits are now prefixed with `breaks_`, and functions generating labels from breaks are prefixed with `labels_`. ```R library(scales) # New naming convention examples: # breaks_width(), breaks_log10(), breaks_pretty() # labels_ordinal(), labels_auto(), labels_dollar() ``` -------------------------------- ### Format date-time sequences with label_date_short in R Source: https://github.com/r-lib/scales/blob/main/tests/testthat/_snaps/label-date.md This snippet illustrates the application of `label_date_short()` for formatting sequences of date-times in R. It covers intervals of hours, days, months, and years, showcasing the function's flexibility with different granularities of time data. ```R # date-times jan1 <- as.POSIXct("2010-01-01", tz = "UTC") dformat(seq(jan1, length = 6, by = "3 hours")) dformat(seq(jan1, length = 6, by = "7 day")) dformat(seq(jan1, length = 6, by = "3 month")) dformat(seq(jan1, length = 6, by = "1 year")) ``` -------------------------------- ### Format Currency Values with Scales Source: https://context7.com/r-lib/scales/llms.txt Formats currency values with automatic cent detection and locale-specific formatting. It handles large values by omitting cents and supports custom currency symbols, separators, and negative value styling. It can also scale large currency values using K/M/B suffixes. ```r library(scales) # Automatic cent formatting for values with fractional parts label_currency()(c(1.50, 10.99, 100)) # [1] "$1.50" "$10.99" "$100.00" # Large values default to no cents label_currency()(c(1000, 50000, 1000000)) # [1] "$1,000" "$50,000" "$1,000,000" # Custom currency symbols and formatting yen <- label_currency( prefix = "¥", suffix = "", big.mark = ",", decimal.mark = "." ) yen(c(1000, 1500, 2000)) # [1] "¥1,000" "¥1,500" "¥2,000" # European format with parentheses for negative values euro <- label_currency( prefix = "€", big.mark = ".", decimal.mark = ",", style_negative = "parens" ) euro(c(-100, 0, 100)) # [1] "(€100,00)" "€0,00" "€100,00" # Scale large currency values with K/M/B suffixes label_currency(scale_cut = cut_short_scale())(c(1e3, 1e6, 1e9)) # [1] "$1K" "$1M" "$1B" ``` -------------------------------- ### Format date sequences with label_date_short in R Source: https://github.com/r-lib/scales/blob/main/tests/testthat/_snaps/label-date.md This snippet demonstrates how to use the `label_date_short()` function to format sequences of dates in R. It shows the output for daily, monthly, and yearly intervals, highlighting the function's ability to adapt its output based on the time span. ```R dformat <- label_date_short() # dates jan1 <- as.Date("2010-01-01") dformat(seq(jan1, length = 8, by = "7 day")) dformat(seq(jan1, length = 8, by = "3 month")) dformat(seq(jan1, length = 8, by = "1 year")) ``` -------------------------------- ### Utilize Timespan Functionality in scales Source: https://github.com/r-lib/scales/blob/main/NEWS.md Adds better support for `difftime` objects using `label_timespan()`, `breaks_timespan()`, and `transform_timespan()`. Provides functionality for adding correct unit suffixes to timespan data, finding pleasant breakpoints across time units, and wrapping everything together. ```R # Add better support for `difftime` objects. `label_timespan()` adds # functionality for adding correct unit suffix to timespan data, # `breaks_timespan()` adds functionality for finding pleasant breakpoints across # the various bases in time units, while `transform_timespan()` wraps it all # together and provides an alternative to `transform_hms()` (#212) ``` -------------------------------- ### R: Byte formatter error for empty symbol vector Source: https://github.com/r-lib/scales/blob/main/tests/testthat/_snaps/label-bytes.md This code snippet shows the error handling in `number_bytes` when an empty character vector is provided for the `symbol` argument. It demonstrates the validation error from `validate_byte_symbol`. ```r number_bytes(symbol = character()) ``` -------------------------------- ### Add Inverse Hyperbolic Sine Transformation in scales Source: https://github.com/r-lib/scales/blob/main/NEWS.md Adds an inverse (area) hyperbolic sine transformation `transform_asinh()`. This provides a logarithm-like transformation of a space, but which accommodates negative values. ```R # Add an inverse (area) hyperbolic sine transformation `transform_asinh()`, # which provides a logarithm-like transformation of a space, but which # accommodates negative values (#297) ``` -------------------------------- ### Rescale difftime Objects in scales Source: https://github.com/r-lib/scales/blob/main/NEWS.md Adds a rescale method for `difftime` objects. This allows for rescaling time differences, enabling consistent handling of time-based data within the scales package. ```R # Add a rescale method for `difftime` objects (#382) ``` -------------------------------- ### Handle Out-of-Bounds Values (R) Source: https://context7.com/r-lib/scales/llms.txt Functions to manage values that fall outside a specified range. oob_squish_infinite clips infinite values, oob_keep retains all values, and oob_discard removes out-of-bounds values. ```r # Squish including infinite values oob_squish_infinite(x, range = c(0, 1)) # [1] 0.0 0.0 0.5 1.0 1.0 1.0 # Keep all values unchanged oob_keep(x, range = c(0, 1)) # [1] -1.0 0.0 0.5 1.0 2.0 Inf # Discard out-of-bounds values oob_discard(x, range = c(0, 1)) # [1] 0.0 0.5 1.0 ``` -------------------------------- ### Format Date and Time Values with Scales Source: https://context7.com/r-lib/scales/llms.txt Formats date and time values using flexible format strings and automatic abbreviation. It supports standard date formatting (e.g., YYYY-MM-DD, Month DD, YYYY) and abbreviated formats. It also includes functions for short date formats that only show changed components, time formatting, and timespan formatting for durations. ```r library(scales) # Standard date formatting dates <- as.Date(c("2020-01-15", "2020-06-20", "2020-12-31")) label_date(format = "%Y-%m-%d")(dates) # [1] "2020-01-15" "2020-06-20" "2020-12-31" label_date(format = "%B %d, %Y")(dates) # [1] "January 15, 2020" "June 20, 2020" "December 31, 2020" # Abbreviated date format label_date(format = "%b '%y")(dates) # [1] "Jan '20" "Jun '20" "Dec '20" # Short format that only shows changed components date_seq <- seq(as.Date("2020-01-01"), as.Date("2020-12-31"), by = "2 months") label_date_short()(date_seq) # Shows only year on first occurrence, then just months # Time formatting times <- as.POSIXct(c("2020-01-01 08:30:00", "2020-01-01 14:45:30")) label_time(format = "%H:%M")(times) # [1] "08:30" "14:45" label_time(format = "%I:%M %p")(times) # [1] "08:30 AM" "02:45 PM" # Localized date formatting (requires stringi package) # label_date(format = "%B %d", locale = "fr")(dates) # [1] "janvier 15" "juin 20" "décembre 31" # Timespan formatting for durations durations <- c(1, 60, 3600, 86400, 604800) label_timespan(unit = "secs")(durations) # [1] "1s" "1m" "1h" "1d" "1w" ``` -------------------------------- ### Rename Transformation Functions in scales Source: https://github.com/r-lib/scales/blob/main/NEWS.md Transformation functions have been renamed to `transform_*`-prefixed names. The S3 class of transformations has been renamed from `"trans"` to `"transform"`. `new_transform()` replaces `trans_new()` and `trim_to_domain()` replaces `trans_range()`. All old functions are kept for posterity. ```R # Transformation function have been renamed to `transform_*`-prefixed names # instead of `*_trans`-suffixed names. This allows for a better tab-completion # search of transformations. The S3 class of transformations has been # renamed from `"trans"` to `"transform"`. `new_transform()` replaces # `trans_new()` and `trim_to_domain()` replaces `trans_range()`. All old # functions are kept for posterity. ``` -------------------------------- ### Control Axis Breaks and Labels with scales Source: https://github.com/r-lib/scales/blob/main/README.md Demonstrates using 'scales' functions like `breaks_width`, `label_date`, `label_number`, `cut_short_scale`, `breaks_extended`, `label_date_short`, and `label_dollar` to customize axis breaks and labels in ggplot2 plots. These functions help in formatting dates, numbers, and applying specific scaling strategies for better readability. ```r library(ggplot2) library(dplyr, warn.conflicts = FALSE) library(lubridate, warn.conflicts = FALSE) txhousing %>% mutate(date = make_date(year, month, 1)) %>% group_by(city) %>% filter(min(sales) > 5e2) %>% ggplot(aes(date, sales, group = city)) + geom_line(na.rm = TRUE) + scale_x_date( NULL, breaks = scales::breaks_width("2 years"), labels = scales::label_date("'%y") ) + scale_y_log10( "Total sales", labels = scales::label_number(scale_cut = scales::cut_short_scale()) ) ``` ```r economics %>% filter(date < ymd("1970-01-01")) %>% ggplot(aes(date, pce)) + geom_line() + scale_x_date(NULL, breaks = scales::breaks_width("3 months"), labels = scales::label_date_short() ) + scale_y_continuous("Personal consumption expenditures", breaks = scales::breaks_extended(8), labels = scales::label_dollar() ) ``` -------------------------------- ### Format Dates with label_date_short() Source: https://github.com/r-lib/scales/blob/main/NEWS.md label_date_short() creates concise labels for date axes, displaying only the components of a date that have changed since the previous label. This is useful for dense date ranges where only the day or month changes. ```r # Example usage for label_date_short() - actual output depends on input dates # Assuming a sequence of dates like Jan 10, Jan 20, Jan 30, Feb 1 # label_date_short() would produce labels like "Jan 10", "20", "30", "Feb 1" ``` -------------------------------- ### Generate Axis Breaks with Scales Functions Source: https://context7.com/r-lib/scales/llms.txt Generates axis break positions automatically or at specified intervals. It includes functions for equal width breaks with adjustable width and offset, and an extended breaks algorithm (Wilkinson's algorithm) for generating a specified number of breaks. ```r library(scales) # Equal width breaks for numeric data breaks_width(width = 10)(c(0, 100)) # [1] 0 10 20 30 40 50 60 70 80 90 100 # Breaks with offset (e.g., for fiscal years) breaks_width(width = 20, offset = 5)(c(0, 100)) # [1] 5 25 45 65 85 105 # Extended breaks algorithm (Wilkinson's algorithm) breaks_extended(n = 5)(c(0, 37)) # [1] 0 10 20 30 40 breaks_extended(n = 10)(c(0, 37)) # [1] 0 5 10 15 20 25 30 35 40 ``` -------------------------------- ### Improved Precision Calculation with Duplicate and Non-finite Values in R Source: https://github.com/r-lib/scales/blob/main/NEWS.md Enhances the internal `precision()` function to better handle duplicate values and mixes of finite and non-finite values. This ensures more robust and accurate precision calculations. ```R library(scales) # Example with duplicate values precision(c(1.23, 1.23, 4.56)) # Example with non-finite values precision(c(1.23, NA, Inf, -Inf)) ``` -------------------------------- ### French Ordinal Formatting in R Source: https://github.com/r-lib/scales/blob/main/tests/testthat/_snaps/label-ordinal.md Formats numeric vectors into French ordinal strings using French linguistic rules. Demonstrates the default French rules and an alternative rule set for different grammatical agreements. ```r library(scales) ordinal(c(1, 2, 10, 11, NA), rules = ordinal_french()) ``` ```r library(scales) ordinal(c(1, 2, 10, 11, NA), rules = ordinal_french("f", TRUE)) ``` -------------------------------- ### Expand Numeric and Date Ranges (R) Source: https://context7.com/r-lib/scales/llms.txt Expands numeric or date ranges by specified multiplicative or additive constants. Handles zero-width ranges and can be applied to date ranges by converting them to numeric. ```r library(scales) # Expand by 10% on each side (multiplicative) expand_range(c(0, 100), mul = 0.1) # [1] -10 110 # Expand by 5 units on each side (additive) expand_range(c(0, 100), add = 5) # [1] -5 105 # Combine multiplicative and additive expansion expand_range(c(0, 100), mul = 0.05, add = 2) # [1] -7 107 # Handle zero-width ranges expand_range(c(5, 5), zero_width = 1) # [1] 4.5 5.5 expand_range(c(5, 5), mul = 0.1, zero_width = 10) # [1] 4 6 # Expand date ranges date_range <- as.Date(c("2020-01-01", "2020-12-31")) expand_range(as.numeric(date_range), mul = 0.05) # Returns expanded numeric range (can convert back to dates) ``` -------------------------------- ### R: Automatic Number Formatting with label_number_auto Source: https://github.com/r-lib/scales/blob/main/tests/testthat/_snaps/label-number-auto.md Uses `label_number_auto()` to format numeric vectors. This function automatically selects the most appropriate format, switching to scientific notation for very small or large numbers and using comma separators for thousands. It also shows how it handles specific cases like years. ```R library(scales) number_auto <- label_number_auto() # Small numbers number_auto(c(0, 1e-06)) number_auto(c(9e-04, 0.001, 0.0011)) number_auto(c(9e-05, 1e-04, 0.00011)) number_auto(c(9e-06, 1e-05, 1.1e-05)) number_auto(c(9e-07, 1e-06, 1.1e-06)) # Large numbers with commas number_auto(c(999, 1000, 1001)) number_auto(c(999999, 1e+06, 1000001)) number_auto(c(9999999, 1e+07, 10000001)) number_auto(c(99999999, 1e+08, 100000001)) # Specific cases number_auto(c(2010, 2013, 2020)) number_auto(c(-2010, -2013, -2020)) # Shortest representation number_auto(10^(1:7)) ``` -------------------------------- ### Parse Labels with label_parse() Source: https://github.com/r-lib/scales/blob/main/NEWS.md label_parse() generates an expression object that can be used for displaying formatted labels, particularly within ggplot2. It facilitates the creation of mathematical or symbolic labels. ```r # Example usage for label_parse() # label_parse()(c("x^2", "y/z")) ```