diff --git a/.DS_Store b/.DS_Store new file mode 100644 index 0000000..d70aedf Binary files /dev/null and b/.DS_Store differ diff --git a/.Rbuildignore b/.Rbuildignore index 5d4b1be..b647645 100644 --- a/.Rbuildignore +++ b/.Rbuildignore @@ -1,3 +1,18 @@ ^\.github$ ^\.gitignore$ -^docs$ \ No newline at end of file +^docs$ +^\.lib$ +^\.DS_Store$ +^tools$ +^plotcli\.Rcheck$ +^plotcli_.*\.tar\.gz$ +^LICENSE$ +^demo_show\.R$ +^mega_show\.R$ +^ultimate_show\.R$ +^ultra_demo\.R$ +^reproduce_.*$ +^vignettes_test\.R$ +^visual_verification\..*$ +^plotcli_docs\.Rmd$ +^\.claude$ diff --git a/DESCRIPTION b/DESCRIPTION index 33f87c7..1d087f7 100644 --- a/DESCRIPTION +++ b/DESCRIPTION @@ -1,20 +1,25 @@ Package: plotcli Title: Command Line Interface Plotting -Version: 0.1.0 -Date: 2024-04-01 +Version: 0.3.0 +Date: 2026-02-08 Authors@R: c(person("Claas", "Heuer", role = c("aut", "cre"), email = "claasheuer@gmail.com")) Description: The 'plotcli' package provides terminal-based plotting in R. - It supports colored scatter plots, line plots, bar plots, and box plots. The package allows users - to customize plot appearance, add titles, labels, ticks, and legends, and output the plot as a text-based visualization. + It supports colored scatter plots, line plots, bar plots, boxplots, + histograms, density plots, heatmaps, and more. The 'ggplotcli()' function + is a universal converter that renders any 'ggplot2' plot in the terminal + using Unicode Braille characters or ASCII. Features include support for + 27 geom types, faceting (facet_wrap/facet_grid), automatic theme + detection, legends, optimized color mapping, and multiple canvas types. License: LGPL-3 URL: https://github.com/cheuerde/plotcli Encoding: UTF-8 -LazyData: true VignetteBuilder: knitr Depends: R6, ggplot2 -Imports: utils, crayon, knitr, rmarkdown, stringr, rlang +Imports: crayon, stringr, rlang, grDevices, stats Suggests: - testthat (>= 3.0.0) -NeedsCompilation: yes -RoxygenNote: 7.2.3 + testthat (>= 3.0.0), + knitr, + rmarkdown +NeedsCompilation: no +RoxygenNote: 7.3.2 Config/testthat/edition: 3 diff --git a/LICENSE b/LICENSE deleted file mode 100755 index 57de0db..0000000 --- a/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -MIT License - -Copyright (c) 2024 Claas Heuer - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. diff --git a/NAMESPACE b/NAMESPACE index 39ba9f9..52eb90d 100644 --- a/NAMESPACE +++ b/NAMESPACE @@ -3,14 +3,27 @@ S3method("+",plotcli) S3method(cbind,plotcli) S3method(rbind,plotcli) +export(AsciiCanvas) +export(BlockCanvas) +export(BrailleCanvas) +export(Canvas) +export(braille_dot_bit) +export(braille_set_dot) export(bresenham) export(cat_plot_matrix) export(cbind_plots) +export(color_to_term) +export(create_canvas) +export(create_scales) export(format_four_chars) export(get_data_subset) +export(get_geom_handler) export(get_term_colors) export(ggplotcli) +export(init_color_mapping) export(is_braille) +export(is_geom_registered) +export(list_registered_geoms) export(make_colored) export(make_unique_names) export(normalize_data) @@ -20,6 +33,7 @@ export(pclid) export(pclih) export(pclil) export(pclis) +export(pixel_to_braille) export(plotcli) export(plotcli_bar) export(plotcli_box) @@ -29,11 +43,18 @@ export(plotcli_line) export(plotcli_options) export(plotcli_scatter) export(rbind_plots) +export(register_geom) export(remove_color_codes) -import(ggplot2) import(R6) -importFrom("stats", "density") -importFrom(crayon, blue, red, green, yellow, magenta, cyan, silver) -importFrom(knitr, opts_chunk) -importFrom(rmarkdown, html_vignette) -importFrom(utils, head, tail, capture.output) \ No newline at end of file +import(ggplot2) +importFrom(crayon,black) +importFrom(crayon,blue) +importFrom(crayon,cyan) +importFrom(crayon,green) +importFrom(crayon,magenta) +importFrom(crayon,red) +importFrom(crayon,silver) +importFrom(crayon,white) +importFrom(crayon,yellow) +importFrom(grDevices,col2rgb) +importFrom(stats,density) diff --git a/NEWS.md b/NEWS.md new file mode 100644 index 0000000..be595d1 --- /dev/null +++ b/NEWS.md @@ -0,0 +1,112 @@ +# plotcli 0.3.0 + +## New Geom Handlers + +* **11 new geom handlers** bringing total support from 16 to 27 geoms: + `geom_step`, `geom_abline`, `geom_ribbon`, `geom_errorbar`, + `geom_linerange`, `geom_pointrange`, `geom_crossbar`, `geom_rug`, + `geom_label`, `geom_raster`, `geom_violin` + +* **Violin plots**: Proper mirrored density rendering using `violinwidth` + for accurate shape computation + +## Bug Fixes + +* Fixed division by zero when plotting constant data values + (e.g., all y-values identical) - both root cause fix in `get_min_max()` + and defensive guard in `normalize_data()` (Closes #1) + +--- + +# plotcli 0.2.0 + +## Major New Features + +### Enhanced ggplotcli: Universal ggplot2 Converter + +The `ggplotcli()` function has been completely rewritten to render any ggplot2 +plot in the terminal: + +* **16 Supported Geoms**: `geom_point`, `geom_line`, `geom_path`, `geom_bar`, + `geom_col`, `geom_histogram`, `geom_density`, `geom_smooth`, `geom_area`, + `geom_segment`, `geom_hline`, `geom_vline`, `geom_rect`, `geom_text`, + `geom_boxplot`, `geom_tile` + +* **Legend Support**: Automatic legends for color and fill aesthetics + +* **Faceting Support**: Both `facet_wrap()` and `facet_grid()` work automatically + +* **Theme Auto-Detection**: Automatically respects ggplot2 themes - `theme_bw()` + adds borders and grids, `theme_classic()` shows only borders, etc. + +* **Multiple Canvas Types**: + - `braille`: Highest resolution using Unicode Braille patterns (2x4 dots per character) + - `block`: Medium resolution using block elements + - `ascii`: Basic ASCII characters for maximum compatibility + +* **Styling Options**: Configurable borders, grid lines, titles, subtitles, + captions, and axis labels + +### Boxplot Rendering + +* New `boxplot_style` parameter: `"ascii"` (box-drawing characters) or `"braille"` +* Renders whiskers, box (Q1-Q3), median line, and outliers +* Perfect centering of whiskers and outliers + +### Optimized Color Mapping + +* Intelligent color assignment minimizes repetition across groups +* 6 groups get 6 distinct terminal colors +* 8+ groups use all available colors before repeating +* Colors sorted by hue for visual consistency + +### Canvas Abstraction Layer + +New R6-based canvas system providing: + +* Pixel-level drawing primitives (points, lines, rectangles, circles, polygons) +* Automatic Braille character composition for smooth curves +* Support for colored output via ANSI escape codes + +### Geom Registry + +Extensible system for adding custom geom handlers, making it easy to add +support for additional ggplot2 geoms. + +### Heatmap Support + +* New `geom_tile` handler for rendering heatmaps +* Works with continuous color scales (`scale_fill_gradient`, `scale_fill_viridis_c`, etc.) +* Supports faceted heatmaps with `facet_wrap()` and `facet_grid()` + +## Improvements + +* Improved Braille bit mapping for more accurate scatter and line plots +* Better color handling for multi-group aesthetics +* Fixed issues with quosure parsing in aesthetic mappings +* Fixed axis label formatting (0 now displays as "0", not "0.0e+0") +* Fixed border overlap issue - data no longer appears on/within borders +* Fixed is_braille error with ANSI color codes + +## Bug Fixes (Latest) + +* Fixed `geom_density` not showing distinct colors when using `fill` aesthetic +* Fixed heatmap legend colors not matching plot colors (legend colors now included + in color mapping for consistency) +* Fixed colors not appearing in non-interactive R sessions (Rscript) by enabling + crayon colors automatically on package load +* Fixed discrete x-axis labels showing numeric positions instead of category names + +## Documentation + +* Comprehensive vignette: "ggplotcli: Universal ggplot2 to Terminal Plotting" +* Showcase examples demonstrating maximum complexity plots + +--- + +# plotcli 0.1.0 + +* Initial CRAN release +* Basic terminal plotting with `plotcli` R6 class +* Support for scatter, line, bar, and box plots +* Basic `ggplotcli()` function for ggplot2 conversion diff --git a/R/canvas.r b/R/canvas.r index cc068bf..7ee47a7 100644 --- a/R/canvas.r +++ b/R/canvas.r @@ -395,17 +395,14 @@ AsciiCanvas <- R6Class("AsciiCanvas", #' High-resolution canvas using Unicode Braille patterns. #' Resolution: 2x4 (2 horizontal, 4 vertical dots per character = 8x resolution) #' -#' Braille dot layout: -#' Col 0 Col 1 Bit values: -#' ┌────┬────┐ ┌────┬────┐ -#' Row 0 │ 1 │ 4 │ │0x01│0x08│ -#' ├────┼────┤ ├────┼────┤ -#' Row 1 │ 2 │ 5 │ │0x02│0x10│ -#' ├────┼────┤ ├────┼────┤ -#' Row 2 │ 3 │ 6 │ │0x04│0x20│ -#' ├────┼────┤ ├────┼────┤ -#' Row 3 │ 7 │ 8 │ │0x40│0x80│ -#' └────┴────┘ └────┴────┘ +#' Braille dot layout (dot numbers and bit values): +#' \preformatted{ +#' Col 0 Col 1 Bit values +#' Row 0: 1 4 0x01 0x08 +#' Row 1: 2 5 0x02 0x10 +#' Row 2: 3 6 0x04 0x20 +#' Row 3: 7 8 0x40 0x80 +#' } #' #' @export BrailleCanvas <- R6Class("BrailleCanvas", @@ -490,7 +487,7 @@ BrailleCanvas <- R6Class("BrailleCanvas", #' Block Canvas Class #' #' Canvas using Unicode block elements for 2x vertical resolution. -#' Uses half-block characters: ▀ (upper), ▄ (lower), █ (full) +#' Uses half-block characters: upper half (U+2580), lower half (U+2584), full block (U+2588). #' #' Resolution: 1x2 (1 horizontal, 2 vertical pixels per character) #' diff --git a/R/geom_registry.r b/R/geom_registry.r index 4676574..3f090cb 100644 --- a/R/geom_registry.r +++ b/R/geom_registry.r @@ -4,6 +4,10 @@ #' a dispatch system for converting ggplot2 geoms to terminal plots. #' #' @name GeomRegistry +#' @importFrom grDevices col2rgb +#' @importFrom stats density +#' @import R6 +#' @import ggplot2 NULL #' Geom Registry Environment @@ -73,42 +77,115 @@ is_geom_registered <- function(geom_name) { #' @param built Result from ggplot_build() #' @param plot_width Canvas pixel width #' @param plot_height Canvas pixel height +#' @param has_border Whether a border will be drawn (adds padding) #' @return List with x_scale and y_scale functions #' @export -create_scales <- function(built, plot_width, plot_height) { +create_scales <- function(built, plot_width, plot_height, has_border = FALSE, + x_mult = 1, y_mult = 1) { # Get the panel parameters (contains scale ranges) layout <- built$layout panel_params <- layout$panel_params[[1]] - + # X scale x_range <- panel_params$x.range if (is.null(x_range)) { x_range <- range(built$data[[1]]$x, na.rm = TRUE) } - + # Y scale y_range <- panel_params$y.range if (is.null(y_range)) { y_range <- range(built$data[[1]]$y, na.rm = TRUE) } + + # Add padding if border is present to prevent data from overlapping border + # Padding must be at least the canvas multiplier to ensure data stays in + # a different character cell than the border (e.g., braille is 2x4 per char) + if (has_border) { + x_padding <- x_mult + 1 # Move past border character cell + y_padding <- y_mult + 1 + } else { + x_padding <- 0 + y_padding <- 0 + } + x_min <- 1 + x_padding + x_max <- plot_width - x_padding + y_min <- 1 + y_padding + y_max <- plot_height - y_padding + + # Ensure we have valid ranges + if (x_max <= x_min) { + x_min <- 1 + x_max <- plot_width + } + if (y_max <= y_min) { + y_min <- 1 + y_max <- plot_height + } # Create scaling functions x_scale <- function(x) { - ((x - x_range[1]) / (x_range[2] - x_range[1])) * (plot_width - 1) + 1 + ((x - x_range[1]) / (x_range[2] - x_range[1])) * (x_max - x_min) + x_min } y_scale <- function(y) { # Invert Y because canvas has origin at top-left - plot_height - ((y - y_range[1]) / (y_range[2] - y_range[1])) * (plot_height - 1) + y_max - ((y - y_range[1]) / (y_range[2] - y_range[1])) * (y_max - y_min) } + # Check for discrete x-axis labels (only use for discrete scales) + x_labels <- NULL + x_label_positions <- NULL + x_is_discrete <- !is.null(panel_params$x) && + !is.null(panel_params$x$is_discrete) && + tryCatch(panel_params$x$is_discrete(), error = function(e) FALSE) + + if (x_is_discrete && !is.null(panel_params$x$breaks)) { + x_labels <- panel_params$x$get_labels() + x_label_positions <- attr(panel_params$x$breaks, "pos") + if (is.null(x_label_positions)) { + x_label_positions <- seq_along(x_labels) + } + # Filter out NA values + if (!is.null(x_labels) && length(x_labels) > 0) { + valid <- !is.na(x_labels) + x_labels <- x_labels[valid] + x_label_positions <- x_label_positions[valid] + } + } + + # Check for discrete y-axis labels (only use for discrete scales) + y_labels <- NULL + y_label_positions <- NULL + y_is_discrete <- !is.null(panel_params$y) && + !is.null(panel_params$y$is_discrete) && + tryCatch(panel_params$y$is_discrete(), error = function(e) FALSE) + + if (y_is_discrete && !is.null(panel_params$y$breaks)) { + y_labels <- panel_params$y$get_labels() + y_label_positions <- attr(panel_params$y$breaks, "pos") + if (is.null(y_label_positions)) { + y_label_positions <- seq_along(y_labels) + } + # Filter out NA values + if (!is.null(y_labels) && length(y_labels) > 0) { + valid <- !is.na(y_labels) + y_labels <- y_labels[valid] + y_label_positions <- y_label_positions[valid] + } + } + list( x = x_scale, y = y_scale, x_range = x_range, y_range = y_range, width = plot_width, - height = plot_height + height = plot_height, + x_labels = x_labels, + x_label_positions = x_label_positions, + y_labels = y_labels, + y_label_positions = y_label_positions ) } @@ -121,7 +198,7 @@ create_scales <- function(built, plot_width, plot_height) { #' #' Renders points as individual pixels or small shapes #' @keywords internal -geom_point_handler <- function(data, canvas, scales, params) { +geom_point_handler <- function(data, canvas, scales, params, style_opts = NULL) { # Get color mapping colors <- if ("colour" %in% names(data)) data$colour else rep("white", nrow(data)) @@ -146,7 +223,7 @@ geom_point_handler <- function(data, canvas, scales, params) { #' #' Renders connected lines #' @keywords internal -geom_line_handler <- function(data, canvas, scales, params) { +geom_line_handler <- function(data, canvas, scales, params, style_opts = NULL) { # Sort by x to ensure proper line connections data <- data[order(data$x), ] @@ -182,7 +259,7 @@ geom_line_handler <- function(data, canvas, scales, params) { #' #' Renders connected paths (order by data, not x) #' @keywords internal -geom_path_handler <- function(data, canvas, scales, params) { +geom_path_handler <- function(data, canvas, scales, params, style_opts = NULL) { # Group by colour/group if present if ("group" %in% names(data)) { groups <- unique(data$group) @@ -215,7 +292,7 @@ geom_path_handler <- function(data, canvas, scales, params) { #' #' Renders bar charts #' @keywords internal -geom_bar_handler <- function(data, canvas, scales, params) { +geom_bar_handler <- function(data, canvas, scales, params, style_opts = NULL) { # Get colors colors <- if ("fill" %in% names(data)) data$fill else rep("white", nrow(data)) @@ -243,7 +320,7 @@ geom_bar_handler <- function(data, canvas, scales, params) { #' #' Renders filled areas #' @keywords internal -geom_area_handler <- function(data, canvas, scales, params) { +geom_area_handler <- function(data, canvas, scales, params, style_opts = NULL) { # Sort by x data <- data[order(data$x), ] @@ -266,7 +343,7 @@ geom_area_handler <- function(data, canvas, scales, params) { #' #' Renders line segments #' @keywords internal -geom_segment_handler <- function(data, canvas, scales, params) { +geom_segment_handler <- function(data, canvas, scales, params, style_opts = NULL) { colors <- if ("colour" %in% names(data)) data$colour else rep("white", nrow(data)) for (i in seq_len(nrow(data))) { @@ -290,7 +367,7 @@ geom_segment_handler <- function(data, canvas, scales, params) { #' #' Renders horizontal lines #' @keywords internal -geom_hline_handler <- function(data, canvas, scales, params) { +geom_hline_handler <- function(data, canvas, scales, params, style_opts = NULL) { colors <- if ("colour" %in% names(data)) data$colour else rep("white", nrow(data)) for (i in seq_len(nrow(data))) { @@ -311,7 +388,7 @@ geom_hline_handler <- function(data, canvas, scales, params) { #' #' Renders vertical lines #' @keywords internal -geom_vline_handler <- function(data, canvas, scales, params) { +geom_vline_handler <- function(data, canvas, scales, params, style_opts = NULL) { colors <- if ("colour" %in% names(data)) data$colour else rep("white", nrow(data)) for (i in seq_len(nrow(data))) { @@ -332,7 +409,7 @@ geom_vline_handler <- function(data, canvas, scales, params) { #' #' Renders rectangles #' @keywords internal -geom_rect_handler <- function(data, canvas, scales, params) { +geom_rect_handler <- function(data, canvas, scales, params, style_opts = NULL) { colors <- if ("fill" %in% names(data)) data$fill else rep("white", nrow(data)) for (i in seq_len(nrow(data))) { @@ -357,7 +434,7 @@ geom_rect_handler <- function(data, canvas, scales, params) { #' #' Renders smoothed lines (just draws the line, ignores confidence interval) #' @keywords internal -geom_smooth_handler <- function(data, canvas, scales, params) { +geom_smooth_handler <- function(data, canvas, scales, params, style_opts = NULL) { # Sort by x data <- data[order(data$x), ] @@ -380,7 +457,7 @@ geom_smooth_handler <- function(data, canvas, scales, params) { #' #' Renders density curves #' @keywords internal -geom_density_handler <- function(data, canvas, scales, params) { +geom_density_handler <- function(data, canvas, scales, params, style_opts = NULL) { # Group by group if present if ("group" %in% names(data)) { groups <- unique(data$group) @@ -395,13 +472,20 @@ geom_density_handler <- function(data, canvas, scales, params) { if (nrow(grp_data) < 2) next - # Get color - color <- if ("colour" %in% names(grp_data)) { + # Get color - prefer fill over colour for density plots + # (density plots typically use fill aesthetic for distinction) + color <- if ("fill" %in% names(grp_data) && + !is.na(grp_data$fill[1]) && + grp_data$fill[1] != "grey20") { + color_to_term(grp_data$fill[1]) + } else if ("colour" %in% names(grp_data) && + !is.na(grp_data$colour[1]) && + grp_data$colour[1] != "black") { color_to_term(grp_data$colour[1]) } else { NULL } - + # Use density as y xs <- sapply(grp_data$x, scales$x) ys <- sapply(grp_data$density, scales$y) @@ -418,11 +502,237 @@ geom_density_handler <- function(data, canvas, scales, params) { geom_histogram_handler <- geom_bar_handler +#' GeomBoxplot Handler +#' +#' Renders boxplots with whiskers, box, median line, and outliers. +#' Supports two styles: "ascii" (box-drawing characters) and "braille" (Braille dots). +#' @keywords internal +geom_boxplot_handler <- function(data, canvas, scales, params, style_opts = NULL) { + # Get boxplot style (default to "ascii" for classic look) + boxplot_style <- if (!is.null(style_opts) && !is.null(style_opts$boxplot_style)) { + style_opts$boxplot_style + } else { + "ascii" + } + + # Get colors + fill_colors <- if ("fill" %in% names(data)) data$fill else rep("white", nrow(data)) + outline_colors <- if ("colour" %in% names(data)) data$colour else rep("white", nrow(data)) + + for (i in seq_len(nrow(data))) { + # Get boxplot statistics + x <- data$x[i] + xmin <- data$xmin[i] + xmax <- data$xmax[i] + ymin <- data$ymin[i] # Lower whisker + lower <- data$lower[i] # Q1 + middle <- data$middle[i] # Median + upper <- data$upper[i] # Q3 + ymax <- data$ymax[i] # Upper whisker + outliers <- data$outliers[[i]] + + # Get color + fill_color <- fill_colors[i] + if (!is.null(fill_color) && !is.na(fill_color)) { + fill_color <- color_to_term(fill_color) + } else { + fill_color <- NULL + } + + outline_color <- outline_colors[i] + if (!is.null(outline_color) && !is.na(outline_color)) { + outline_color <- color_to_term(outline_color) + } else { + outline_color <- fill_color + } + + # Scale coordinates + sx <- scales$x(x) + sxmin <- scales$x(xmin) + sxmax <- scales$x(xmax) + symin <- scales$y(ymin) + slower <- scales$y(lower) + smiddle <- scales$y(middle) + supper <- scales$y(upper) + symax <- scales$y(ymax) + + if (boxplot_style == "ascii") { + # ASCII style: use box-drawing characters directly on the character grid + # Convert pixel coordinates to character coordinates + # Use the center x coordinate as the reference point + char_x <- round(sx / canvas$x_mult) + char_ymin <- round(symin / canvas$y_mult) + char_lower <- round(slower / canvas$y_mult) + char_middle <- round(smiddle / canvas$y_mult) + char_upper <- round(supper / canvas$y_mult) + char_ymax <- round(symax / canvas$y_mult) + + # Calculate box width in character units from the data + box_half_width <- round((sxmax - sxmin) / canvas$x_mult / 2) + if (box_half_width < 2) box_half_width <- 2 # Minimum width for visible box + + # Box-drawing characters + horiz <- "\u2500" # horizontal line + vert <- "\u2502" # vertical line + top_left <- "\u250c" # top left corner + top_right <- "\u2510" # top right corner + bottom_left <- "\u2514" # bottom left corner + bottom_right <- "\u2518" # bottom right corner + + # Get canvas matrix dimensions + n_rows <- nrow(canvas$matrix) + n_cols <- ncol(canvas$matrix) + + # Clamp center to valid range + char_x <- max(1, min(n_cols, char_x)) + char_ymin <- max(1, min(n_rows, char_ymin)) + char_lower <- max(1, min(n_rows, char_lower)) + char_middle <- max(1, min(n_rows, char_middle)) + char_upper <- max(1, min(n_rows, char_upper)) + char_ymax <- max(1, min(n_rows, char_ymax)) + + # Calculate box boundaries from center + box_left <- max(1, char_x - box_half_width) + box_right <- min(n_cols, char_x + box_half_width) + box_top <- min(char_lower, char_upper) + box_bottom <- max(char_lower, char_upper) + + # Draw whiskers (vertical lines) - use char_x (true center from data) + # Only draw whiskers OUTSIDE the box (between ymin and lower, between upper and ymax) + # Lower whisker: from ymin to just before lower (box_bottom) + if (char_ymin != box_bottom) { + whisker_rows_lower <- seq(min(box_bottom, char_ymin), max(box_bottom, char_ymin)) + # Exclude the box edge itself + whisker_rows_lower <- whisker_rows_lower[whisker_rows_lower != box_bottom] + for (row in whisker_rows_lower) { + if (row >= 1 && row <= n_rows && char_x >= 1 && char_x <= n_cols) { + canvas$matrix[row, char_x] <- make_colored(vert, fill_color) + } + } + } + # Upper whisker: from just after upper (box_top) to ymax + if (char_ymax != box_top) { + whisker_rows_upper <- seq(min(box_top, char_ymax), max(box_top, char_ymax)) + # Exclude the box edge itself + whisker_rows_upper <- whisker_rows_upper[whisker_rows_upper != box_top] + for (row in whisker_rows_upper) { + if (row >= 1 && row <= n_rows && char_x >= 1 && char_x <= n_cols) { + canvas$matrix[row, char_x] <- make_colored(vert, fill_color) + } + } + } + + # Draw whisker caps (horizontal lines) - same width as median (inside box) + # Only draw caps if they differ from the box edges + for (col in (box_left + 1):(box_right - 1)) { + if (col >= 1 && col <= n_cols) { + if (char_ymin >= 1 && char_ymin <= n_rows && char_ymin != box_bottom) { + canvas$matrix[char_ymin, col] <- make_colored(horiz, fill_color) + } + if (char_ymax >= 1 && char_ymax <= n_rows && char_ymax != box_top) { + canvas$matrix[char_ymax, col] <- make_colored(horiz, fill_color) + } + } + } + + # Top and bottom of box + for (col in box_left:box_right) { + if (box_top >= 1 && box_top <= n_rows) { + canvas$matrix[box_top, col] <- make_colored(horiz, fill_color) + } + if (box_bottom >= 1 && box_bottom <= n_rows) { + canvas$matrix[box_bottom, col] <- make_colored(horiz, fill_color) + } + } + + # Sides of box + for (row in box_top:box_bottom) { + if (row >= 1 && row <= n_rows) { + if (box_left >= 1 && box_left <= n_cols) { + canvas$matrix[row, box_left] <- make_colored(vert, fill_color) + } + if (box_right >= 1 && box_right <= n_cols) { + canvas$matrix[row, box_right] <- make_colored(vert, fill_color) + } + } + } + + # Corners + if (box_top >= 1 && box_top <= n_rows) { + if (box_left >= 1 && box_left <= n_cols) { + canvas$matrix[box_top, box_left] <- make_colored(top_left, fill_color) + } + if (box_right >= 1 && box_right <= n_cols) { + canvas$matrix[box_top, box_right] <- make_colored(top_right, fill_color) + } + } + if (box_bottom >= 1 && box_bottom <= n_rows) { + if (box_left >= 1 && box_left <= n_cols) { + canvas$matrix[box_bottom, box_left] <- make_colored(bottom_left, fill_color) + } + if (box_right >= 1 && box_right <= n_cols) { + canvas$matrix[box_bottom, box_right] <- make_colored(bottom_right, fill_color) + } + } + + # Median line - only inside the box (not including the border) + if (char_middle >= 1 && char_middle <= n_rows) { + for (col in (box_left + 1):(box_right - 1)) { + if (col >= 1 && col <= n_cols) { + canvas$matrix[char_middle, col] <- make_colored(horiz, fill_color) + } + } + } + + # Outliers - use char_x (true center from data) + if (length(outliers) > 0 && !all(is.na(outliers))) { + for (out in outliers) { + if (!is.na(out)) { + char_y_out <- round(scales$y(out) / canvas$y_mult) + if (char_y_out >= 1 && char_y_out <= n_rows && + char_x >= 1 && char_x <= n_cols) { + canvas$matrix[char_y_out, char_x] <- make_colored("*", fill_color) + } + } + } + } + + } else { + # Braille style: use canvas drawing methods (high resolution) + # Draw whiskers (vertical lines from box to whisker ends) + canvas$draw_segment(round(sx), round(slower), round(sx), round(symin), color = fill_color) + canvas$draw_segment(round(sx), round(supper), round(sx), round(symax), color = fill_color) + + # Draw whisker caps (horizontal lines at whisker ends) + cap_width <- (sxmax - sxmin) / 2 + canvas$draw_segment(round(sx - cap_width/2), round(symin), round(sx + cap_width/2), round(symin), color = fill_color) + canvas$draw_segment(round(sx - cap_width/2), round(symax), round(sx + cap_width/2), round(symax), color = fill_color) + + # Draw box (rectangle from Q1 to Q3) + canvas$draw_rect(round(sxmin), round(supper), round(sxmax), round(slower), color = fill_color) + + # Draw median line + canvas$draw_segment(round(sxmin), round(smiddle), round(sxmax), round(smiddle), color = fill_color) + + # Draw outliers + if (length(outliers) > 0 && !all(is.na(outliers))) { + for (out in outliers) { + if (!is.na(out)) { + sy_out <- scales$y(out) + canvas$set_pixel(round(sx), round(sy_out), fill_color) + } + } + } + } + } +} + + #' GeomText Handler #' #' Renders text labels #' @keywords internal -geom_text_handler <- function(data, canvas, scales, params) { +geom_text_handler <- function(data, canvas, scales, params, style_opts = NULL) { colors <- if ("colour" %in% names(data)) data$colour else rep("white", nrow(data)) for (i in seq_len(nrow(data))) { @@ -450,8 +760,108 @@ geom_text_handler <- function(data, canvas, scales, params) { # Color Conversion # ============================================================================ +# ============================================================================ +# Color Mapping System +# ============================================================================ + +# Environment to store color mappings for the current plot +.color_map_env <- new.env(parent = emptyenv()) + +#' Initialize color mapping for a set of ggplot colors +#' +#' This function takes all unique colors from a ggplot and assigns terminal +#' colors to minimize repetition while respecting hue similarity. +#' +#' @param ggplot_colors Vector of unique colors from ggplot +#' @export +init_color_mapping <- function(ggplot_colors) { + # Available chromatic terminal colors (in hue order: 0, 60, 120, 180, 240, 300) + term_colors <- c("red", "yellow", "green", "cyan", "blue", "magenta") + n_term <- length(term_colors) + + # Filter out NULL/NA and get unique colors + ggplot_colors <- unique(ggplot_colors[!is.na(ggplot_colors) & !is.null(ggplot_colors)]) + n_colors <- length(ggplot_colors) + + if (n_colors == 0) { + .color_map_env$mapping <- list() + return(invisible(NULL)) + } + + # Calculate hue for each ggplot color + hues <- sapply(ggplot_colors, get_color_hue) + + # Sort colors by hue + hue_order <- order(hues) + sorted_colors <- ggplot_colors[hue_order] + sorted_hues <- hues[hue_order] + + # Assign terminal colors to minimize repetition + # Strategy: distribute terminal colors evenly across the sorted hue spectrum + mapping <- list() + + if (n_colors <= n_term) { + # We have enough terminal colors - assign each ggplot color a unique one + # Use the hue-sorted order to assign colors that are spread out + term_indices <- round(seq(1, n_term, length.out = n_colors)) + for (i in seq_along(sorted_colors)) { + mapping[[sorted_colors[i]]] <- term_colors[term_indices[i]] + } + } else { + # More ggplot colors than terminal colors - minimize repetition + # Each terminal color will be used ceiling(n_colors/n_term) or floor times + # Distribute evenly across the hue-sorted colors + for (i in seq_along(sorted_colors)) { + # Cycle through terminal colors + term_idx <- ((i - 1) %% n_term) + 1 + mapping[[sorted_colors[i]]] <- term_colors[term_idx] + } + } + + .color_map_env$mapping <- mapping + invisible(NULL) +} + +#' Get the hue of a color (0-360 degrees) +#' +#' @param color A color value +#' @return Hue in degrees (0-360) or NA for grayscale +#' @keywords internal +get_color_hue <- function(color) { + if (is.null(color) || is.na(color)) return(NA) + + tryCatch({ + rgb_val <- col2rgb(color) + r <- rgb_val[1, 1] + g <- rgb_val[2, 1] + b <- rgb_val[3, 1] + + max_val <- max(r, g, b) + min_val <- min(r, g, b) + chroma <- max_val - min_val + + if (chroma == 0) return(NA) # Grayscale + + if (max_val == r) { + hue <- 60 * (((g - b) / chroma) %% 6) + } else if (max_val == g) { + hue <- 60 * ((b - r) / chroma + 2) + } else { + hue <- 60 * ((r - g) / chroma + 4) + } + + if (hue < 0) hue <- hue + 360 + return(hue) + }, error = function(e) { + return(NA) + }) +} + #' Convert ggplot2 color to terminal color name #' +#' If init_color_mapping() was called, uses the pre-computed mapping. +#' Otherwise falls back to simple hue-based matching. +#' #' @param color A color value (hex, name, or R color) #' @return A terminal color name (blue, red, green, etc.) or NULL #' @export @@ -464,40 +874,51 @@ color_to_term <- function(color) { return(tolower(color)) } - # Try to convert hex/named color to RGB and find closest terminal color + # Check if we have a pre-computed mapping + if (exists("mapping", envir = .color_map_env) && + length(.color_map_env$mapping) > 0 && + color %in% names(.color_map_env$mapping)) { + return(.color_map_env$mapping[[color]]) + } + + # Fallback: simple hue-based matching tryCatch({ - rgb <- col2rgb(color) - r <- rgb[1, 1] - g <- rgb[2, 1] - b <- rgb[3, 1] + rgb_val <- col2rgb(color) + r <- rgb_val[1, 1] + g <- rgb_val[2, 1] + b <- rgb_val[3, 1] - # Simple heuristic: find dominant channel + # Check for near-black or near-white first max_val <- max(r, g, b) min_val <- min(r, g, b) - if (max_val < 50) return("black") - if (min_val > 200) return("white") + if (max_val < 40) return("black") + if (min_val > 220) return("white") - # Check for grayscale - if (max_val - min_val < 30) { - if (max_val > 180) return("white") - if (max_val > 100) return("silver") + # Check for grayscale (low saturation) + if (max_val - min_val < 25) { + if (max_val > 170) return("white") + if (max_val > 85) return("silver") return("black") } - # Find dominant color - if (r >= g && r >= b) { - if (g > b && g > 100) return("yellow") - if (b > g && b > 100) return("magenta") + # Get hue and map to terminal color + hue <- get_color_hue(color) + if (is.na(hue)) return("silver") + + # Map hue to terminal colors (60-degree segments) + if (hue < 30 || hue >= 330) { return("red") - } else if (g >= r && g >= b) { - if (r > b && r > 100) return("yellow") - if (b > r && b > 100) return("cyan") + } else if (hue < 90) { + return("yellow") + } else if (hue < 150) { return("green") - } else { - if (r > g && r > 100) return("magenta") - if (g > r && g > 100) return("cyan") + } else if (hue < 210) { + return("cyan") + } else if (hue < 270) { return("blue") + } else { + return("magenta") } }, error = function(e) { return(NULL) @@ -505,6 +926,417 @@ color_to_term <- function(color) { } +#' GeomTile Handler +#' +#' Renders tiles/heatmaps. Tiles use center (x, y) coordinates with width/height. +#' @keywords internal +geom_tile_handler <- function(data, canvas, scales, params, style_opts = NULL) { + # Get fill colors + colors <- if ("fill" %in% names(data)) data$fill else rep("white", nrow(data)) + + # Default tile dimensions (usually 1 for discrete scales) + default_width <- if ("width" %in% names(data) && !is.na(data$width[1])) data$width[1] else 1 + default_height <- if ("height" %in% names(data) && !is.na(data$height[1])) data$height[1] else 1 + + for (i in seq_len(nrow(data))) { + # Get center coordinates - skip if NA + x_center <- data$x[i] + y_center <- data$y[i] + if (is.na(x_center) || is.na(y_center)) next + + # Get tile dimensions + tile_width <- if ("width" %in% names(data) && !is.na(data$width[i])) { + data$width[i] + } else { + default_width + } + tile_height <- if ("height" %in% names(data) && !is.na(data$height[i])) { + data$height[i] + } else { + default_height + } + + # Calculate corners from center + xmin <- x_center - tile_width / 2 + xmax <- x_center + tile_width / 2 + ymin <- y_center - tile_height / 2 + ymax <- y_center + tile_height / 2 + + # Scale to canvas coordinates + xmin_scaled <- scales$x(xmin) + xmax_scaled <- scales$x(xmax) + ymin_scaled <- scales$y(ymin) + ymax_scaled <- scales$y(ymax) + + # Check for valid coordinates + if (any(is.na(c(xmin_scaled, xmax_scaled, ymin_scaled, ymax_scaled)))) next + + # Get color + color <- colors[i] + if (!is.null(color) && !is.na(color)) { + color <- color_to_term(color) + } else { + color <- NULL + } + + # Draw filled rectangle (note: y is inverted in canvas coordinates) + canvas$fill_rect(round(xmin_scaled), round(ymax_scaled), + round(xmax_scaled), round(ymin_scaled), color) + } +} + + +# ============================================================================ +# Additional Geom Handlers +# ============================================================================ + +#' GeomStep Handler +#' +#' Renders step functions (staircase lines) +#' @keywords internal +geom_step_handler <- function(data, canvas, scales, params, style_opts = NULL) { + # Group by group if present + if ("group" %in% names(data)) { + groups <- unique(data$group) + } else { + groups <- 1 + data$group <- 1 + } + + for (grp in groups) { + grp_data <- data[data$group == grp, ] + grp_data <- grp_data[order(grp_data$x), ] + if (nrow(grp_data) < 2) next + + color <- if ("colour" %in% names(grp_data)) { + color_to_term(grp_data$colour[1]) + } else { + NULL + } + + # Build step coordinates: horizontal then vertical + xs <- numeric(0) + ys <- numeric(0) + for (i in seq_len(nrow(grp_data))) { + sx <- scales$x(grp_data$x[i]) + sy <- scales$y(grp_data$y[i]) + if (i > 1) { + # Horizontal segment to new x at previous y + xs <- c(xs, sx) + ys <- c(ys, ys[length(ys)]) + } + xs <- c(xs, sx) + ys <- c(ys, sy) + } + + canvas$draw_polyline(xs, ys, color) + } +} + +#' GeomAbline Handler +#' +#' Renders diagonal reference lines (slope + intercept) +#' @keywords internal +geom_abline_handler <- function(data, canvas, scales, params, style_opts = NULL) { + colors <- if ("colour" %in% names(data)) data$colour else rep("white", nrow(data)) + + for (i in seq_len(nrow(data))) { + intercept <- data$intercept[i] + slope <- data$slope[i] + + color <- colors[i] + if (!is.null(color) && !is.na(color)) { + color <- color_to_term(color) + } else { + color <- NULL + } + + # Compute line endpoints from x_range + x0 <- scales$x_range[1] + x1 <- scales$x_range[2] + y0 <- intercept + slope * x0 + y1 <- intercept + slope * x1 + + # Clamp to y_range + y0 <- max(scales$y_range[1], min(scales$y_range[2], y0)) + y1 <- max(scales$y_range[1], min(scales$y_range[2], y1)) + + canvas$draw_line( + round(scales$x(x0)), round(scales$y(y0)), + round(scales$x(x1)), round(scales$y(y1)), + color + ) + } +} + +#' GeomRibbon Handler +#' +#' Renders filled ribbons between ymin and ymax +#' @keywords internal +geom_ribbon_handler <- function(data, canvas, scales, params, style_opts = NULL) { + if ("group" %in% names(data)) { + groups <- unique(data$group) + } else { + groups <- 1 + data$group <- 1 + } + + for (grp in groups) { + grp_data <- data[data$group == grp, ] + grp_data <- grp_data[order(grp_data$x), ] + if (nrow(grp_data) < 2) next + + color <- if ("fill" %in% names(grp_data)) { + color_to_term(grp_data$fill[1]) + } else if ("colour" %in% names(grp_data)) { + color_to_term(grp_data$colour[1]) + } else { + NULL + } + + # Fill between ymin and ymax by drawing vertical segments + for (i in seq_len(nrow(grp_data))) { + x_px <- round(scales$x(grp_data$x[i])) + ymin_px <- round(scales$y(grp_data$ymin[i])) + ymax_px <- round(scales$y(grp_data$ymax[i])) + # y is inverted: ymax_px < ymin_px in pixel space + top <- min(ymin_px, ymax_px) + bottom <- max(ymin_px, ymax_px) + for (py in top:bottom) { + canvas$set_pixel(x_px, py, color) + } + } + } +} + +#' GeomErrorbar Handler +#' +#' Renders vertical error bars with horizontal caps +#' @keywords internal +geom_errorbar_handler <- function(data, canvas, scales, params, style_opts = NULL) { + colors <- if ("colour" %in% names(data)) data$colour else rep("white", nrow(data)) + + for (i in seq_len(nrow(data))) { + color <- colors[i] + if (!is.null(color) && !is.na(color)) { + color <- color_to_term(color) + } else { + color <- NULL + } + + x_px <- round(scales$x(data$x[i])) + ymin_px <- round(scales$y(data$ymin[i])) + ymax_px <- round(scales$y(data$ymax[i])) + + # Vertical line + canvas$draw_line(x_px, ymin_px, x_px, ymax_px, color) + + # Horizontal caps using xmin/xmax if available, otherwise approximate + if ("xmin" %in% names(data) && "xmax" %in% names(data)) { + xmin_px <- round(scales$x(data$xmin[i])) + xmax_px <- round(scales$x(data$xmax[i])) + } else { + cap_half <- max(2, round(scales$width * 0.01)) + xmin_px <- x_px - cap_half + xmax_px <- x_px + cap_half + } + + canvas$draw_line(xmin_px, ymin_px, xmax_px, ymin_px, color) + canvas$draw_line(xmin_px, ymax_px, xmax_px, ymax_px, color) + } +} + +#' GeomLinerange Handler +#' +#' Renders vertical line ranges (no caps) +#' @keywords internal +geom_linerange_handler <- function(data, canvas, scales, params, style_opts = NULL) { + colors <- if ("colour" %in% names(data)) data$colour else rep("white", nrow(data)) + + for (i in seq_len(nrow(data))) { + color <- colors[i] + if (!is.null(color) && !is.na(color)) { + color <- color_to_term(color) + } else { + color <- NULL + } + + x_px <- round(scales$x(data$x[i])) + ymin_px <- round(scales$y(data$ymin[i])) + ymax_px <- round(scales$y(data$ymax[i])) + + canvas$draw_line(x_px, ymin_px, x_px, ymax_px, color) + } +} + +#' GeomPointrange Handler +#' +#' Renders point with vertical line range +#' @keywords internal +geom_pointrange_handler <- function(data, canvas, scales, params, style_opts = NULL) { + colors <- if ("colour" %in% names(data)) data$colour else rep("white", nrow(data)) + + for (i in seq_len(nrow(data))) { + color <- colors[i] + if (!is.null(color) && !is.na(color)) { + color <- color_to_term(color) + } else { + color <- NULL + } + + x_px <- round(scales$x(data$x[i])) + y_px <- round(scales$y(data$y[i])) + ymin_px <- round(scales$y(data$ymin[i])) + ymax_px <- round(scales$y(data$ymax[i])) + + # Line range + canvas$draw_line(x_px, ymin_px, x_px, ymax_px, color) + # Point at center + canvas$set_pixel(x_px, y_px, color) + } +} + +#' GeomCrossbar Handler +#' +#' Renders crossbar (box with middle line, no whiskers) +#' @keywords internal +geom_crossbar_handler <- function(data, canvas, scales, params, style_opts = NULL) { + fill_colors <- if ("fill" %in% names(data)) data$fill else rep(NA, nrow(data)) + outline_colors <- if ("colour" %in% names(data)) data$colour else rep("white", nrow(data)) + + for (i in seq_len(nrow(data))) { + color <- outline_colors[i] + if (!is.null(color) && !is.na(color)) { + color <- color_to_term(color) + } else { + color <- NULL + } + + fill_color <- fill_colors[i] + if (!is.null(fill_color) && !is.na(fill_color)) { + fill_color <- color_to_term(fill_color) + } else { + fill_color <- NULL + } + + xmin_px <- round(scales$x(data$xmin[i])) + xmax_px <- round(scales$x(data$xmax[i])) + y_px <- round(scales$y(data$y[i])) + ymin_px <- round(scales$y(data$ymin[i])) + ymax_px <- round(scales$y(data$ymax[i])) + + # Fill if fill color given + if (!is.null(fill_color)) { + canvas$fill_rect(xmin_px, min(ymin_px, ymax_px), xmax_px, max(ymin_px, ymax_px), fill_color) + } + + # Outline rectangle + canvas$draw_rect(xmin_px, min(ymin_px, ymax_px), xmax_px, max(ymin_px, ymax_px), color) + # Middle line (median) + canvas$draw_line(xmin_px, y_px, xmax_px, y_px, color) + } +} + +#' GeomRug Handler +#' +#' Renders rug marks (short tick marks along axes) +#' @keywords internal +geom_rug_handler <- function(data, canvas, scales, params, style_opts = NULL) { + colors <- if ("colour" %in% names(data)) data$colour else rep("white", nrow(data)) + rug_length <- max(2, round(scales$height * 0.03)) + + for (i in seq_len(nrow(data))) { + color <- colors[i] + if (!is.null(color) && !is.na(color)) { + color <- color_to_term(color) + } else { + color <- NULL + } + + # X rug: short vertical tick at bottom + if ("x" %in% names(data) && !is.na(data$x[i])) { + x_px <- round(scales$x(data$x[i])) + canvas$draw_line(x_px, scales$height, x_px, scales$height - rug_length, color) + } + + # Y rug: short horizontal tick at left + if ("y" %in% names(data) && !is.na(data$y[i])) { + y_px <- round(scales$y(data$y[i])) + canvas$draw_line(1, y_px, 1 + rug_length, y_px, color) + } + } +} + +#' GeomLabel Handler +#' +#' Renders text labels (same as geom_text for terminal) +#' @keywords internal +geom_label_handler <- geom_text_handler + +#' GeomRaster Handler +#' +#' Renders raster images (same as tile for terminal) +#' @keywords internal +geom_raster_handler <- geom_tile_handler + +#' GeomViolin Handler +#' +#' Renders violin plots (mirrored density curves) +#' @keywords internal +geom_violin_handler <- function(data, canvas, scales, params, style_opts = NULL) { + if ("group" %in% names(data)) { + groups <- unique(data$group) + } else { + groups <- 1 + data$group <- 1 + } + + for (grp in groups) { + grp_data <- data[data$group == grp, ] + grp_data <- grp_data[order(grp_data$y), ] + if (nrow(grp_data) < 2) next + + fill_color <- if ("fill" %in% names(grp_data) && !is.na(grp_data$fill[1])) { + color_to_term(grp_data$fill[1]) + } else { + NULL + } + + outline_color <- if ("colour" %in% names(grp_data) && !is.na(grp_data$colour[1])) { + color_to_term(grp_data$colour[1]) + } else { + fill_color + } + + # Compute actual violin edges from violinwidth + # (xmin/xmax in data are group bounds, not the per-slice shape) + x_center <- grp_data$x + vw <- grp_data$violinwidth + xminv <- x_center - vw * (x_center - grp_data$xmin) + xmaxv <- x_center + vw * (grp_data$xmax - x_center) + + # Fill violin body + for (i in seq_len(nrow(grp_data))) { + xmin_px <- round(scales$x(xminv[i])) + xmax_px <- round(scales$x(xmaxv[i])) + y_px <- round(scales$y(grp_data$y[i])) + if (xmin_px <= xmax_px) { + for (px in xmin_px:xmax_px) { + canvas$set_pixel(px, y_px, fill_color) + } + } + } + + # Draw outline polylines for left and right edges + xs_left <- sapply(xminv, scales$x) + xs_right <- sapply(xmaxv, scales$x) + ys <- sapply(grp_data$y, scales$y) + canvas$draw_polyline(xs_left, ys, outline_color) + canvas$draw_polyline(xs_right, ys, outline_color) + } +} + + # ============================================================================ # Register Built-in Geoms # ============================================================================ @@ -520,10 +1352,23 @@ color_to_term <- function(color) { register_geom("GeomHline", geom_hline_handler) register_geom("GeomVline", geom_vline_handler) register_geom("GeomRect", geom_rect_handler) + register_geom("GeomTile", geom_tile_handler) register_geom("GeomSmooth", geom_smooth_handler) register_geom("GeomDensity", geom_density_handler) register_geom("GeomHistogram", geom_histogram_handler) register_geom("GeomText", geom_text_handler) + register_geom("GeomBoxplot", geom_boxplot_handler) + register_geom("GeomStep", geom_step_handler) + register_geom("GeomAbline", geom_abline_handler) + register_geom("GeomRibbon", geom_ribbon_handler) + register_geom("GeomErrorbar", geom_errorbar_handler) + register_geom("GeomLinerange", geom_linerange_handler) + register_geom("GeomPointrange", geom_pointrange_handler) + register_geom("GeomCrossbar", geom_crossbar_handler) + register_geom("GeomRug", geom_rug_handler) + register_geom("GeomLabel", geom_label_handler) + register_geom("GeomRaster", geom_raster_handler) + register_geom("GeomViolin", geom_violin_handler) } # Register geoms when the file is sourced diff --git a/R/ggplotcli.r b/R/ggplotcli.r index ffd850f..0674bdd 100644 --- a/R/ggplotcli.r +++ b/R/ggplotcli.r @@ -26,13 +26,6 @@ get_data_subset <- function(geom_name, data, aes, p_build) { } - #if(geom_name %in% c("GeomBar")) { - - # out$y = data[[rlang::as_name(aes$x)]] - # out$x = rep(1, length(out$y)) - - #} - if(!geom_name %in% c("GeomDensity", "GeomSmooth", "GeomBoxplot", "GeomBar")) { out$x = data[[rlang::as_name(aes$x)]] @@ -50,6 +43,7 @@ get_data_subset <- function(geom_name, data, aes, p_build) { #' #' @param aes_expr The aesthetic expression (can be a quosure) #' @return Character string of the column name, or NULL +#' @keywords internal safe_aes_name <- function(aes_expr) { if (is.null(aes_expr)) return(NULL) @@ -87,99 +81,154 @@ safe_aes_name <- function(aes_expr) { }) } -#' ggplotcli - Render ggplot objects in the terminal +#' ggplotcli - Render ggplot2 objects in the terminal #' -#' This function takes a ggplot object and renders it in the terminal using ASCII or Braille characters. +#' Convert any ggplot2 plot to a terminal-based visualization using Unicode +#' Braille characters or ASCII. Supports 15+ geom types, faceting, themes, +#' and color aesthetics. #' -#' @param ggplot_obj A ggplot object to be rendered in the terminal. -#' @param plot_width Width of the terminal plot in characters (default: 80). -#' @param plot_height Height of the terminal plot in characters (default: 40). -#' @param braille Use Braille characters for higher resolution (default: TRUE). +#' @param p A ggplot2 object to render +#' @param width Character width of the plot (default: 60) +#' @param height Character height of the plot (default: 20) +#' @param canvas_type Type of canvas: "braille" (high-res), "block" (medium), or "ascii" (basic). Default: "braille" +#' @param border Draw border around plot. "auto" uses ggplot theme, or TRUE/FALSE (default: "auto") +#' @param grid Grid lines: "none", "major", "minor", "both", or "auto" (default: "none") +#' @param show_axes Whether to show axis values (default: TRUE) +#' @param axis_labels Whether to show axis labels from ggplot (default: TRUE) +#' @param legend Legend display: "auto", "right", "bottom", "none" (default: "auto") +#' @param title_align Title alignment: "center" or "left" (default: "center") +#' @param subtitle Whether to show subtitle (default: TRUE) +#' @param caption Whether to show caption (default: TRUE) +#' @param title Optional title override (NULL uses ggplot title) +#' @param boxplot_style Style for boxplots: "ascii" uses box-drawing characters (default), +#' "braille" uses Braille dots like other geoms #' -#' @return A TerminalPlot object. +#' @return Invisibly returns the canvas object #' @export -ggplotcli <- function(ggplot_obj, plot_width = 80, plot_height = 40, braille = TRUE) { - - geoms_valid <- data.frame( - geom = c("GeomPoint", "GeomLine", "GeomDensity", "GeomSmooth", "GeomBar", "GeomBoxplot"), - plot_type = c("scatter", "line", "line", "line", "barplot", "boxplot") - ) - - p_build = ggplot2::ggplot_build(ggplot_obj) - - data <- ggplot_obj$data - aes <- ggplot_obj$mapping - geoms <- lapply(ggplot_obj$layers, function(layer) layer$geom) - geom_names = unlist(lapply(geoms, function(geom) class(geom)[[1]])) - - terminal_plot <- plotcli$new( - plot_width, - plot_height, - x_label = ggplot_obj$labels$x, - y_label = ggplot_obj$labels$y, - title = ggplot_obj$labels$title - ) - - for (i in 1:length(geoms)) { - - geom = geoms[[i]] - geom_name <- geom_names[i] - plot_type <- geoms_valid[geoms_valid$geom == geom_name, "plot_type"] - - # Safely extract color aesthetic name (handles factor(col) etc.) - color_aes <- safe_aes_name(aes$colour) - - # FIXME: need to get barplot to work - if (!geom_name %in% geoms_valid$geom | geom_name == "GeomBar") stop("Unsupported geom: ", geom_name) - - if (!is.null(color_aes) && color_aes %in% names(data)) { - - aes_levels <- as.character(unique(data[[color_aes]])) - num_levels <- length(aes_levels) - - this_term_colors <- get_term_colors(num_levels) - - for (j in 1:num_levels) { +#' +#' @examples +#' library(ggplot2) +#' +#' # Basic scatter plot +#' p <- ggplot(mtcars, aes(x = wt, y = mpg)) + geom_point() +#' ggplotcli(p) +#' +#' # With styling +#' ggplotcli(p, border = TRUE, grid = "major") +#' +#' # Faceted plot +#' p <- ggplot(mtcars, aes(x = wt, y = mpg)) + +#' geom_point() + +#' facet_wrap(~cyl) +#' ggplotcli(p, width = 70, height = 16) +#' +#' # Multiple geoms +#' p <- ggplot(mtcars, aes(x = mpg)) + +#' geom_histogram(aes(y = after_stat(density)), bins = 10) + +#' geom_density(color = "red") +#' ggplotcli(p) +ggplotcli <- function(p, + width = 60, + height = 20, + canvas_type = "braille", + border = "auto", + grid = "none", + show_axes = TRUE, + axis_labels = TRUE, + legend = "auto", + title_align = "center", + subtitle = TRUE, + caption = TRUE, + title = NULL, + boxplot_style = "ascii") { + + # Build the plot to get computed data + built <- ggplot2::ggplot_build(p) + + # Initialize color mapping for all colors in the plot (including legend colors) + # This ensures we minimize color repetition across groups and consistent legend + all_colors <- c() + for (layer_data in built$data) { + if ("colour" %in% names(layer_data)) { + all_colors <- c(all_colors, layer_data$colour) + } + if ("fill" %in% names(layer_data)) { + all_colors <- c(all_colors, layer_data$fill) + } + } - data_subset <- data[data[[color_aes]] == aes_levels[j], ] - data_subset <- get_data_subset(geom_name, data_subset, aes, p_build) + # Also include legend colors for consistent mapping + # Helper to extract colors from a scale (handles both discrete and continuous) + get_scale_colors <- function(scale, n) { + colors <- tryCatch(scale$palette(n), error = function(e) NULL) + if (is.null(colors) || (length(colors) == 1 && is.na(colors[1])) || + all(is.na(colors))) { + colors <- tryCatch(scale$palette(seq(0, 1, length.out = n)), error = function(e) NULL) + } + colors + } - terminal_plot$add_data(list( - x = data_subset$x, - y = data_subset$y, - color = this_term_colors[j], - name = aes_levels[j], - braille = braille, - type = plot_type - )) + # Get legend colors from colour scale + color_scale <- built$plot$scales$get_scales("colour") + if (!is.null(color_scale)) { + tryCatch({ + breaks <- color_scale$get_breaks() + n <- length(breaks) + if (n > 0) { + legend_cols <- get_scale_colors(color_scale, n) + if (!is.null(legend_cols) && !all(is.na(legend_cols))) { + all_colors <- c(all_colors, legend_cols) + } } + }, error = function(e) NULL) + } - } else { - - data_subset <- get_data_subset(geom_name, data, aes, p_build) - this_color = ggplot_obj$layers[[i]]$aes_params$colour - - if(!is.null(this_color)) { - - if(this_color != "") { - - if(!this_color %in% get_term_colors()) this_color = get_term_colors()[i] - + # Get legend colors from fill scale + fill_scale <- built$plot$scales$get_scales("fill") + if (!is.null(fill_scale)) { + tryCatch({ + breaks <- fill_scale$get_breaks() + n <- length(breaks) + if (n > 0) { + legend_cols <- get_scale_colors(fill_scale, n) + if (!is.null(legend_cols) && !all(is.na(legend_cols))) { + all_colors <- c(all_colors, legend_cols) } - } - - terminal_plot$add_data(list( - x = data_subset$x, - y = data_subset$y, - color = this_color, - name = "", - braille = braille, - type = plot_type - )) - } + }, error = function(e) NULL) } - return(terminal_plot) + init_color_mapping(unique(all_colors)) + + # Extract styling from ggplot theme + style <- extract_plot_style(built, border, grid, legend) + + # Get plot labels + labels <- extract_plot_labels(built, title, subtitle, caption, axis_labels) + + # Create style options object + style_opts <- list( + border = style$border, + grid = style$grid, + show_axes = show_axes, + axis_labels = axis_labels, + legend = style$legend, + title_align = title_align, + labels = labels, + boxplot_style = boxplot_style + ) + + # Check for faceting + layout <- built$layout -} \ No newline at end of file +facet_info <- get_facet_info(layout) + + if (facet_info$has_facets) { + # Render faceted plot + render_faceted_plot(built, facet_info, width, height, canvas_type, + style_opts) + } else { + # Render single panel plot + render_single_panel(built, width, height, canvas_type, style_opts) + } +} diff --git a/R/ggplotcli2.r b/R/ggplotcli_helpers.r similarity index 51% rename from R/ggplotcli2.r rename to R/ggplotcli_helpers.r index 8d0439d..38b64dd 100644 --- a/R/ggplotcli2.r +++ b/R/ggplotcli_helpers.r @@ -1,79 +1,6 @@ -#' Convert ggplot2 to Terminal Plot (v2) -#' -#' This is the new implementation using the Canvas abstraction and geom registry. -#' It properly uses ggplot_build() to get computed data and dispatches to -#' registered geom handlers. -#' -#' @param p A ggplot2 object -#' @param width Character width of the plot (default: 60) -#' @param height Character height of the plot (default: 20) -#' @param canvas_type Type of canvas: "braille", "block", or "ascii" (default: "braille") -#' @param border Draw border around plot area. "auto" uses ggplot theme, or TRUE/FALSE (default: "auto") -#' @param grid Grid lines: "none", "major", "minor", "both", or "auto" (default: "none") -#' @param show_axes Whether to show axis values (default: TRUE) -#' @param axis_labels Whether to show axis labels from ggplot (default: TRUE) -#' @param legend Legend display: "auto", "right", "bottom", "none" (default: "auto") -#' @param title_align Title alignment: "center" or "left" (default: "center") -#' @param subtitle Whether to show subtitle (default: TRUE) -#' @param caption Whether to show caption (default: TRUE) -#' @param title Optional title override (NULL uses ggplot title) -#' -#' @return Invisibly returns the canvas object -#' @export -#' -#' @examples -#' library(ggplot2) -#' p <- ggplot(mtcars, aes(x = wt, y = mpg)) + geom_point() -#' ggplotcli2(p) -#' ggplotcli2(p, border = TRUE, grid = "major") -ggplotcli2 <- function(p, - width = 60, - height = 20, - canvas_type = "braille", - border = "auto", - grid = "none", - show_axes = TRUE, - axis_labels = TRUE, - legend = "auto", - title_align = "center", - subtitle = TRUE, - caption = TRUE, - title = NULL) { - - # Build the plot to get computed data - built <- ggplot2::ggplot_build(p) - - # Extract styling from ggplot theme - style <- extract_plot_style(built, border, grid, legend) - - # Get plot labels - labels <- extract_plot_labels(built, title, subtitle, caption, axis_labels) - - # Create style options object - style_opts <- list( - border = style$border, - grid = style$grid, - show_axes = show_axes, - axis_labels = axis_labels, - legend = style$legend, - title_align = title_align, - labels = labels - ) - - # Check for faceting - layout <- built$layout - facet_info <- get_facet_info(layout) - - if (facet_info$has_facets) { - # Render faceted plot - render_faceted_plot(built, facet_info, width, height, canvas_type, - style_opts) - } else { - # Render single panel plot - render_single_panel(built, width, height, canvas_type, style_opts) - } -} - +#' Null-coalescing operator (if rlang not available) +#' @keywords internal +`%||%` <- function(x, y) if (is.null(x)) y else x #' Extract Plot Style from ggplot Theme #' @keywords internal @@ -148,6 +75,75 @@ extract_plot_labels <- function(built, title, subtitle, caption, axis_labels) { } +#' Extract Legend Information from ggplot +#' @keywords internal +extract_legend_info <- function(built) { + # Try to get color/colour scale + color_scale <- built$plot$scales$get_scales("colour") + fill_scale <- built$plot$scales$get_scales("fill") + + legend_items <- list() + + # Helper to extract colors from a scale (handles both discrete and continuous) + get_scale_colors <- function(scale, n) { + # First try direct palette call (works for discrete scales) + colors <- tryCatch(scale$palette(n), error = function(e) NULL) + + # If that returned NA or NULL, try continuous scale approach + if (is.null(colors) || (length(colors) == 1 && is.na(colors[1])) || + all(is.na(colors))) { + # For continuous scales, palette expects values in [0, 1] + colors <- tryCatch( + scale$palette(seq(0, 1, length.out = n)), + error = function(e) NULL + ) + } + + colors + } + + # Extract from color scale + if (!is.null(color_scale)) { + tryCatch({ + breaks <- color_scale$get_breaks() + labels <- color_scale$get_labels() + n <- length(breaks) + if (n > 0) { + colors <- get_scale_colors(color_scale, n) + if (!is.null(colors) && !all(is.na(colors))) { + legend_items$colour <- list( + title = built$plot$labels$colour %||% "colour", + labels = labels, + colors = colors + ) + } + } + }, error = function(e) NULL) + } + + # Extract from fill scale + if (!is.null(fill_scale)) { + tryCatch({ + breaks <- fill_scale$get_breaks() + labels <- fill_scale$get_labels() + n <- length(breaks) + if (n > 0) { + colors <- get_scale_colors(fill_scale, n) + if (!is.null(colors) && !all(is.na(colors))) { + legend_items$fill <- list( + title = built$plot$labels$fill %||% "fill", + labels = labels, + colors = colors + ) + } + } + }, error = function(e) NULL) + } + + legend_items +} + + #' Render a single panel (non-faceted) plot #' @keywords internal render_single_panel <- function(built, width, height, canvas_type, style_opts) { @@ -180,8 +176,10 @@ render_single_panel <- function(built, width, height, canvas_type, style_opts) { # Create canvas for plot area canvas <- create_canvas(plot_width, plot_height, canvas_type) - # Create scales - scales <- create_scales(built, canvas$pixel_width, canvas$pixel_height) + # Create scales (with border padding if needed, using canvas multipliers) + scales <- create_scales(built, canvas$pixel_width, canvas$pixel_height, + has_border = style_opts$border, + x_mult = canvas$x_mult, y_mult = canvas$y_mult) # Draw grid lines first (behind data) if (style_opts$grid != "none") { @@ -207,9 +205,9 @@ render_single_panel <- function(built, width, height, canvas_type, style_opts) { # Get layer parameters params <- layer$aes_params - # Call handler + # Call handler (pass style_opts for geoms that need it, like boxplot) tryCatch({ - handler(layer_data, canvas, scales, params) + handler(layer_data, canvas, scales, params, style_opts) }, error = function(e) { warning(sprintf("Error rendering %s: %s", geom_class, e$message)) }) @@ -220,6 +218,9 @@ render_single_panel <- function(built, width, height, canvas_type, style_opts) { draw_border(canvas) } + # Extract legend information + legend_info <- extract_legend_info(built) + # Build the final output matrix output <- build_plot_output_v2( canvas = canvas, @@ -228,7 +229,8 @@ render_single_panel <- function(built, width, height, canvas_type, style_opts) { height = height, style_opts = style_opts, left_margin = left_margin, - top_margin = top_margin + top_margin = top_margin, + legend_info = legend_info ) # Print @@ -311,15 +313,17 @@ draw_border <- function(canvas) { #' @param style_opts Style options #' @param left_margin Left margin size #' @param top_margin Top margin size +#' @param legend_info Legend information from extract_legend_info #' @return Character matrix #' @keywords internal build_plot_output_v2 <- function(canvas, scales, width, height, style_opts, - left_margin, top_margin) { + left_margin, top_margin, legend_info = NULL) { # Get rendered canvas rendered <- canvas$render() labels <- style_opts$labels show_axes <- style_opts$show_axes title_align <- style_opts$title_align + legend_position <- style_opts$legend # Create output matrix output <- matrix(" ", nrow = height, ncol = width) @@ -377,43 +381,90 @@ build_plot_output_v2 <- function(canvas, scales, width, height, style_opts, # Draw Y axis values if (show_axes) { - y_ticks <- pretty(scales$y_range, n = 5) - y_ticks <- y_ticks[y_ticks >= scales$y_range[1] & y_ticks <= scales$y_range[2]] - - for (tick in y_ticks) { - y_frac <- (tick - scales$y_range[1]) / (scales$y_range[2] - scales$y_range[1]) - row <- round(nrow(rendered) - y_frac * (nrow(rendered) - 1)) + top_margin - - if (row >= 1 && row <= height) { - label <- format_axis_label(tick) - label_chars <- strsplit(label, "")[[1]] - - start_col <- max(1, left_margin - length(label_chars)) - for (i in seq_along(label_chars)) { - if (start_col + i - 1 < left_margin) { - output[row, start_col + i - 1] <- label_chars[i] + # Check if we have discrete y labels + if (!is.null(scales$y_labels) && length(scales$y_labels) > 0) { + # Use discrete labels for y-axis + for (i in seq_along(scales$y_labels)) { + pos <- scales$y_label_positions[i] + y_frac <- (pos - scales$y_range[1]) / (scales$y_range[2] - scales$y_range[1]) + row <- round(nrow(rendered) - y_frac * (nrow(rendered) - 1)) + top_margin + + if (row >= 1 && row <= height) { + label <- scales$y_labels[i] + label_chars <- strsplit(label, "")[[1]] + + start_col <- max(1, left_margin - length(label_chars)) + for (j in seq_along(label_chars)) { + if (start_col + j - 1 < left_margin) { + output[row, start_col + j - 1] <- label_chars[j] + } + } + } + } + } else { + # Use numeric ticks for y-axis + y_ticks <- pretty(scales$y_range, n = 5) + y_ticks <- y_ticks[y_ticks >= scales$y_range[1] & y_ticks <= scales$y_range[2]] + + for (tick in y_ticks) { + y_frac <- (tick - scales$y_range[1]) / (scales$y_range[2] - scales$y_range[1]) + row <- round(nrow(rendered) - y_frac * (nrow(rendered) - 1)) + top_margin + + if (row >= 1 && row <= height) { + label <- format_axis_label(tick) + label_chars <- strsplit(label, "")[[1]] + + start_col <- max(1, left_margin - length(label_chars)) + for (j in seq_along(label_chars)) { + if (start_col + j - 1 < left_margin) { + output[row, start_col + j - 1] <- label_chars[j] + } } } } } - + # Draw X axis values x_row <- top_margin + nrow(rendered) + 1 - x_ticks <- pretty(scales$x_range, n = 5) - x_ticks <- x_ticks[x_ticks >= scales$x_range[1] & x_ticks <= scales$x_range[2]] - for (tick in x_ticks) { - x_frac <- (tick - scales$x_range[1]) / (scales$x_range[2] - scales$x_range[1]) - col <- round(x_frac * (ncol(rendered) - 1)) + left_margin + 1 + # Check if we have discrete labels + if (!is.null(scales$x_labels) && length(scales$x_labels) > 0) { + # Use discrete labels + for (i in seq_along(scales$x_labels)) { + pos <- scales$x_label_positions[i] + x_frac <- (pos - scales$x_range[1]) / (scales$x_range[2] - scales$x_range[1]) + col <- round(x_frac * (ncol(rendered) - 1)) + left_margin + 1 + + if (col >= left_margin && col <= width && x_row <= height) { + label <- scales$x_labels[i] + label_chars <- strsplit(label, "")[[1]] + + start_col <- col - floor(length(label_chars) / 2) + for (j in seq_along(label_chars)) { + if (start_col + j - 1 >= 1 && start_col + j - 1 <= width) { + output[x_row, start_col + j - 1] <- label_chars[j] + } + } + } + } + } else { + # Use numeric ticks + x_ticks <- pretty(scales$x_range, n = 5) + x_ticks <- x_ticks[x_ticks >= scales$x_range[1] & x_ticks <= scales$x_range[2]] - if (col >= left_margin && col <= width && x_row <= height) { - label <- format_axis_label(tick) - label_chars <- strsplit(label, "")[[1]] + for (tick in x_ticks) { + x_frac <- (tick - scales$x_range[1]) / (scales$x_range[2] - scales$x_range[1]) + col <- round(x_frac * (ncol(rendered) - 1)) + left_margin + 1 - start_col <- col - floor(length(label_chars) / 2) - for (i in seq_along(label_chars)) { - if (start_col + i - 1 >= 1 && start_col + i - 1 <= width) { - output[x_row, start_col + i - 1] <- label_chars[i] + if (col >= left_margin && col <= width && x_row <= height) { + label <- format_axis_label(tick) + label_chars <- strsplit(label, "")[[1]] + + start_col <- col - floor(length(label_chars) / 2) + for (j in seq_along(label_chars)) { + if (start_col + j - 1 >= 1 && start_col + j - 1 <= width) { + output[x_row, start_col + j - 1] <- label_chars[j] + } } } } @@ -462,10 +513,80 @@ build_plot_output_v2 <- function(canvas, scales, width, height, style_opts, } } + # Add legend if present and not "none" + if (!is.null(legend_info) && length(legend_info) > 0 && + !identical(legend_position, "none")) { + output <- add_legend_to_output(output, legend_info, legend_position, + top_margin, nrow(rendered)) + } + return(output) } +#' Add Legend to Output Matrix +#' @keywords internal +add_legend_to_output <- function(output, legend_info, position, top_margin, plot_height) { + # Get the first legend (colour or fill) + legend <- legend_info$colour %||% legend_info$fill + if (is.null(legend)) return(output) + + n_items <- length(legend$labels) + if (n_items == 0) return(output) + + # Calculate legend dimensions - include title width + max_label_len <- max(nchar(legend$labels)) + title_len <- if (!is.null(legend$title)) nchar(legend$title) else 0 + legend_width <- max(max_label_len + 3, title_len + 1) # "* label" or "Title " + + height <- nrow(output) + width <- ncol(output) + + if (position %in% c("right", "auto")) { + # Add legend to the right side + # Create legend column + legend_col <- matrix(" ", nrow = height, ncol = legend_width) + + # Center legend vertically in plot area + legend_start_row <- top_margin + max(1, floor((plot_height - n_items - 1) / 2)) + + # Add title if present + if (!is.null(legend$title) && nchar(legend$title) > 0) { + title_chars <- strsplit(substr(legend$title, 1, legend_width - 1), "")[[1]] + for (i in seq_along(title_chars)) { + if (legend_start_row <= height) { + legend_col[legend_start_row, i] <- title_chars[i] + } + } + legend_start_row <- legend_start_row + 1 + } + + # Add each legend item + for (i in seq_len(n_items)) { + row <- legend_start_row + i - 1 + if (row <= height && row >= 1) { + # Color indicator (use terminal color) + term_color <- color_to_term(legend$colors[i]) + legend_col[row, 1] <- make_colored("*", term_color) + + # Label + label_chars <- strsplit(legend$labels[i], "")[[1]] + for (j in seq_along(label_chars)) { + if (j + 2 <= legend_width) { + legend_col[row, j + 2] <- label_chars[j] + } + } + } + } + + # Append legend to output + output <- cbind(output, legend_col) + } + + output +} + + #' Build Plot Output with Axes and Title (legacy) #' #' @param canvas The rendered canvas @@ -481,13 +602,14 @@ build_plot_output <- function(canvas, scales, width, height, show_axes, title) { style_opts <- list( show_axes = show_axes, title_align = "center", + legend = "none", labels = list(title = title, subtitle = NULL, caption = NULL, x = NULL, y = NULL) ) left_margin <- if (show_axes) 6 else 0 top_margin <- if (!is.null(title)) 1 else 0 - build_plot_output_v2(canvas, scales, width, height, style_opts, left_margin, top_margin) + build_plot_output_v2(canvas, scales, width, height, style_opts, left_margin, top_margin, NULL) } @@ -497,6 +619,11 @@ build_plot_output <- function(canvas, scales, width, height, show_axes, title) { #' @return Formatted string #' @keywords internal format_axis_label <- function(value) { + # Handle exact zero + if (value == 0) { + return("0") + } + # Use scientific notation for very small or very large numbers if (abs(value) < 0.01 || abs(value) >= 10000) { sprintf("%.1e", value) } else if (abs(value) < 1) { @@ -584,18 +711,24 @@ render_faceted_plot <- function(built, facet_info, width, height, canvas_type, show_axes <- style_opts$show_axes # Calculate dimensions for each panel - # Reserve space for: title, facet labels, axes - top_margin <- if (!is.null(labels$title)) 2 else 1 + # Reserve space for: title, subtitle, facet labels, axes, x label + top_margin <- 1 # At least 1 for facet labels + if (!is.null(labels$title)) top_margin <- top_margin + 1 + if (!is.null(labels$subtitle)) top_margin <- top_margin + 1 + bottom_margin <- 2 # For x-axis values + if (!is.null(labels$x)) bottom_margin <- bottom_margin + 1 # Extra row for x label left_margin <- if (show_axes) 7 else 0 + if (!is.null(labels$y) && left_margin > 0) left_margin <- left_margin + 1 # Extra col for y label # Calculate panel dimensions panel_width <- floor((width - left_margin) / n_cols) - panel_height <- floor((height - top_margin - 2) / n_rows) # -2 for x-axis + panel_height <- floor((height - top_margin - bottom_margin) / n_rows) # Create output matrix output <- matrix(" ", nrow = height, ncol = width) # Add title if present + current_row <- 1 if (!is.null(labels$title)) { title_chars <- strsplit(substr(labels$title, 1, width), "")[[1]] if (style_opts$title_align == "center") { @@ -604,7 +737,21 @@ render_faceted_plot <- function(built, facet_info, width, height, canvas_type, start_col <- left_margin + 1 } for (i in seq_along(title_chars)) { - output[1, start_col + i - 1] <- title_chars[i] + output[current_row, start_col + i - 1] <- title_chars[i] + } + current_row <- current_row + 1 + } + + # Add subtitle if present + if (!is.null(labels$subtitle)) { + sub_chars <- strsplit(substr(labels$subtitle, 1, width), "")[[1]] + if (style_opts$title_align == "center") { + start_col <- max(1, floor((width - length(sub_chars)) / 2)) + } else { + start_col <- left_margin + 1 + } + for (i in seq_along(sub_chars)) { + output[current_row, start_col + i - 1] <- sub_chars[i] } } @@ -629,9 +776,11 @@ render_faceted_plot <- function(built, facet_info, width, height, canvas_type, canvas <- create_canvas(canvas_width, canvas_height, canvas_type) - # Create scales for this panel + # Create scales for this panel (with border padding if needed, using canvas multipliers) panel_params <- built$layout$panel_params[[panel_idx]] - scales <- create_panel_scales(panel_params, canvas$pixel_width, canvas$pixel_height) + scales <- create_panel_scales(panel_params, canvas$pixel_width, canvas$pixel_height, + has_border = style_opts$border, + x_mult = canvas$x_mult, y_mult = canvas$y_mult) # Draw grid lines first (behind data) if (style_opts$grid != "none") { @@ -658,9 +807,9 @@ render_faceted_plot <- function(built, facet_info, width, height, canvas_type, if (is.null(handler)) next - # Render + # Render (pass style_opts for geoms that need it, like boxplot) tryCatch({ - handler(panel_data, canvas, scales, layer$aes_params) + handler(panel_data, canvas, scales, layer$aes_params, style_opts) }, error = function(e) { warning(sprintf("Error rendering %s in panel %d: %s", geom_class, panel_idx, e$message)) @@ -699,20 +848,42 @@ render_faceted_plot <- function(built, facet_info, width, height, canvas_type, # Add Y axis for leftmost panels if (panel_col == 1 && show_axes) { - y_ticks <- pretty(scales$y_range, n = 3) - y_ticks <- y_ticks[y_ticks >= scales$y_range[1] & y_ticks <= scales$y_range[2]] - - for (tick in y_ticks) { - y_frac <- (tick - scales$y_range[1]) / (scales$y_range[2] - scales$y_range[1]) - row <- out_row_start + 1 + round((1 - y_frac) * (canvas_height - 1)) - - if (row >= 1 && row <= height) { - label <- format_axis_label(tick) - label_chars <- strsplit(label, "")[[1]] - start_col <- max(1, left_margin - length(label_chars)) - for (i in seq_along(label_chars)) { - if (start_col + i - 1 <= left_margin && start_col + i - 1 >= 1) { - output[row, start_col + i - 1] <- label_chars[i] + # Check if we have discrete y labels + if (!is.null(scales$y_labels) && length(scales$y_labels) > 0) { + # Use discrete labels for y-axis + for (i in seq_along(scales$y_labels)) { + pos <- scales$y_label_positions[i] + y_frac <- (pos - scales$y_range[1]) / (scales$y_range[2] - scales$y_range[1]) + row <- out_row_start + 1 + round((1 - y_frac) * (canvas_height - 1)) + + if (row >= 1 && row <= height) { + label <- scales$y_labels[i] + label_chars <- strsplit(label, "")[[1]] + start_col <- max(1, left_margin - length(label_chars)) + for (j in seq_along(label_chars)) { + if (start_col + j - 1 <= left_margin && start_col + j - 1 >= 1) { + output[row, start_col + j - 1] <- label_chars[j] + } + } + } + } + } else { + # Use numeric ticks for y-axis + y_ticks <- pretty(scales$y_range, n = 3) + y_ticks <- y_ticks[y_ticks >= scales$y_range[1] & y_ticks <= scales$y_range[2]] + + for (tick in y_ticks) { + y_frac <- (tick - scales$y_range[1]) / (scales$y_range[2] - scales$y_range[1]) + row <- out_row_start + 1 + round((1 - y_frac) * (canvas_height - 1)) + + if (row >= 1 && row <= height) { + label <- format_axis_label(tick) + label_chars <- strsplit(label, "")[[1]] + start_col <- max(1, left_margin - length(label_chars)) + for (j in seq_along(label_chars)) { + if (start_col + j - 1 <= left_margin && start_col + j - 1 >= 1) { + output[row, start_col + j - 1] <- label_chars[j] + } } } } @@ -723,20 +894,42 @@ render_faceted_plot <- function(built, facet_info, width, height, canvas_type, if (panel_row == n_rows && show_axes) { x_row <- out_row_start + canvas_height + 1 if (x_row <= height) { - x_ticks <- pretty(scales$x_range, n = 3) - x_ticks <- x_ticks[x_ticks >= scales$x_range[1] & x_ticks <= scales$x_range[2]] - - for (tick in x_ticks) { - x_frac <- (tick - scales$x_range[1]) / (scales$x_range[2] - scales$x_range[1]) - col <- out_col_start + round(x_frac * (canvas_width - 1)) + # Check if we have discrete labels + if (!is.null(scales$x_labels) && length(scales$x_labels) > 0) { + # Use discrete labels + for (i in seq_along(scales$x_labels)) { + pos <- scales$x_label_positions[i] + x_frac <- (pos - scales$x_range[1]) / (scales$x_range[2] - scales$x_range[1]) + col <- out_col_start + round(x_frac * (canvas_width - 1)) + + if (col >= 1 && col <= width) { + label <- scales$x_labels[i] + label_chars <- strsplit(label, "")[[1]] + start_col <- col - floor(length(label_chars) / 2) + for (j in seq_along(label_chars)) { + if (start_col + j - 1 >= 1 && start_col + j - 1 <= width) { + output[x_row, start_col + j - 1] <- label_chars[j] + } + } + } + } + } else { + # Use numeric ticks + x_ticks <- pretty(scales$x_range, n = 3) + x_ticks <- x_ticks[x_ticks >= scales$x_range[1] & x_ticks <= scales$x_range[2]] - if (col >= 1 && col <= width) { - label <- format_axis_label(tick) - label_chars <- strsplit(label, "")[[1]] - start_col <- col - floor(length(label_chars) / 2) - for (i in seq_along(label_chars)) { - if (start_col + i - 1 >= 1 && start_col + i - 1 <= width) { - output[x_row, start_col + i - 1] <- label_chars[i] + for (tick in x_ticks) { + x_frac <- (tick - scales$x_range[1]) / (scales$x_range[2] - scales$x_range[1]) + col <- out_col_start + round(x_frac * (canvas_width - 1)) + + if (col >= 1 && col <= width) { + label <- format_axis_label(tick) + label_chars <- strsplit(label, "")[[1]] + start_col <- col - floor(length(label_chars) / 2) + for (j in seq_along(label_chars)) { + if (start_col + j - 1 >= 1 && start_col + j - 1 <= width) { + output[x_row, start_col + j - 1] <- label_chars[j] + } } } } @@ -745,6 +938,46 @@ render_faceted_plot <- function(built, facet_info, width, height, canvas_type, } } + # Add Y axis label (vertically on the left) + if (!is.null(labels$y) && left_margin >= 2) { + y_label <- labels$y + y_chars <- strsplit(substr(y_label, 1, min(nchar(y_label), panel_height * n_rows)), "")[[1]] + label_start <- top_margin + floor((panel_height * n_rows - length(y_chars)) / 2) + for (i in seq_along(y_chars)) { + row <- label_start + i + if (row >= 1 && row <= height) { + output[row, 1] <- y_chars[i] + } + } + } + + # Add X axis label (centered at bottom) + if (!is.null(labels$x)) { + x_row <- top_margin + panel_height * n_rows + 2 + if (x_row <= height) { + x_label <- substr(labels$x, 1, width - left_margin) + x_chars <- strsplit(x_label, "")[[1]] + # Center across all panels + plot_area_width <- panel_width * n_cols + start_col <- left_margin + floor((plot_area_width - length(x_chars)) / 2) + for (i in seq_along(x_chars)) { + if (start_col + i - 1 >= 1 && start_col + i - 1 <= width) { + output[x_row, start_col + i - 1] <- x_chars[i] + } + } + } + } + + # Add legend if present + legend_info <- extract_legend_info(built) + if (!is.null(legend_info) && length(legend_info) > 0 && + !identical(style_opts$legend, "none")) { + # Calculate plot height for legend centering + plot_height <- panel_height * n_rows + output <- add_legend_to_output(output, legend_info, style_opts$legend, + top_margin, plot_height) + } + # Print cat("\n") for (i in seq_len(nrow(output))) { @@ -760,24 +993,94 @@ render_faceted_plot <- function(built, facet_info, width, height, canvas_type, #' @param panel_params Panel parameters from ggplot_build #' @param plot_width Pixel width #' @param plot_height Pixel height +#' @param has_border Whether a border will be drawn (adds padding) #' @return List with scale functions #' @keywords internal -create_panel_scales <- function(panel_params, plot_width, plot_height) { +create_panel_scales <- function(panel_params, plot_width, plot_height, has_border = FALSE, + x_mult = 1, y_mult = 1) { + # Get x and y ranges from panel params x_range <- panel_params$x.range y_range <- panel_params$y.range - + # Fallback if ranges not available if (is.null(x_range)) x_range <- c(0, 1) if (is.null(y_range)) y_range <- c(0, 1) + + # Add padding if border is present to prevent data from overlapping border + # Padding must be at least the canvas multiplier to ensure data stays in + # a different character cell than the border (e.g., braille is 2x4 per char) + if (has_border) { + x_padding <- x_mult + 1 # Move past border character cell + y_padding <- y_mult + 1 + } else { + x_padding <- 0 + y_padding <- 0 + } + x_min <- 1 + x_padding + x_max <- plot_width - x_padding + y_min <- 1 + y_padding + y_max <- plot_height - y_padding + + # Ensure we have valid ranges + if (x_max <= x_min) { + x_min <- 1 + x_max <- plot_width + } + if (y_max <= y_min) { + y_min <- 1 + y_max <- plot_height + } # Create scaling functions x_scale <- function(x) { - ((x - x_range[1]) / (x_range[2] - x_range[1])) * (plot_width - 1) + 1 + ((x - x_range[1]) / (x_range[2] - x_range[1])) * (x_max - x_min) + x_min } y_scale <- function(y) { - plot_height - ((y - y_range[1]) / (y_range[2] - y_range[1])) * (plot_height - 1) + y_max - ((y - y_range[1]) / (y_range[2] - y_range[1])) * (y_max - y_min) + } + + # Check for discrete x-axis labels (only use labels for discrete scales) + x_labels <- NULL + x_label_positions <- NULL + x_is_discrete <- !is.null(panel_params$x) && + !is.null(panel_params$x$is_discrete) && + tryCatch(panel_params$x$is_discrete(), error = function(e) FALSE) + + if (x_is_discrete && !is.null(panel_params$x$breaks)) { + x_labels <- panel_params$x$get_labels() + x_label_positions <- attr(panel_params$x$breaks, "pos") + if (is.null(x_label_positions)) { + x_label_positions <- seq_along(x_labels) + } + # Filter out NA values from labels and positions + if (!is.null(x_labels) && length(x_labels) > 0) { + valid <- !is.na(x_labels) + x_labels <- x_labels[valid] + x_label_positions <- x_label_positions[valid] + } + } + + # Check for discrete y-axis labels (only use labels for discrete scales) + y_labels <- NULL + y_label_positions <- NULL + y_is_discrete <- !is.null(panel_params$y) && + !is.null(panel_params$y$is_discrete) && + tryCatch(panel_params$y$is_discrete(), error = function(e) FALSE) + + if (y_is_discrete && !is.null(panel_params$y$breaks)) { + y_labels <- panel_params$y$get_labels() + y_label_positions <- attr(panel_params$y$breaks, "pos") + if (is.null(y_label_positions)) { + y_label_positions <- seq_along(y_labels) + } + # Filter out NA values from labels and positions + if (!is.null(y_labels) && length(y_labels) > 0) { + valid <- !is.na(y_labels) + y_labels <- y_labels[valid] + y_label_positions <- y_label_positions[valid] + } } list( @@ -786,7 +1089,11 @@ create_panel_scales <- function(panel_params, plot_width, plot_height) { x_range = x_range, y_range = y_range, width = plot_width, - height = plot_height + height = plot_height, + x_labels = x_labels, + x_label_positions = x_label_positions, + y_labels = y_labels, + y_label_positions = y_label_positions ) } diff --git a/R/helper_functions.r b/R/helper_functions.r index 0f70871..1bdebc3 100644 --- a/R/helper_functions.r +++ b/R/helper_functions.r @@ -1,3 +1,6 @@ +#' @importFrom crayon blue red green yellow magenta cyan silver white black +NULL + #' Print plot matrix #' #' This function prints a plot matrix to the console. @@ -131,6 +134,9 @@ normalize_data <- function(data, data_min, data_max, plot_range) { + if (data_max == data_min) { + return(rep(round(plot_range / 2), length(data))) + } val <- ((data - data_min) / (data_max - data_min) * (plot_range)) + 1 val[val < 1] <- 1 val[val > plot_range] <- plot_range @@ -204,25 +210,27 @@ remove_color_codes <- function(s) { #' @examples #' is_braille("A") is_braille <- function(char) { + if (is.null(char) || length(char) == 0 || nchar(char) == 0) return(FALSE) + # Get the first character's code (ignore ANSI escape sequences) code <- utf8ToInt(char) - return((code >= 0x2800 && code <= 0x28FF)) + if (length(code) == 0) return(FALSE) + # Check only the first code point + code <- code[1] + return(code >= 0x2800 && code <= 0x28FF) } #' Get Braille dot bit value #' #' Returns the bit value for a specific dot position in a Braille cell. -#' Braille cells have a 2x4 dot matrix: +#' Braille cells have a 2x4 dot matrix with the following bit values: #' -#' Col 0 Col 1 -#' ┌────┬────┐ -#' Row 0 │ 0x01│ 0x08│ -#' ├────┼────┤ -#' Row 1 │ 0x02│ 0x10│ -#' ├────┼────┤ -#' Row 2 │ 0x04│ 0x20│ -#' ├────┼────┤ -#' Row 3 │ 0x40│ 0x80│ -#' └────┴────┘ +#' \preformatted{ +#' Col 0 Col 1 +#' Row 0: 0x01 0x08 +#' Row 1: 0x02 0x10 +#' Row 2: 0x04 0x20 +#' Row 3: 0x40 0x80 +#' } #' #' @param dot_row Row within the Braille cell (0-3, top to bottom) #' @param dot_col Column within the Braille cell (0-1, left to right) diff --git a/R/plotcli.r b/R/plotcli.r index b92522c..ab864d0 100644 --- a/R/plotcli.r +++ b/R/plotcli.r @@ -465,9 +465,15 @@ plotcli <- R6Class("plotcli", if (is.null(self$xlim)) { x_range <- self$x_max - self$x_min - cushion_x <- x_range * cushion_percentage - self$x_min <- self$x_min - cushion_x - self$x_max <- self$x_max + cushion_x + if (x_range == 0) { + expand <- if (self$x_min == 0) 1 else abs(self$x_min) * 0.05 + self$x_min <- self$x_min - expand + self$x_max <- self$x_max + expand + } else { + cushion_x <- x_range * cushion_percentage + self$x_min <- self$x_min - cushion_x + self$x_max <- self$x_max + cushion_x + } } else { self$x_min <- self$xlim[1] self$x_max <- self$xlim[2] @@ -475,9 +481,15 @@ plotcli <- R6Class("plotcli", if (is.null(self$ylim)) { y_range <- self$y_max - self$y_min - cushion_y <- y_range * cushion_percentage - self$y_min <- self$y_min - cushion_y - self$y_max <- self$y_max + cushion_y + if (y_range == 0) { + expand <- if (self$y_min == 0) 1 else abs(self$y_min) * 0.05 + self$y_min <- self$y_min - expand + self$y_max <- self$y_max + expand + } else { + cushion_y <- y_range * cushion_percentage + self$y_min <- self$y_min - cushion_y + self$y_max <- self$y_max + cushion_y + } } else { self$y_min <- self$ylim[1] self$y_max <- self$ylim[2] diff --git a/R/zzz.r b/R/zzz.r index 0707c3b..688cab0 100644 --- a/R/zzz.r +++ b/R/zzz.r @@ -1,3 +1,11 @@ +.onLoad <- function(libname, pkgname) { + # Enable crayon colors even in non-interactive sessions (e.g., Rscript) + # This ensures colored output works when running scripts + if (is.null(getOption("crayon.enabled"))) { + options(crayon.enabled = TRUE) + } +} + .onAttach <- function(libname, pkgname) { # Set default options plotcli_options(plot_width = 60, plot_height = 20, braille = FALSE) diff --git a/README.md b/README.md index 6dbe499..9a86f98 100644 --- a/README.md +++ b/README.md @@ -1,111 +1,192 @@ -# plotcli: Command-Line Plots for R +# plotcli: ggplot2 in Your Terminal [![CRAN status](https://www.r-pkg.org/badges/version/plotcli?color=green)](https://CRAN.R-project.org/package=plotcli) [![CRAN checks](https://badges.cranchecks.info/worst/plotcli.svg)](https://cran.r-project.org/web/checks/check_results_plotcli.html) -[![Downloads](https://cranlogs.r-pkg.org/badges/grand-total/plotcli)](http://www.r-pkg.org/pkg/plotcli) -[![Downloads](http://cranlogs.r-pkg.org/badges/plotcli?color=blue)](http://www.r-pkg.org/pkg/plotcli) +[![Downloads](https://cranlogs.r-pkg.org/badges/grand-total/plotcli)](https://www.r-pkg.org/pkg/plotcli) +[![Downloads](https://cranlogs.r-pkg.org/badges/plotcli?color=blue)](https://www.r-pkg.org/pkg/plotcli) +

+ plotcli: colored scatter plot in terminal +

-![Colored Density Plot on Terminal](docs/boxplot.jpg) +plotcli renders ggplot2 plots directly in the terminal using Unicode Braille characters and ANSI colors. +Write your ggplot code as usual, then call `ggplotcli()` to see it in the console -- no graphics device needed. -plotcli is an R package that brings the power of command-line plotting to your R environment. -With a simple and intuitive R6 class interface, plotcli allows you to create and customize a -variety of plot types, such as scatter, line, bar, and box plots, directly in your console. +Inspired by the excellent [UnicodePlots.jl](https://github.com/JuliaPlots/UnicodePlots.jl). -Features +## Installation + +```r +# From CRAN +install.packages("plotcli") -- Convert `ggplot2` objects to colored terminal plots with `ggplotcli` -- Easy-to-use R6 class interface -- Supports scatter, line, bar, and box plots -- Customizable plot elements: title, axis labels, ticks, and legend -- Braille character support for high-resolution plots -- Convenience wrappers for most frequently used functions +# Development version from GitHub +remotes::install_github("cheuerde/plotcli") +``` -`plotcli` is heavily inspired by the excellent [UnicodePlots.jl](https://github.com/JuliaPlots/UnicodePlots.jl) library. +## Quick Start +Any ggplot2 plot works. Build your plot as usual, then pass it to `ggplotcli()`: ```r -> ggplotcli(ggplot(iris, aes(x = Sepal.Width, y = Sepal.Length, color = Species)) + geom_boxplot()) - - ┌────────────────────────────────────────────────────────────┐ - 4.4 │ ─────── │ - │ │ │ - │ │ │ - │ │ │ - │ │ ─────── │ - 3.8 │ ┌───────┐ │ │ - │ │ │ │ │ - │ │───────│ ─────── │ │ - │ │ │ │ │ │ setosa -Sepal.Length 3.2 │ └───────┘ │ ┌───────┐ │ versicolor - │ │ │ │ │ │ virginica - │ │ ┌───────┐ │───────│ │ - │ ─────── │───────│ └───────┘ │ - │ │ │ │ │ - 2.6 │ │ │ │ │ - │ └───────┘ │ │ - │ │ │ │ - │ * │ ─────── │ - │ │ │ - 2.0 │ ─────── │ - └────────────────────────────────────────────────────────────┘ - - setosa versicolor virginica - - Sepal.Width +library(plotcli) +library(ggplot2) + +p <- ggplot(mtcars, aes(x = wt, y = mpg, color = factor(cyl))) + + geom_point() + + labs(title = "MPG vs Weight by Cylinders", + x = "Weight (1000 lbs)", y = "Miles per Gallon", + color = "Cylinders") + + theme_bw() + +ggplotcli(p) ``` +

+ Scatter plot with colored groups +

-## Installation +## Gallery -You can install the plotcli package from GitHub using the devtools package: +### Boxplots ```r -# Install devtools if you haven't already -if (!requireNamespace("devtools", quietly = TRUE)) { - install.packages("devtools") -} +p <- ggplot(df, aes(x = group, y = value, fill = group)) + + geom_boxplot() + + labs(title = "Distribution Comparison by Group") +ggplotcli(p) +``` + +

+ Boxplot +

+ +### Line Charts + +```r +p <- ggplot(economics, aes(x = date, y = unemploy)) + + geom_line(color = "steelblue") + + geom_smooth(color = "red", se = FALSE) + + labs(title = "US Unemployment Over Time") +ggplotcli(p) +``` -# Install plotcli from GitHub -devtools::install_github("cheuerde/plotcli") +

+ Line chart +

+ +### Bar Charts + +

+ Bar chart +

+ +### Histograms + +

+ Histogram +

+ +### Density Plots + +

+ Density plot +

+ +### Heatmaps + +```r +cor_mat <- cor(mtcars[, c("mpg", "cyl", "disp", "hp", "wt", "qsec")]) +df <- as.data.frame(as.table(cor_mat)) +names(df) <- c("Var1", "Var2", "value") +p <- ggplot(df, aes(Var1, Var2, fill = value)) + + geom_tile() + + labs(title = "Correlation Heatmap", fill = "correlation") +ggplotcli(p) ``` -## Usage +

+ Heatmap +

-The easiest way to use the package if you are already familiar with `ggplot2` -is to configure your ggplot2 object as usual and then simply convert to a `plotcli` -terminal plot with `ggplotcli`: +### Faceted Plots ```r -# Load the plotcli package -library(plotcli) +p <- ggplot(mpg, aes(x = displ, y = hwy)) + + geom_point(color = "steelblue") + + geom_smooth(method = "lm", color = "red", se = FALSE) + + facet_wrap(~drv) + + theme_bw() +ggplotcli(p, width = 80, height = 18) +``` -data(mtcars) -mtcars$cf = as.character(mtcars$cyl) +

+ Faceted plot +

+ +### Canvas Types + +**Block canvas** -- medium resolution using block characters: +

+ Block canvas +

+ +**ASCII canvas** -- basic ASCII for maximum compatibility: +

+ ASCII canvas +

+ +## Supported Geoms (27) + +| Geom | Status | +|------|--------| +| `geom_point` | :white_check_mark: | +| `geom_line`, `geom_path` | :white_check_mark: | +| `geom_step` | :white_check_mark: | +| `geom_bar`, `geom_col`, `geom_histogram` | :white_check_mark: | +| `geom_boxplot` | :white_check_mark: | +| `geom_violin` | :white_check_mark: | +| `geom_density` | :white_check_mark: | +| `geom_smooth` | :white_check_mark: | +| `geom_area` | :white_check_mark: | +| `geom_ribbon` | :white_check_mark: | +| `geom_segment`, `geom_hline`, `geom_vline`, `geom_abline` | :white_check_mark: | +| `geom_errorbar`, `geom_linerange`, `geom_pointrange`, `geom_crossbar` | :white_check_mark: | +| `geom_rect`, `geom_tile`, `geom_raster` (heatmaps) | :white_check_mark: | +| `geom_text`, `geom_label` | :white_check_mark: | +| `geom_rug` | :white_check_mark: | +| `facet_wrap`, `facet_grid` | :white_check_mark: | + +## Options -p = ggplot(mtcars, aes(x = mpg, y = wt, color = cf)) + geom_point() +```r +# Control size +ggplotcli(p, width = 80, height = 24) -# print to terminal -ggplotcli(p, braille = FALSE) +# Canvas types +ggplotcli(p, canvas_type = "braille") # High resolution (default) +ggplotcli(p, canvas_type = "block") # Block characters +ggplotcli(p, canvas_type = "ascii") # ASCII only ``` -Check the vignettes for all possible ways of using the package. +## Direct R6 Class Usage -## Showcase +For lower-level control, use the `plotcli` R6 class directly: -![Colored Density Plot on Terminal](docs/scatter.jpg) -![Colored Density Plot on Terminal](docs/density_raw.jpg) -![Colored Density Plot on Terminal](docs/regression.jpg) -![Colored Density Plot on Terminal](docs/hist.jpg) -![Colored Density Plot on Terminal](docs/pca.jpg) +```r +pc <- plotcli$new(plot_width = 60, plot_height = 20, x_label = "wt", y_label = "mpg", + title = "MPG vs Weight") +pc$add_data(list(x = mtcars$wt, y = mtcars$mpg, type = "scatter", name = "mtcars")) +pc$print_plot() +``` ## Similar Projects - - [txtplot](https://github.com/bbnkmp/txtplot/): The OG in R - - [r-plot](https://github.com/geotheory/r-plot): Collection of excellent terminal plotting functions - - [UnicodePlots.jl](https://github.com/JuliaPlots/UnicodePlots.jl): The gold standard for terminal graphics - - [plotext](https://github.com/piccolomo/plotext): Powerful terminal graphics in python +- [txtplot](https://github.com/bbnkmp/txtplot/): The OG in R +- [r-plot](https://github.com/geotheory/r-plot): Collection of excellent terminal plotting functions +- [UnicodePlots.jl](https://github.com/JuliaPlots/UnicodePlots.jl): The gold standard for terminal graphics +- [plotext](https://github.com/piccolomo/plotext): Powerful terminal graphics in Python ## License -`plotcli` is released under the MIT License. +`plotcli` is released under the LGPL-3 License. diff --git a/docs/ascii.png b/docs/ascii.png new file mode 100644 index 0000000..a720268 Binary files /dev/null and b/docs/ascii.png differ diff --git a/docs/bar.png b/docs/bar.png new file mode 100644 index 0000000..550778f Binary files /dev/null and b/docs/bar.png differ diff --git a/docs/block.png b/docs/block.png new file mode 100644 index 0000000..9612a03 Binary files /dev/null and b/docs/block.png differ diff --git a/docs/boxplot.jpg b/docs/boxplot.jpg deleted file mode 100644 index 29db859..0000000 Binary files a/docs/boxplot.jpg and /dev/null differ diff --git a/docs/boxplot.png b/docs/boxplot.png new file mode 100644 index 0000000..b239860 Binary files /dev/null and b/docs/boxplot.png differ diff --git a/docs/bp.jpg b/docs/bp.jpg deleted file mode 100644 index d9f0da9..0000000 Binary files a/docs/bp.jpg and /dev/null differ diff --git a/docs/density.jpg b/docs/density.jpg deleted file mode 100644 index 0c88eca..0000000 Binary files a/docs/density.jpg and /dev/null differ diff --git a/docs/density.png b/docs/density.png new file mode 100644 index 0000000..9d641a9 Binary files /dev/null and b/docs/density.png differ diff --git a/docs/density_raw.jpg b/docs/density_raw.jpg deleted file mode 100644 index 8fc07f7..0000000 Binary files a/docs/density_raw.jpg and /dev/null differ diff --git a/docs/facet.png b/docs/facet.png new file mode 100644 index 0000000..76fdd55 Binary files /dev/null and b/docs/facet.png differ diff --git a/docs/facet_grid.png b/docs/facet_grid.png new file mode 100644 index 0000000..3b8d0f9 Binary files /dev/null and b/docs/facet_grid.png differ diff --git a/docs/generate_png.sh b/docs/generate_png.sh new file mode 100755 index 0000000..5aceebd --- /dev/null +++ b/docs/generate_png.sh @@ -0,0 +1,137 @@ +#!/bin/bash +# generate_png.sh - Generate PNG images from plotcli terminal output +# +# This script captures ANSI-colored terminal output from R/plotcli and converts +# it to PNG images with a nice terminal theme (Solarized Dark). +# +# Requirements: +# - R with plotcli, ggplot2, dplyr installed +# - Python 3 with ansi2html: pip install ansi2html +# - Chromium or Google Chrome browser +# +# Usage: +# ./generate_png.sh input.R output.png [width] [height] +# +# Example: +# # Create a simple R script +# echo 'library(plotcli); library(ggplot2) +# p <- ggplot(mtcars, aes(x=wt, y=mpg, color=factor(cyl))) + geom_point() +# ggplotcli(p, width=70, height=18)' > myplot.R +# +# # Generate PNG +# ./generate_png.sh myplot.R myplot.png +# +# # With custom dimensions (default: 900x550) +# ./generate_png.sh myplot.R myplot.png 1000 600 + +set -e + +# Check arguments +if [ $# -lt 2 ]; then + echo "Usage: $0 [width] [height]" + echo "" + echo "Example:" + echo " $0 myplot.R myplot.png" + echo " $0 myplot.R myplot.png 1000 600" + exit 1 +fi + +INPUT_R="$1" +OUTPUT_PNG="$2" +WIDTH="${3:-900}" +HEIGHT="${4:-550}" + +# Check if input file exists +if [ ! -f "$INPUT_R" ]; then + echo "Error: Input file '$INPUT_R' not found" + exit 1 +fi + +# Check dependencies +if ! command -v Rscript &> /dev/null; then + echo "Error: Rscript not found. Please install R." + exit 1 +fi + +if ! python3 -c "import ansi2html" &> /dev/null; then + echo "Error: ansi2html not found. Install with: pip install ansi2html" + exit 1 +fi + +# Find chromium or chrome +CHROME="" +for cmd in chromium chromium-browser google-chrome google-chrome-stable; do + if command -v "$cmd" &> /dev/null; then + CHROME="$cmd" + break + fi +done + +if [ -z "$CHROME" ]; then + echo "Error: Chromium or Google Chrome not found" + exit 1 +fi + +# Create temp files +TEMP_DIR=$(mktemp -d) +TEMP_HTML="$TEMP_DIR/plot.html" +TEMP_ANSI="$TEMP_DIR/plot.ansi" + +# Cleanup on exit +cleanup() { + rm -rf "$TEMP_DIR" +} +trap cleanup EXIT + +# Run R script and capture ANSI output +echo "Running R script..." +LANG=en_US.UTF-8 LC_ALL=en_US.UTF-8 Rscript "$INPUT_R" 2>/dev/null > "$TEMP_ANSI" + +# Convert ANSI to HTML with inline styles +echo "Converting to HTML..." +ANSI_CONTENT=$(cat "$TEMP_ANSI" | python3 -m ansi2html --inline) + +# Create themed HTML +cat > "$TEMP_HTML" << EOF + + + + + + +
+$ANSI_CONTENT +
+ + +EOF + +# Convert HTML to PNG using headless Chrome +echo "Generating PNG..." +"$CHROME" --headless --disable-gpu --screenshot="$OUTPUT_PNG" \ + --window-size="${WIDTH},${HEIGHT}" \ + "file://$TEMP_HTML" 2>/dev/null + +echo "Done! Output saved to: $OUTPUT_PNG" diff --git a/docs/heatmap.png b/docs/heatmap.png new file mode 100644 index 0000000..79249e0 Binary files /dev/null and b/docs/heatmap.png differ diff --git a/docs/hist.jpg b/docs/hist.jpg deleted file mode 100644 index 46ed1b1..0000000 Binary files a/docs/hist.jpg and /dev/null differ diff --git a/docs/histogram.png b/docs/histogram.png new file mode 100644 index 0000000..3162bf2 Binary files /dev/null and b/docs/histogram.png differ diff --git a/docs/line.png b/docs/line.png new file mode 100644 index 0000000..f32d72f Binary files /dev/null and b/docs/line.png differ diff --git a/docs/noborder.png b/docs/noborder.png new file mode 100644 index 0000000..2d85266 Binary files /dev/null and b/docs/noborder.png differ diff --git a/docs/pca.jpg b/docs/pca.jpg deleted file mode 100644 index 9728f9b..0000000 Binary files a/docs/pca.jpg and /dev/null differ diff --git a/docs/regression.jpg b/docs/regression.jpg deleted file mode 100644 index db482d2..0000000 Binary files a/docs/regression.jpg and /dev/null differ diff --git a/docs/scatter.jpg b/docs/scatter.jpg deleted file mode 100644 index daeff33..0000000 Binary files a/docs/scatter.jpg and /dev/null differ diff --git a/docs/scatter.png b/docs/scatter.png new file mode 100644 index 0000000..2e5647f Binary files /dev/null and b/docs/scatter.png differ diff --git a/docs/showcase.R b/docs/showcase.R new file mode 100644 index 0000000..0c2762f --- /dev/null +++ b/docs/showcase.R @@ -0,0 +1,182 @@ +#!/usr/bin/env Rscript +# plotcli Showcase +# Run this script to see all the features of plotcli in action +# Usage: Rscript docs/showcase.R + +library(plotcli) +library(ggplot2) +library(dplyr) + +cat("\n") +cat("========================================================================\n") +cat(" plotcli Feature Showcase\n") +cat("========================================================================\n\n") + +# ----------------------------------------------------------------------------- +cat("1. SCATTER PLOT WITH LEGEND\n") +cat("------------------------------------------------------------------------\n\n") + +p <- ggplot(mtcars, aes(x = wt, y = mpg, color = factor(cyl))) + + geom_point(size = 3) + + labs(title = "MPG vs Weight by Cylinders", + x = "Weight (1000 lbs)", y = "Miles per Gallon", + color = "Cylinders") + + theme_bw() +ggplotcli(p, width = 75, height = 20) + +cat("\n") + +# ----------------------------------------------------------------------------- +cat("2. DENSITY PLOT WITH FILL COLORS\n") +cat("------------------------------------------------------------------------\n\n") + +p <- ggplot(iris, aes(x = Sepal.Length, fill = Species)) + + geom_density(alpha = 0.7) + + labs(title = "Iris Sepal Length Distribution", + x = "Sepal Length (cm)", y = "Density") + + theme_bw() +ggplotcli(p, width = 75, height = 18) + +cat("\n") + +# ----------------------------------------------------------------------------- +cat("3. BOXPLOT WITH OUTLIERS\n") +cat("------------------------------------------------------------------------\n\n") + +set.seed(42) +boxplot_data <- data.frame( + category = rep(c("Group A", "Group B", "Group C", "Group D", "Group E"), each = 50), + value = c( + rnorm(50, mean = 25, sd = 5), + rnorm(50, mean = 35, sd = 6), + rnorm(50, mean = 20, sd = 4), + rnorm(50, mean = 40, sd = 7), + rnorm(50, mean = 30, sd = 5) + ) +) + +p <- ggplot(boxplot_data, aes(x = category, y = value, fill = category)) + + geom_boxplot() + + labs(title = "Distribution Comparison by Group", + x = "Category", y = "Value") + + theme_bw() + + theme(legend.position = "none") +ggplotcli(p, width = 75, height = 22, boxplot_style = "ascii") + +cat("\n") + +# ----------------------------------------------------------------------------- +cat("4. HEATMAP (CORRELATION MATRIX)\n") +cat("------------------------------------------------------------------------\n\n") + +cor_data <- cor(mtcars[, c("mpg", "cyl", "disp", "hp", "drat", "wt", "qsec")]) %>% + as.data.frame() %>% + tibble::rownames_to_column("var1") %>% + tidyr::pivot_longer(-var1, names_to = "var2", values_to = "correlation") + +p <- ggplot(cor_data, aes(x = var1, y = var2, fill = correlation)) + + geom_tile() + + scale_fill_gradient2(low = "blue", mid = "white", high = "red", + midpoint = 0, limits = c(-1, 1)) + + labs(title = "Correlation Heatmap - mtcars") + + theme_minimal() +ggplotcli(p, width = 70, height = 20) + +cat("\n") + +# ----------------------------------------------------------------------------- +cat("5. FACETED PLOT (facet_wrap)\n") +cat("------------------------------------------------------------------------\n\n") + +p <- ggplot(mpg, aes(x = displ, y = hwy, color = drv)) + + geom_point(size = 2) + + facet_wrap(~cyl, ncol = 2) + + labs(title = "Highway MPG vs Engine Displacement", + subtitle = "Faceted by Cylinder Count", + x = "Displacement (L)", y = "Highway MPG", + color = "Drive") + + theme_bw() +ggplotcli(p, width = 85, height = 26) + +cat("\n") + +# ----------------------------------------------------------------------------- +cat("6. LINE CHART WITH SMOOTHING\n") +cat("------------------------------------------------------------------------\n\n") + +econ <- economics %>% filter(date >= "1990-01-01", date <= "2015-01-01") +p <- ggplot(econ, aes(x = date, y = unemploy/1000)) + + geom_line(color = "steelblue", linewidth = 1) + + geom_smooth(color = "red", se = FALSE, method = "loess", span = 0.3) + + labs(title = "US Unemployment Over Time", + subtitle = "Blue: actual data, Red: smoothed trend", + x = "Year", y = "Unemployed (millions)") + + theme_bw() +ggplotcli(p, width = 80, height = 16) + +cat("\n") + +# ----------------------------------------------------------------------------- +cat("7. BAR CHART (GROUPED)\n") +cat("------------------------------------------------------------------------\n\n") + +p <- ggplot(mpg, aes(x = class, fill = drv)) + + geom_bar(position = "dodge") + + labs(title = "Vehicle Classes by Drive Type", + x = "Vehicle Class", y = "Count", + fill = "Drive") + + theme_bw() +ggplotcli(p, width = 80, height = 16) + +cat("\n") + +# ----------------------------------------------------------------------------- +cat("8. HISTOGRAM WITH DENSITY OVERLAY\n") +cat("------------------------------------------------------------------------\n\n") + +p <- ggplot(mtcars, aes(x = mpg)) + + geom_histogram(aes(y = after_stat(density)), bins = 12, + fill = "steelblue", color = "white") + + geom_density(color = "red", linewidth = 1) + + labs(title = "Distribution of MPG", + x = "Miles per Gallon", y = "Density") + + theme_bw() +ggplotcli(p, width = 70, height = 16) + +cat("\n") + +# ----------------------------------------------------------------------------- +cat("9. CANVAS TYPE COMPARISON\n") +cat("------------------------------------------------------------------------\n\n") + +base_plot <- ggplot(mtcars, aes(x = wt, y = mpg)) + + geom_point(color = "blue") + + labs(title = "Canvas Comparison") + + theme_bw() + +cat("BRAILLE canvas (high resolution):\n\n") +ggplotcli(base_plot, width = 50, height = 12, canvas_type = "braille") + +cat("\nBLOCK canvas (medium resolution):\n\n") +ggplotcli(base_plot, width = 50, height = 12, canvas_type = "block") + +cat("\nASCII canvas (maximum compatibility):\n\n") +ggplotcli(base_plot, width = 50, height = 12, canvas_type = "ascii") + +cat("\n") + +# ----------------------------------------------------------------------------- +cat("10. FACET GRID (2D FACETING)\n") +cat("------------------------------------------------------------------------\n\n") + +p <- ggplot(mpg %>% filter(cyl %in% c(4, 6, 8)), aes(x = displ, y = hwy)) + + geom_point(color = "steelblue") + + facet_grid(drv ~ cyl) + + labs(title = "Facet Grid: Drive Type vs Cylinders") + + theme_bw() +ggplotcli(p, width = 90, height = 28) + +cat("\n") +cat("========================================================================\n") +cat(" End of Showcase\n") +cat("========================================================================\n\n") diff --git a/inst/doc/ggplotcli.R b/inst/doc/ggplotcli.R new file mode 100644 index 0000000..673ddc2 --- /dev/null +++ b/inst/doc/ggplotcli.R @@ -0,0 +1,231 @@ +## ----setup, include = FALSE--------------------------------------------------- +knitr::opts_chunk$set( + collapse = TRUE, + comment = "#>" +) + + +## ----------------------------------------------------------------------------- +library(plotcli) +library(ggplot2) + +# Create a ggplot +p <- ggplot(mtcars, aes(x = wt, y = mpg, color = factor(cyl))) + + geom_point() + + labs(title = "MPG vs Weight by Cylinders") + +# Render in terminal +ggplotcli(p, width = 60, height = 16) + + +## ----------------------------------------------------------------------------- +p <- ggplot(iris, aes(x = Sepal.Length, y = Sepal.Width, color = Species)) + + geom_point() + + labs(title = "Iris: Sepal Dimensions by Species") +ggplotcli(p, width = 60, height = 16) + + +## ----------------------------------------------------------------------------- +# Multiple colored lines +df <- data.frame( + x = rep(1:30, 2), + y = c(sin(1:30/4) * 10, cos(1:30/4) * 10), + type = rep(c("sin", "cos"), each = 30) +) +p <- ggplot(df, aes(x, y, color = type)) + + geom_line() + + labs(title = "Sine and Cosine Waves") +ggplotcli(p, width = 60, height = 12) + + +## ----------------------------------------------------------------------------- +p <- ggplot(mtcars, aes(x = mpg, fill = factor(cyl))) + + geom_histogram(bins = 10, position = "dodge") + + labs(title = "MPG Distribution by Cylinders") +ggplotcli(p, width = 60, height = 12) + + +## ----------------------------------------------------------------------------- +p <- ggplot(mtcars, aes(x = mpg, color = factor(cyl))) + + geom_density() + + labs(title = "MPG Density by Cylinders") +ggplotcli(p, width = 60, height = 12) + + +## ----------------------------------------------------------------------------- +df <- data.frame( + category = c("A", "B", "C", "D", "E", "F"), + value = c(25, 45, 30, 60, 35, 50) +) +p <- ggplot(df, aes(x = category, y = value, fill = category)) + + geom_col() + + labs(title = "Category Values") +ggplotcli(p, width = 60, height = 12) + + +## ----------------------------------------------------------------------------- +set.seed(42) +df <- data.frame( + group = factor(rep(paste0("Group ", 1:6), each = 50)), + value = c(rnorm(50, 10, 3), rnorm(50, 5, 2), rnorm(50, 8, 4), + rnorm(50, 6, 2), rnorm(50, 12, 3), rnorm(50, 7, 2)) +) +p <- ggplot(df, aes(x = group, y = value, fill = group)) + + geom_boxplot() + + labs(title = "Boxplot Colored by Group", y = "Value", x = "Group") +ggplotcli(p, width = 80, height = 20, boxplot_style = "ascii") + + +## ----------------------------------------------------------------------------- +ggplotcli(p, width = 80, height = 20, boxplot_style = "braille") + + +## ----------------------------------------------------------------------------- +# Histogram with density overlay +p <- ggplot(mtcars, aes(x = mpg)) + + geom_histogram(aes(y = after_stat(density)), bins = 10, fill = "gray") + + geom_density(color = "red") + + labs(title = "Histogram with Density Overlay") +ggplotcli(p, width = 60, height = 12) + + +## ----------------------------------------------------------------------------- +# Points with smooth line +p <- ggplot(mtcars, aes(x = wt, y = mpg)) + + geom_point(color = "gray") + + geom_smooth(method = "loess", color = "red") + + labs(title = "Scatter with LOESS Smooth") +suppressMessages(ggplotcli(p, width = 60, height = 12)) + + +## ----------------------------------------------------------------------------- +mtcars$cyl_fac <- factor(mtcars$cyl) +p <- ggplot(mtcars, aes(x = wt, y = mpg, color = cyl_fac)) + + geom_point() + + facet_wrap(~cyl_fac) + + labs(title = "MPG vs Weight: Faceted by Cylinders") +ggplotcli(p, width = 75, height = 16) + + +## ----------------------------------------------------------------------------- +p <- ggplot(mtcars, aes(x = wt, y = mpg, color = factor(gear))) + + geom_point() + + facet_grid(am ~ cyl) + + labs(title = "MPG: AM (rows) x Cylinders (cols)") +ggplotcli(p, width = 80, height = 20) + + +## ----------------------------------------------------------------------------- +p <- ggplot(mtcars, aes(x = hp, y = qsec)) + + geom_point(color = "cyan") + + labs(title = "Quarter Mile Time vs HP") + +# With border +ggplotcli(p, width = 55, height = 12, border = TRUE) + +# With grid +ggplotcli(p, width = 55, height = 12, grid = "major") + +# Both +ggplotcli(p, width = 55, height = 12, border = TRUE, grid = "major") + + +## ----------------------------------------------------------------------------- +p <- ggplot(mtcars, aes(x = wt, y = mpg)) + + geom_point(color = "blue") + + labs(title = "theme_bw() - Grid + Border") + +# theme_bw has both grid and border +ggplotcli(p + theme_bw(), width = 60, height = 14, border = "auto", grid = "auto") + +# theme_classic has border but no grid +ggplotcli(p + theme_classic() + labs(title = "theme_classic() - Border Only"), + width = 60, height = 14, border = "auto", grid = "auto") + + +## ----------------------------------------------------------------------------- +wave <- ggplot(data.frame(x = 1:25, y = sin(1:25/4)*8), aes(x, y)) + + geom_line(color = "green") + +# Braille (highest resolution - 2x4 dots per character) +ggplotcli(wave + labs(title = "Braille Canvas (highest resolution)"), + width = 50, height = 8, canvas_type = "braille") + +# Block (medium resolution - uses block characters) +ggplotcli(wave + labs(title = "Block Canvas (medium resolution)"), + width = 50, height = 8, canvas_type = "block") + +# ASCII (basic, most compatible) +ggplotcli(wave + labs(title = "ASCII Canvas (most compatible)"), + width = 50, height = 8, canvas_type = "ascii") + + +## ----------------------------------------------------------------------------- +set.seed(123) +df <- data.frame( + group = factor(rep(paste0("G", 1:8), each = 30)), + value = unlist(lapply(1:8, function(i) rnorm(30, mean = i * 2, sd = 1.5))) +) +p <- ggplot(df, aes(x = group, y = value, fill = group)) + + geom_boxplot() + + labs(title = "8 Groups with Optimized Color Distribution") +ggplotcli(p, width = 85, height = 18, boxplot_style = "ascii") + + +## ----------------------------------------------------------------------------- +set.seed(42) +df <- data.frame( + treatment = factor(rep(c("Control", "Drug A", "Drug B"), each = 60)), + timepoint = factor(rep(rep(c("Baseline", "Week 4", "Week 8"), each = 20), 3)), + response = c( + rnorm(20, 50, 10), rnorm(20, 52, 10), rnorm(20, 51, 10), # Control + rnorm(20, 50, 10), rnorm(20, 65, 12), rnorm(20, 70, 11), # Drug A + rnorm(20, 50, 10), rnorm(20, 58, 11), rnorm(20, 62, 10) # Drug B + ) +) + +p <- ggplot(df, aes(x = timepoint, y = response)) + + geom_boxplot(aes(fill = treatment)) + + labs(title = "Treatment Response Over Time", + subtitle = "Faceted by treatment group", + x = "Timepoint", y = "Response") + + theme_bw() + +ggplotcli(p, width = 100, height = 22, boxplot_style = "ascii") + + +## ----------------------------------------------------------------------------- +# Simulated experiment data +set.seed(123) +x <- seq(0, 10, length.out = 50) +df <- data.frame( + x = rep(x, 3), + y = c( + 2 * x + rnorm(50, 0, 1.5), + 1.5 * x + 3 + rnorm(50, 0, 1.2), + x^1.2 + rnorm(50, 0, 1) + ), + group = rep(c("Linear", "Offset", "Power"), each = 50) +) + +p <- ggplot(df, aes(x = x, y = y, color = group)) + + geom_point(alpha = 0.6) + + geom_smooth(method = "loess", se = FALSE) + + labs(title = "Multi-Group Regression Analysis", + subtitle = "Points with LOESS smoothing", + x = "Predictor", y = "Response") + + theme_minimal() + +suppressMessages(ggplotcli(p, width = 70, height = 18)) + + +## ----------------------------------------------------------------------------- +p <- ggplot(iris, aes(x = Sepal.Length, y = Petal.Length, color = Species)) + + geom_point() + + facet_wrap(~Species) + + labs(title = "Iris Dataset: Sepal vs Petal Length", + subtitle = "Faceted by species with color legend") + + theme_bw() + +ggplotcli(p, width = 80, height = 16) + diff --git a/inst/doc/ggplotcli.Rmd b/inst/doc/ggplotcli.Rmd new file mode 100644 index 0000000..2f1e5dd --- /dev/null +++ b/inst/doc/ggplotcli.Rmd @@ -0,0 +1,329 @@ +--- +title: "ggplotcli: Universal ggplot2 to Terminal Plotting" +author: "Claas Heuer" +date: "`r Sys.Date()`" +output: rmarkdown::html_vignette +vignette: > + %\VignetteIndexEntry{ggplotcli: Universal ggplot2 to Terminal Plotting} + %\VignetteEngine{knitr::rmarkdown} + %\VignetteEncoding{UTF-8} +--- + +```{r setup, include = FALSE} +knitr::opts_chunk$set( + collapse = TRUE, + comment = "#>" +) +``` + +## Introduction + +`ggplotcli` is a universal converter that renders any ggplot2 plot in the terminal using Unicode/ASCII characters. It automatically extracts data, aesthetics, and styling from ggplot objects, supporting 15+ geom types, faceting, color aesthetics, and legends. + +## Basic Usage + +```{r} +library(plotcli) +library(ggplot2) + +# Create a ggplot +p <- ggplot(mtcars, aes(x = wt, y = mpg, color = factor(cyl))) + + geom_point() + + labs(title = "MPG vs Weight by Cylinders") + +# Render in terminal +ggplotcli(p, width = 60, height = 16) +``` + +## Supported Geoms + +### Scatter Plots (geom_point) + +```{r} +p <- ggplot(iris, aes(x = Sepal.Length, y = Sepal.Width, color = Species)) + + geom_point() + + labs(title = "Iris: Sepal Dimensions by Species") +ggplotcli(p, width = 60, height = 16) +``` + +### Line Plots (geom_line) + +```{r} +# Multiple colored lines +df <- data.frame( + x = rep(1:30, 2), + y = c(sin(1:30/4) * 10, cos(1:30/4) * 10), + type = rep(c("sin", "cos"), each = 30) +) +p <- ggplot(df, aes(x, y, color = type)) + + geom_line() + + labs(title = "Sine and Cosine Waves") +ggplotcli(p, width = 60, height = 12) +``` + +### Histograms (geom_histogram) + +```{r} +p <- ggplot(mtcars, aes(x = mpg, fill = factor(cyl))) + + geom_histogram(bins = 10, position = "dodge") + + labs(title = "MPG Distribution by Cylinders") +ggplotcli(p, width = 60, height = 12) +``` + +### Density Plots (geom_density) + +```{r} +p <- ggplot(mtcars, aes(x = mpg, color = factor(cyl))) + + geom_density() + + labs(title = "MPG Density by Cylinders") +ggplotcli(p, width = 60, height = 12) +``` + +### Bar Charts (geom_col) + +```{r} +df <- data.frame( + category = c("A", "B", "C", "D", "E", "F"), + value = c(25, 45, 30, 60, 35, 50) +) +p <- ggplot(df, aes(x = category, y = value, fill = category)) + + geom_col() + + labs(title = "Category Values") +ggplotcli(p, width = 60, height = 12) +``` + +### Boxplots (geom_boxplot) + +Boxplots are rendered with box-drawing characters by default, showing whiskers, box (Q1-Q3), median line, and outliers: + +```{r} +set.seed(42) +df <- data.frame( + group = factor(rep(paste0("Group ", 1:6), each = 50)), + value = c(rnorm(50, 10, 3), rnorm(50, 5, 2), rnorm(50, 8, 4), + rnorm(50, 6, 2), rnorm(50, 12, 3), rnorm(50, 7, 2)) +) +p <- ggplot(df, aes(x = group, y = value, fill = group)) + + geom_boxplot() + + labs(title = "Boxplot Colored by Group", y = "Value", x = "Group") +ggplotcli(p, width = 80, height = 20, boxplot_style = "ascii") +``` + +You can also use Braille rendering for boxplots: + +```{r} +ggplotcli(p, width = 80, height = 20, boxplot_style = "braille") +``` + +## Combining Multiple Geoms + +```{r} +# Histogram with density overlay +p <- ggplot(mtcars, aes(x = mpg)) + + geom_histogram(aes(y = after_stat(density)), bins = 10, fill = "gray") + + geom_density(color = "red") + + labs(title = "Histogram with Density Overlay") +ggplotcli(p, width = 60, height = 12) +``` + +```{r} +# Points with smooth line +p <- ggplot(mtcars, aes(x = wt, y = mpg)) + + geom_point(color = "gray") + + geom_smooth(method = "loess", color = "red") + + labs(title = "Scatter with LOESS Smooth") +suppressMessages(ggplotcli(p, width = 60, height = 12)) +``` + +## Faceting + +### facet_wrap with Color Aesthetics + +Faceting works seamlessly with color/fill aesthetics and legends: + +```{r} +mtcars$cyl_fac <- factor(mtcars$cyl) +p <- ggplot(mtcars, aes(x = wt, y = mpg, color = cyl_fac)) + + geom_point() + + facet_wrap(~cyl_fac) + + labs(title = "MPG vs Weight: Faceted by Cylinders") +ggplotcli(p, width = 75, height = 16) +``` + +### facet_grid + +```{r} +p <- ggplot(mtcars, aes(x = wt, y = mpg, color = factor(gear))) + + geom_point() + + facet_grid(am ~ cyl) + + labs(title = "MPG: AM (rows) x Cylinders (cols)") +ggplotcli(p, width = 80, height = 20) +``` + +## Styling Options + +### Borders and Grid Lines + +```{r} +p <- ggplot(mtcars, aes(x = hp, y = qsec)) + + geom_point(color = "cyan") + + labs(title = "Quarter Mile Time vs HP") + +# With border +ggplotcli(p, width = 55, height = 12, border = TRUE) + +# With grid +ggplotcli(p, width = 55, height = 12, grid = "major") + +# Both +ggplotcli(p, width = 55, height = 12, border = TRUE, grid = "major") +``` + +### Theme Auto-Detection + +ggplotcli automatically respects ggplot2 themes: + +```{r} +p <- ggplot(mtcars, aes(x = wt, y = mpg)) + + geom_point(color = "blue") + + labs(title = "theme_bw() - Grid + Border") + +# theme_bw has both grid and border +ggplotcli(p + theme_bw(), width = 60, height = 14, border = "auto", grid = "auto") + +# theme_classic has border but no grid +ggplotcli(p + theme_classic() + labs(title = "theme_classic() - Border Only"), + width = 60, height = 14, border = "auto", grid = "auto") +``` + +## Canvas Types + +Three rendering modes are available: + +```{r} +wave <- ggplot(data.frame(x = 1:25, y = sin(1:25/4)*8), aes(x, y)) + + geom_line(color = "green") + +# Braille (highest resolution - 2x4 dots per character) +ggplotcli(wave + labs(title = "Braille Canvas (highest resolution)"), + width = 50, height = 8, canvas_type = "braille") + +# Block (medium resolution - uses block characters) +ggplotcli(wave + labs(title = "Block Canvas (medium resolution)"), + width = 50, height = 8, canvas_type = "block") + +# ASCII (basic, most compatible) +ggplotcli(wave + labs(title = "ASCII Canvas (most compatible)"), + width = 50, height = 8, canvas_type = "ascii") +``` + +## Color Mapping + +ggplotcli intelligently maps ggplot2 colors to terminal colors (red, yellow, green, cyan, blue, magenta). The mapping prioritizes **color distinctness** over hue accuracy to maximize visual differentiation between groups. + +### Many Groups (8+) + +Even with many groups, colors are distributed to minimize repetition: + +```{r} +set.seed(123) +df <- data.frame( + group = factor(rep(paste0("G", 1:8), each = 30)), + value = unlist(lapply(1:8, function(i) rnorm(30, mean = i * 2, sd = 1.5))) +) +p <- ggplot(df, aes(x = group, y = value, fill = group)) + + geom_boxplot() + + labs(title = "8 Groups with Optimized Color Distribution") +ggplotcli(p, width = 85, height = 18, boxplot_style = "ascii") +``` + +## Showcase: Maximum Complexity + +### Complex Faceted Boxplot + +```{r} +set.seed(42) +df <- data.frame( + treatment = factor(rep(c("Control", "Drug A", "Drug B"), each = 60)), + timepoint = factor(rep(rep(c("Baseline", "Week 4", "Week 8"), each = 20), 3)), + response = c( + rnorm(20, 50, 10), rnorm(20, 52, 10), rnorm(20, 51, 10), # Control + rnorm(20, 50, 10), rnorm(20, 65, 12), rnorm(20, 70, 11), # Drug A + rnorm(20, 50, 10), rnorm(20, 58, 11), rnorm(20, 62, 10) # Drug B + ) +) + +p <- ggplot(df, aes(x = timepoint, y = response)) + + geom_boxplot(aes(fill = treatment)) + + labs(title = "Treatment Response Over Time", + subtitle = "Faceted by treatment group", + x = "Timepoint", y = "Response") + + theme_bw() + +ggplotcli(p, width = 100, height = 22, boxplot_style = "ascii") +``` + +### Multi-Layer Scientific Plot + +```{r} +# Simulated experiment data +set.seed(123) +x <- seq(0, 10, length.out = 50) +df <- data.frame( + x = rep(x, 3), + y = c( + 2 * x + rnorm(50, 0, 1.5), + 1.5 * x + 3 + rnorm(50, 0, 1.2), + x^1.2 + rnorm(50, 0, 1) + ), + group = rep(c("Linear", "Offset", "Power"), each = 50) +) + +p <- ggplot(df, aes(x = x, y = y, color = group)) + + geom_point(alpha = 0.6) + + geom_smooth(method = "loess", se = FALSE) + + labs(title = "Multi-Group Regression Analysis", + subtitle = "Points with LOESS smoothing", + x = "Predictor", y = "Response") + + theme_minimal() + +suppressMessages(ggplotcli(p, width = 70, height = 18)) +``` + +### Dense Scatter with Facets + +```{r} +p <- ggplot(iris, aes(x = Sepal.Length, y = Petal.Length, color = Species)) + + geom_point() + + facet_wrap(~Species) + + labs(title = "Iris Dataset: Sepal vs Petal Length", + subtitle = "Faceted by species with color legend") + + theme_bw() + +ggplotcli(p, width = 80, height = 16) +``` + +## Supported Features Summary + +| Feature | Status | +|---------|--------| +| geom_point | ✓ | +| geom_line, geom_path | ✓ | +| geom_bar, geom_col, geom_histogram | ✓ | +| geom_density | ✓ | +| geom_smooth | ✓ | +| geom_area | ✓ | +| geom_segment, geom_hline, geom_vline | ✓ | +| geom_rect | ✓ | +| geom_text | ✓ | +| geom_boxplot | ✓ | +| Color/fill aesthetics | ✓ | +| Legends (auto-generated) | ✓ | +| facet_wrap, facet_grid | ✓ | +| Titles, subtitles, captions | ✓ | +| Theme auto-detection | ✓ | +| Optimized color mapping | ✓ | +| Multiple canvas types | ✓ | +| geom_tile (heatmaps) | Planned | +| geom_violin | Planned | + diff --git a/inst/doc/ggplotcli.html b/inst/doc/ggplotcli.html new file mode 100644 index 0000000..2c23b65 --- /dev/null +++ b/inst/doc/ggplotcli.html @@ -0,0 +1,1078 @@ + + + + + + + + + + + + + + + + +ggplotcli: Universal ggplot2 to Terminal Plotting + + + + + + + + + + + + + + + + + + + + + + + + + + +

ggplotcli: Universal ggplot2 to Terminal +Plotting

+

Claas Heuer

+

2026-02-09

+ + + +
+

Introduction

+

ggplotcli is a universal converter that renders any +ggplot2 plot in the terminal using Unicode/ASCII characters. It +automatically extracts data, aesthetics, and styling from ggplot +objects, supporting 15+ geom types, faceting, color aesthetics, and +legends.

+
+
+

Basic Usage

+
library(plotcli)
+#> Loading required package: R6
+#> Loading required package: ggplot2
+#> plotcli loaded. Use plotcli_options() to set global options.
+library(ggplot2)
+
+# Create a ggplot
+p <- ggplot(mtcars, aes(x = wt, y = mpg, color = factor(cyl))) +
+  geom_point() +
+  labs(title = "MPG vs Weight by Cylinders")
+
+# Render in terminal
+ggplotcli(p, width = 60, height = 16)
+#> 
+#>                 MPG vs Weight by Cylinders                               
+#>   35.0       ⠄                                                           
+#>                  ⠐                                                       
+#>   30.0   ⠐⠐                                                              
+#>               ⠠                                             factor(cyl)  
+#> m 25.0           ⠁           ⢀                              * 4          
+#> p                  ⠄         ⠄                              * 6          
+#> g 20.0              ⠐ ⠠ ⠐⠠   ⠐                              * 8          
+#>                         ⠈       ⢰    ⠐                                   
+#>                              ⡀      ⠁   ⠄                                
+#>   15.0                          ⠈⠈⠆ ⠈                  ⠂                 
+#>                                      ⠁                                   
+#>   10.0                                                ⠂ ⠂                
+#>               2.0         3.0         4.0         5.0                    
+#>                                wt                                        
+#> 
+
+
+

Supported Geoms

+
+

Scatter Plots (geom_point)

+
p <- ggplot(iris, aes(x = Sepal.Length, y = Sepal.Width, color = Species)) +
+  geom_point() +
+  labs(title = "Iris: Sepal Dimensions by Species")
+ggplotcli(p, width = 60, height = 16)
+#> 
+#>             Iris: Sepal Dimensions by Species                             
+#> S  4.5                     ⠠                                              
+#> e                    ⡀   ⠄                                                
+#> p  4.0                 ⢀     ⠂                                            
+#> a                  ⢐  ⢀⢀   ⠐                         ⠐  ⠂   Species       
+#> l  3.5       ⠁   ⠁⠨⠠ ⠄   ⠄                     ⠁            * setosa      
+#> .         ⢀  ⡁⢀ ⠁ ⢨⠨ ⠁ ⠈      ⡀⠈  ⠁⠨⢀ ⡀ ⠠ ⡀⡀⢀  ⡀            * versicolor  
+#> W  3.0   ⢀⢀  ⠂  ⡂⡂⢀    ⢀  ⡀⢀  ⡀⢀⢀   ⠐ ⡀⢀⢐ ⡀⠂  ⡀⡀    ⢀⢀      * virginica   
+#> i         ⠐               ⡂⢐ ⡀ ⠐⢐ ⡂⢐⢐ ⡀⠐  ⡀     ⠐⢀   ⢀                    
+#> d  2.5               ⠁   ⠄⠁⠠ ⠅ ⠈⠠  ⠈⠈                ⠠                    
+#> t                ⠅ ⠈     ⠅⠁⠈       ⠈    ⠈                                 
+#> h           ⠁     ⠈      ⠁     ⠐  ⠂⠈                                      
+#>    2.0            ⠐                                                       
+#>                  5.0          6.0          7.0          8.0               
+#>                           Sepal.Length                                    
+#> 
+
+
+

Line Plots (geom_line)

+
# Multiple colored lines
+df <- data.frame(
+  x = rep(1:30, 2),
+  y = c(sin(1:30/4) * 10, cos(1:30/4) * 10),
+  type = rep(c("sin", "cos"), each = 30)
+)
+p <- ggplot(df, aes(x, y, color = type)) +
+  geom_line() +
+  labs(title = "Sine and Cosine Waves")
+ggplotcli(p, width = 60, height = 12)
+#> 
+#>                   Sine and Cosine Waves                            
+#>   10.0   ⠠⢄⡀   ⣀⠤⠒⠢⠤⣀⡀                       ⣀⠤⠔⠒⠤⠤⣀   ⣀⠄          
+#>            ⠈⡱⢖⠉      ⠈⠑⠤⡀                 ⣀⠔⠊       ⢉⠶⢎     type   
+#>    5.0    ⡠⠊  ⠑⠢⡀       ⠈⠢⡀             ⢠⠊        ⣀⠔⠁  ⠣⡀   * cos  
+#> y        ⠈      ⠘⢄        ⠑⢄          ⢀⠔⠁       ⢠⠊          * sin  
+#>      0            ⠑⢄        ⠑⠤⡀     ⢀⠔⠁       ⢀⠔⠁                  
+#>   -5.0              ⠑⠤⡀       ⠈⢆  ⢀⠔⠁        ⡰⠁                    
+#>                       ⠈⠢⡀       ⡱⠶⣁       ⡠⠒⠉                      
+#>  -10.0                  ⠈⠑⠒⠒⠤⠤⠒⠉   ⠉⠑⠒⠤⠔⠒⠉                         
+#>         0      5.0    10.0    15.0    20.0    25.0    30.0         
+#>                                x                                   
+#> 
+
+
+

Histograms (geom_histogram)

+
p <- ggplot(mtcars, aes(x = mpg, fill = factor(cyl))) +
+  geom_histogram(bins = 10, position = "dodge") +
+  labs(title = "MPG Distribution by Cylinders")
+ggplotcli(p, width = 60, height = 12)
+#> 
+#>               MPG Distribution by Cylinders                              
+#>                       ⣶⣶                                                 
+#> c  6.0                ⣿⣿                                    factor(cyl)  
+#> o                     ⣿⣿                                    * 4          
+#> u  4.0                ⣿⣿     ⢰⣶⡆                            * 6          
+#> n                     ⣿⣿ ⣤⣤⣤⡄⢸⣿⡇⢠⣤⣤            ⣤⣤           * 8          
+#> t  2.0      ⢠⣤⡄  ⣤⣤   ⣿⣿ ⣿⣿⣿⣧⣼⣿⡇⢸⣿⣿  ⢠⣤⡄       ⣿⣿                        
+#>             ⢸⣿⡇  ⣿⣿   ⣿⣿ ⣿⣿⣿⣿⣿⣿⡇⢸⣿⣿  ⢸⣿⡇       ⣿⣿  ⢠⣤⡄                   
+#>      0   ⠠⠤⠤⠼⠿⠧⠤⠤⠿⠿⠤⠤⠤⠿⠿⠤⠿⠿⠿⠿⠿⠿⠧⠼⠿⠿⠤⠤⠼⠿⠧⠤⠤⠤⠤⠤⠤⠤⠿⠿⠤⠤⠼⠿⠧⠤⠤⠄                
+#>          10.0     15.0     20.0     25.0    30.0     35.0                
+#>                               mpg                                        
+#> 
+
+
+

Density Plots (geom_density)

+
p <- ggplot(mtcars, aes(x = mpg, color = factor(cyl))) +
+  geom_density() +
+  labs(title = "MPG Density by Cylinders")
+ggplotcli(p, width = 60, height = 12)
+#> 
+#>                  MPG Density by Cylinders                                
+#> d 0.25            ⣠⢦                                                     
+#> e 0.20           ⢠⠃⠈⣇      ⢀⡠⠞⠙⣆                            factor(cyl)  
+#> n                ⡞  ⠸⡀  ⢠⠚⠉⠁   ⠸⡄                           * 4          
+#> s 0.15          ⢠⠃   ⢣ ⢠⠃       ⢧                           * 6          
+#> i 0.10         ⢀⡎    ⠈⢆⡎        ⠘⡄                          * 8          
+#> t 0.05   ⠘⢦   ⢀⡞      ⡼⠳⠤⠖⠒⢦ ⢀⣠⠤⠖⢳⠒⠒⠒⠒⠒⠦⠤⠤⣄⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀                    
+#> y         ⠈⢣⡀⣠⠞      ⡰⠁ ⢀⣀⡤⠔⢻⡉   ⠈⢧                 ⠈⠉⠉⠓⠂                
+#>      0   ⠠⠤⠤⠭⠥⠤⠤⠤⠴⠶⠒⠚⠓⠒⠉⠉    ⠙⠒⠦⠤⠤⠬⠷⠶⠤⠤⠤⠤⠤⠤⠤⠤⠤⠤⠤⠤⠤⠤⠤⠤⠤⠤⠤⠄                
+#>        10.0     15.0      20.0      25.0      30.0      35.0             
+#>                               mpg                                        
+#> 
+
+
+

Bar Charts (geom_col)

+
df <- data.frame(
+  category = c("A", "B", "C", "D", "E", "F"),
+  value = c(25, 45, 30, 60, 35, 50)
+)
+p <- ggplot(df, aes(x = category, y = value, fill = category)) +
+  geom_col() +
+  labs(title = "Category Values")
+ggplotcli(p, width = 60, height = 12)
+#> 
+#>                      Category Values                                  
+#>   60.0                           ⣶⣶⣶⣶⣶⣶⣶⣶                   category  
+#> v 50.0                           ⣿⣿⣿⣿⣿⣿⣿⣿         ⣤⣤⣤⣤⣤⣤⣤⣤  * A       
+#> a 40.0          ⢸⣿⣿⣿⣿⣿⣿⣿⡇        ⣿⣿⣿⣿⣿⣿⣿⣿         ⣿⣿⣿⣿⣿⣿⣿⣿  * B       
+#> l 30.0          ⢸⣿⣿⣿⣿⣿⣿⣿⡇⣀⣀⣀⣀⣀⣀⣀⣀⣿⣿⣿⣿⣿⣿⣿⣿⢰⣶⣶⣶⣶⣶⣶⣶⡆⣿⣿⣿⣿⣿⣿⣿⣿  * C       
+#> u       ⣤⣤⣤⣤⣤⣤⣤⣤⢸⣿⣿⣿⣿⣿⣿⣿⡇⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⢸⣿⣿⣿⣿⣿⣿⣿⡇⣿⣿⣿⣿⣿⣿⣿⣿  * D       
+#> e 20.0  ⣿⣿⣿⣿⣿⣿⣿⣿⢸⣿⣿⣿⣿⣿⣿⣿⡇⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⢸⣿⣿⣿⣿⣿⣿⣿⡇⣿⣿⣿⣿⣿⣿⣿⣿  * E       
+#>   10.0  ⣿⣿⣿⣿⣿⣿⣿⣿⢸⣿⣿⣿⣿⣿⣿⣿⡇⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⢸⣿⣿⣿⣿⣿⣿⣿⡇⣿⣿⣿⣿⣿⣿⣿⣿  * F       
+#>      0  ⠿⠿⠿⠿⠿⠿⠿⠿⠸⠿⠿⠿⠿⠿⠿⠿⠇⠿⠿⠿⠿⠿⠿⠿⠿⠿⠿⠿⠿⠿⠿⠿⠿⠸⠿⠿⠿⠿⠿⠿⠿⠇⠿⠿⠿⠿⠿⠿⠿⠿            
+#>             A       B       C        D       E       F                
+#>                             category                                  
+#> 
+
+
+

Boxplots (geom_boxplot)

+

Boxplots are rendered with box-drawing characters by default, showing +whiskers, box (Q1-Q3), median line, and outliers:

+
set.seed(42)
+df <- data.frame(
+  group = factor(rep(paste0("Group ", 1:6), each = 50)),
+  value = c(rnorm(50, 10, 3), rnorm(50, 5, 2), rnorm(50, 8, 4),
+            rnorm(50, 6, 2), rnorm(50, 12, 3), rnorm(50, 7, 2))
+)
+p <- ggplot(df, aes(x = group, y = value, fill = group)) +
+  geom_boxplot() +
+  labs(title = "Boxplot Colored by Group", y = "Value", x = "Group")
+ggplotcli(p, width = 80, height = 20, boxplot_style = "ascii")
+#> 
+#>                            Boxplot Colored by Group                                        
+#>                                     *                    ───────                           
+#>           ───────                                           │                              
+#>              │                      *                       │                              
+#>   15.0       │                                          ┌───────┐               group      
+#>              │                   ───*───                │       │               * Group 1  
+#> V        ┌───────┐                  │                   │───────│   ───────     * Group 2  
+#> a        │       │                  │                   └───────┘      │        * Group 3  
+#> l 10.0   │───────│              ┌───────┐    ───────        │          │        * Group 4  
+#> u        └───────┘    ───────   │       │   ┌───────┐       │      ┌───────┐    * Group 5  
+#> e            │       ┌───────┐  └───────┘   │───────│    ───────   │       │    * Group 6  
+#>    5.0       │       │───────│      │       └───────┘              └───────┘               
+#>              │       └───────┘      │           │                      │                   
+#>           ───*───     ───────       │        ───────                ───────                
+#>                                  ───────                                                   
+#>      0                   *          *                                                      
+#>                                                                                            
+#>            Group 1    Group 2     Group 3    Group 4     Group 5    Group 6                
+#>                                        Group                                               
+#> 
+

You can also use Braille rendering for boxplots:

+
ggplotcli(p, width = 80, height = 20, boxplot_style = "braille")
+#> 
+#>                            Boxplot Colored by Group                                        
+#>                                      ⡀                                                     
+#>                                                           ⠒⠒⡖⠒⠂                            
+#>             ⠉⠉⡏⠉⠁                                           ⡇                              
+#>   15.0        ⡇                      ⠂                      ⡇                   group      
+#>               ⡇                      ⠂                 ⢰⠒⠒⠒⠒⠓⠒⠒⠒⢲               * Group 1  
+#> V        ⢀⣀⣀⣀⣀⣇⣀⣀⣀⡀                ⠉⠉⡏⠉⠁               ⢸        ⢸    ⢀⣀⣀⣀⣀      * Group 2  
+#> a        ⢸        ⡇                  ⡇                 ⢸⠉⠉⠉⠉⠉⠉⠉⠉⢹      ⢸        * Group 3  
+#> l 10.0   ⢸⠒⠒⠒⠒⠒⠒⠒⠒⡇                  ⡇        ⠐⠒⢲⠒⠒    ⠘⠒⠒⠒⠒⡖⠒⠒⠒⠚      ⢸        * Group 4  
+#> u        ⠸⠤⠤⠤⠤⡤⠤⠤⠤⠇    ⠠⠤⢤⠤⠤    ⢰⠒⠒⠒⠒⠓⠒⠒⠒⢲      ⢸           ⡇      ⢰⠒⠒⠒⠚⠒⠒⠒⠒⡆   * Group 5  
+#> e             ⡇      ⣀⣀⣀⣀⣸⣀⣀⣀⣀⡀ ⢸⠒⠒⠒⠒⠒⠒⠒⠒⢺  ⡖⠒⠒⠒⠚⠒⠒⠒⠒⡆      ⡇      ⢸⠒⠒⠒⠒⠒⠒⠒⠒⡇   * Group 6  
+#>    5.0        ⡇      ⡗⠒⠒⠒⠒⠒⠒⠒⠒⡇ ⠘⠒⠒⠒⠒⡖⠒⠒⠒⠚  ⣏⣉⣉⣉⣉⣉⣉⣉⣉⡇    ⠉⠉⠉⠉⠁    ⠘⠒⠒⠒⢲⠒⠒⠒⠒⠃              
+#>               ⡇      ⠧⠤⠤⠤⢤⠤⠤⠤⠤⠇      ⡇          ⢸                      ⢸                   
+#>             ⠤⠤⡧⠤⠄      ⢀⣀⣸⣀⣀         ⡇        ⠠⠤⠼⠤⠤                    ⢸                   
+#>                                    ⠒⠒⠓⠒⠂                             ⠐⠒⠚⠒⠒                 
+#>      0                               ⠄                                                     
+#>                          ⠈                                                                 
+#>            Group 1    Group 2     Group 3    Group 4     Group 5    Group 6                
+#>                                        Group                                               
+#> 
+
+
+
+

Combining Multiple Geoms

+
# Histogram with density overlay
+p <- ggplot(mtcars, aes(x = mpg)) +
+  geom_histogram(aes(y = after_stat(density)), bins = 10, fill = "gray") +
+  geom_density(color = "red") +
+  labs(title = "Histogram with Density Overlay")
+ggplotcli(p, width = 60, height = 12)
+#> 
+#>               Histogram with Density Overlay                 
+#> d                 ⢰⣶⣶⣶⣶⣶                                     
+#> e 0.08            ⢸⣿⣿⣿⣿⣿⣶⣶⣶⣶⣶⣶⣶⣶⣶                            
+#> n 0.06            ⢸⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿                            
+#> s               ⢀⡴⢻⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠑⢦⡀                         
+#> i 0.04        ⢀⡴⠋ ⢸⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣤⣤⣭⣷⣤⡀        ⣤⣤⣤⣤⣤         
+#> t 0.02   ⢠⣤⣤⣤⣾⣥⣤⣤⣤⣼⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣭⣷⣦⣤⣄⣀⣀⣀⣀⣿⣿⣿⣿⣿         
+#> y        ⢸⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡇    ⣿⣿⣿⣿⣿⣽⣶⣦⣤⡄    
+#>      0   ⠸⠿⠿⠿⠿⠿⠿⠿⠿⠿⠿⠿⠿⠿⠿⠿⠿⠿⠿⠿⠿⠿⠿⠿⠿⠿⠿⠿⠿⠿⠿⠿⠿⠧⠤⠤⠤⠤⠿⠿⠿⠿⠿⠿⠿⠿⠿⠇    
+#>          10.0     15.0     20.0     25.0    30.0     35.0    
+#>                               mpg                            
+#> 
+
# Points with smooth line
+p <- ggplot(mtcars, aes(x = wt, y = mpg)) +
+  geom_point(color = "gray") +
+  geom_smooth(method = "loess", color = "red") +
+  labs(title = "Scatter with LOESS Smooth")
+suppressMessages(ggplotcli(p, width = 60, height = 12))
+#> 
+#>                 Scatter with LOESS Smooth                    
+#>                                                              
+#>   35.0   ⢐⢤⣀⣀⠁   ⠐                                           
+#> m 30.0       ⠉⠲⠢⢄⡀                                           
+#> p 25.0           ⠉⠉⡒⠤⣀⣀      ⡐                               
+#> g 20.0              ⠈ ⠐⠉⠩⠙⠒⠒⠢⠬⢄⣀⣠    ⠠                       
+#>   15.0                       ⠄  ⢈⠩⡒⠒⢣⠤⠤⢄⣂⣀⣀            ⡀     
+#>   10.0                               ⠁     ⠉⠉⠉⠉⠑⠒⠒⠒⠒⠢⠤⡤⠤⡄    
+#>                                                              
+#>               2.0         3.0         4.0         5.0        
+#>                                wt                            
+#> 
+
+
+

Faceting

+
+

facet_wrap with Color Aesthetics

+

Faceting works seamlessly with color/fill aesthetics and legends:

+
mtcars$cyl_fac <- factor(mtcars$cyl)
+p <- ggplot(mtcars, aes(x = wt, y = mpg, color = cyl_fac)) +
+  geom_point() +
+  facet_wrap(~cyl_fac) +
+  labs(title = "MPG vs Weight: Faceted by Cylinders")
+ggplotcli(p, width = 75, height = 16)
+#> 
+#>                    MPG vs Weight: Faceted by Cylinders                              
+#>                4, 1                  6, 1                  8, 1                     
+#>          ⠠                                                                          
+#>         ⣀  ⠁                                                                        
+#>    30.0                                                                    cyl_fac  
+#>           ⠁⠄                                                               * 4      
+#> m           ⡀  ⢀⠁                                                          * 6      
+#> p  20.0     ⠈ ⠂                    ⠂⡐ ⠂                                    * 8      
+#> g                                      ⠅                     ⠂⢀⠁                    
+#>                                                             ⠂⢤⠠ ⠁     ⡀             
+#>                                                                ⠂                    
+#>    10.0                                                              ⠐⠐             
+#>          2.0      4.0          2.0      4.0          2.0      4.0                   
+#>                                                                                     
+#>                                        wt                                           
+#> 
+
+
+

facet_grid

+
p <- ggplot(mtcars, aes(x = wt, y = mpg, color = factor(gear))) +
+  geom_point() +
+  facet_grid(am ~ cyl) +
+  labs(title = "MPG: AM (rows) x Cylinders (cols)")
+ggplotcli(p, width = 80, height = 20)
+#> 
+#>                       MPG: AM (rows) x Cylinders (cols)                                       
+#>                0, 4, 1                 0, 6, 1                 0, 8, 1                        
+#>                                                                                               
+#>    30.0                                                                                       
+#>                 ⢀⠂                                                                            
+#>    20.0      ⠁                           ⠁⡄                       ⡀ ⠄                         
+#>                                                                   ⠔⠌⡄⠐      ⠄   factor(gear)  
+#> m  10.0                                                                    ⠠⠠   * 3           
+#> p              1, 4, 1                 1, 6, 1                 1, 8, 1          * 4           
+#> g        ⠐ ⠠                                                                    * 5           
+#>    30.0 ⠉ ⡀                                                                                   
+#>            ⠈⡀                                                                                 
+#>    20.0       ⠈                       ⠢⠂                                                      
+#>                                                                 ⠐  ⠄                          
+#>    10.0                                                                                       
+#>          2.0        4.0          2.0        4.0          2.0        4.0                       
+#>                                                                                               
+#>                                           wt                                                  
+#>                                                                                               
+#> 
+
+
+
+

Styling Options

+
+

Borders and Grid Lines

+
p <- ggplot(mtcars, aes(x = hp, y = qsec)) +
+  geom_point(color = "cyan") +
+  labs(title = "Quarter Mile Time vs HP")
+
+# With border
+ggplotcli(p, width = 55, height = 12, border = TRUE)
+#> 
+#>                Quarter Mile Time vs HP                  
+#>        ⡏⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⢹  
+#>   22.0 ⡇        ⠠                                    ⢸  
+#> q      ⡇                                             ⢸  
+#> s 20.0 ⡇    ⢲    ⠂⠡ ⢀                                ⢸  
+#> e 18.0 ⡇  ⠈     ⠁ ⢈ ⠈   ⡀  ⢀⠰   ⠂⠐ ⠠                 ⢸  
+#> c      ⡇        ⠁ ⠐⠁    ⠁  ⢀         ⢠               ⢸  
+#>   16.0 ⡇                                ⠂         ⠂  ⢸  
+#>        ⣇⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣸  
+#>        50.0    100     150    200    250     300        
+#>                             hp                          
+#> 
+
+# With grid
+ggplotcli(p, width = 55, height = 12, grid = "major")
+#> 
+#>                Quarter Mile Time vs HP                  
+#>          ⡇     ⠐⢸       ⡇      ⡇      ⢸       ⡇         
+#>   22.0 ⠉⠉⡏⠉⠉⠉⠉⠉⠉⢹⠉⠉⠉⠉⠉⠉⠉⡏⠉⠉⠉⠉⠉⠉⡏⠉⠉⠉⠉⠉⠉⢹⠉⠉⠉⠉⠉⠉⠉⡏⠉⠉⠉⠉⠉⠉⠉  
+#> q      ⣀⣀⣇⣀⣀⣀⣀⣀⣀⣸⣄⣀⣀⣀⣀⣀⣀⣇⣀⣀⣀⣀⣀⣀⣇⣀⣀⣀⣀⣀⣀⣸⣀⣀⣀⣀⣀⣀⣀⣇⣀⣀⣀⣀⣀⣀⣀  
+#> s 20.0   ⡇ ⡂    ⢸ ⠂⢀    ⡇      ⡇      ⢸       ⡇         
+#> e 18.0 ⠤⠤⡧⠤⠤⠤⠤⠤⠥⢼⠬⠤⠴⠤⠤⠤⠤⡧⠤⠤⠤⡤⠤⠤⡧⠤⠤⠤⠤⠤⠤⢼⠤⠤⠤⠤⠤⠤⠤⡧⠤⠤⠤⠤⠤⠤⠤  
+#> c        ⡇     ⠄⢸ ⡆     ⡇  ⠐⠁  ⡇   ⠈  ⢸       ⡇         
+#>   16.0 ⠒⠒⡗⠒⠒⠒⠒⠒⠒⢺⠒⠒⠒⠒⠒⠒⠒⡗⠒⠒⠲⠒⠒⠒⡗⠒⠒⠒⠒⠒⠒⣺⠒⠒⠒⠒⠒⠒⠒⡗⠒⠒⠒⠒⠒⠒⠒  
+#>          ⡇      ⢸       ⡇      ⡇      ⢸  ⠄    ⡇    ⠐    
+#>        50.0    100     150    200    250     300        
+#>                             hp                          
+#> 
+
+# Both
+ggplotcli(p, width = 55, height = 12, border = TRUE, grid = "major")
+#> 
+#>                Quarter Mile Time vs HP                  
+#>        ⡏⠉⠉⡏⠉⠉⠉⠉⠉⠉⡏⠉⠉⠉⠉⠉⠉⡏⠉⠉⠉⠉⠉⠉⡏⠉⠉⠉⠉⠉⠉⡏⠉⠉⠉⠉⠉⠉⡏⠉⠉⠉⠉⠉⠉⠉⢹  
+#>   22.0 ⡇  ⡇     ⠠⡇      ⡇      ⡇      ⡇      ⡇       ⢸  
+#> q      ⡏⠉⠉⡏⠉⠉⠉⠉⠉⠉⡏⠉⠉⠉⠉⠉⠉⡏⠉⠉⠉⠉⠉⠉⡏⠉⠉⠉⠉⠉⠉⡏⠉⠉⠉⠉⠉⠉⡏⠉⠉⠉⠉⠉⠉⠉⢹  
+#> s 20.0 ⡗⠒⠒⡗⠒⢲⠒⠒⠒⠒⡗⠳⠒⢒⠒⠒⠒⡗⠒⠒⠒⠒⠒⠒⡗⠒⠒⠒⠒⠒⠒⡗⠒⠒⠒⠒⠒⠒⡗⠒⠒⠒⠒⠒⠒⠒⢺  
+#> e 18.0 ⡗⠒⠒⡟⠒⠒⠒⠒⠒⠓⡗⢚⠒⠚⠒⠒⠒⡗⠒⠒⢒⠲⠒⠒⡗⠒⠒⠒⠲⠒⠒⡗⠒⠒⠒⠒⠒⠒⡗⠒⠒⠒⠒⠒⠒⠒⢺  
+#> c      ⡧⠤⠤⡧⠤⠤⠤⠤⠤⠥⡧⠴⠥⠤⠤⠤⠤⡧⠤⠤⢤⠤⠤⠤⡧⠤⠤⠤⠤⠤⢤⡧⠤⠤⠤⠤⠤⠤⡧⠤⠤⠤⠤⠤⠤⠤⢼  
+#>   16.0 ⡇  ⡇      ⡇      ⡇      ⡇      ⡇ ⠂    ⡇    ⠂  ⢸  
+#>        ⣇⣀⣀⣇⣀⣀⣀⣀⣀⣀⣇⣀⣀⣀⣀⣀⣀⣇⣀⣀⣀⣀⣀⣀⣇⣀⣀⣀⣀⣀⣀⣇⣀⣀⣀⣀⣀⣀⣇⣀⣀⣀⣀⣀⣀⣀⣸  
+#>        50.0    100     150    200    250     300        
+#>                             hp                          
+#> 
+
+
+

Theme Auto-Detection

+

ggplotcli automatically respects ggplot2 themes:

+
p <- ggplot(mtcars, aes(x = wt, y = mpg)) +
+  geom_point(color = "blue") +
+  labs(title = "theme_bw() - Grid + Border")
+
+# theme_bw has both grid and border
+ggplotcli(p + theme_bw(), width = 60, height = 14, border = "auto", grid = "auto")
+#> 
+#>                 theme_bw() - Grid + Border                   
+#>   35.0 ⡏⠉⠉⢹⠉⠉⠉⠉⠉⡏⠉⠉⠉⠉⠉⡏⠉⠉⠉⠉⢹⠉⠉⠉⠉⠉⡏⠉⠉⠉⠉⢹⠉⠉⠉⠉⠉⢹⠉⠉⠉⠉⠉⡏⠉⠉⠉⠉⢹⠉⠉⢹  
+#>        ⡧⠤⠤⢼⠤⠤⠤⠤⠤⡧⠤⠤⠤⠤⠤⡧⠤⠤⠤⠤⢼⠤⠤⠤⠤⠤⡧⠤⠤⠤⠤⢼⠤⠤⠤⠤⠤⢼⠤⠤⠤⠤⠤⡧⠤⠤⠤⠤⢼⠤⠤⢼  
+#>   30.0 ⣏⣉⣉⣹⣉⣍⣉⣉⣉⣏⣉⣉⣉⣉⣉⣏⣉⣉⣉⣉⣹⣉⣉⣉⣉⣉⣏⣉⣉⣉⣉⣹⣉⣉⣉⣉⣉⣹⣉⣉⣉⣉⣉⣏⣉⣉⣉⣉⣹⣉⣉⣹  
+#> m      ⣗⣒⣒⣺⣒⣒⣒⣒⣲⣗⣒⣒⣒⣒⣒⣗⣒⣒⣒⣒⣺⣒⣒⣒⣒⣒⣗⣒⣒⣒⣒⣺⣒⣒⣒⣒⣒⣺⣒⣒⣒⣒⣒⣗⣒⣒⣒⣒⣺⣒⣒⣺  
+#> p 25.0 ⡗⠒⠒⢺⠒⠒⠒⠒⠒⡗⠒⠒⠒⡒⠒⡗⠒⠒⠒⠒⢺⠒⡒⠒⠒⠒⡗⠒⠒⠒⠒⢺⠒⠒⠒⠒⠒⢺⠒⠒⠒⠒⠒⡗⠒⠒⠒⠒⢺⠒⠒⢺  
+#> g 20.0 ⡯⠭⠭⢽⠭⠭⠭⠭⠭⡯⠭⠭⠭⠭⠭⡯⠯⠭⠭⠯⢽⠭⠭⠭⠭⢭⡯⠭⠭⠭⡭⢽⠭⠭⠭⠭⠭⢽⠭⠭⠭⠭⠭⡯⠭⠭⠭⠭⢽⠭⠭⢽  
+#>        ⡯⠭⠭⢽⠭⠭⠭⠭⠭⡯⠭⠭⠭⠭⠭⡯⠭⠭⠭⠭⢽⠭⢭⠭⠭⢭⣯⠭⠽⢭⠭⢽⠭⠭⠭⠭⠭⢽⠭⠭⠭⠭⠭⡯⠭⠭⠭⠭⢽⠭⠭⢽  
+#>   15.0 ⣗⣒⣒⣺⣒⣒⣒⣒⣒⣗⣒⣒⣒⣒⣒⣗⣒⣒⣒⣒⣺⣒⣒⣒⣒⣒⣗⣓⣒⣒⣒⣺⣒⣒⣒⣒⣒⣺⣒⣒⣒⣒⣒⣗⣒⣒⣒⣓⣺⣒⣒⣺  
+#>        ⡗⠒⠒⢺⠒⠒⠒⠒⠒⡗⠒⠒⠒⠒⠒⡗⠒⠒⠒⠒⢺⠒⠒⠒⠒⠒⡗⠒⠒⠒⠒⢺⠒⠒⠒⠒⠒⢺⠒⠒⠒⠒⠒⡗⠒⠒⠒⠒⢺⠒⠒⢺  
+#>   10.0 ⣇⣀⣀⣸⣀⣀⣀⣀⣀⣇⣀⣀⣀⣀⣀⣇⣀⣀⣀⣀⣸⣀⣀⣀⣀⣀⣇⣀⣀⣀⣀⣸⣀⣀⣀⣀⣀⣸⣀⣀⣀⣀⣀⣇⣀⣀⣀⣀⣸⣀⣀⣸  
+#>               2.0         3.0         4.0         5.0        
+#>                                wt                            
+#> 
+
+# theme_classic has border but no grid
+ggplotcli(p + theme_classic() + labs(title = "theme_classic() - Border Only"), 
+           width = 60, height = 14, border = "auto", grid = "auto")
+#> 
+#>               theme_classic() - Border Only                  
+#>   35.0 ⡏⠉⠉⢹⠉⠉⠉⠉⠉⡏⠉⠉⠉⠉⠉⡏⠉⠉⠉⠉⢹⠉⠉⠉⠉⠉⡏⠉⠉⠉⠉⢹⠉⠉⠉⠉⠉⢹⠉⠉⠉⠉⠉⡏⠉⠉⠉⠉⢹⠉⠉⢹  
+#>        ⡧⠤⠤⢼⠤⠤⠤⠤⠤⡧⠤⠤⠤⠤⠤⡧⠤⠤⠤⠤⢼⠤⠤⠤⠤⠤⡧⠤⠤⠤⠤⢼⠤⠤⠤⠤⠤⢼⠤⠤⠤⠤⠤⡧⠤⠤⠤⠤⢼⠤⠤⢼  
+#>   30.0 ⣏⣉⣉⣹⣉⣍⣉⣉⣉⣏⣉⣉⣉⣉⣉⣏⣉⣉⣉⣉⣹⣉⣉⣉⣉⣉⣏⣉⣉⣉⣉⣹⣉⣉⣉⣉⣉⣹⣉⣉⣉⣉⣉⣏⣉⣉⣉⣉⣹⣉⣉⣹  
+#> m      ⣗⣒⣒⣺⣒⣒⣒⣒⣲⣗⣒⣒⣒⣒⣒⣗⣒⣒⣒⣒⣺⣒⣒⣒⣒⣒⣗⣒⣒⣒⣒⣺⣒⣒⣒⣒⣒⣺⣒⣒⣒⣒⣒⣗⣒⣒⣒⣒⣺⣒⣒⣺  
+#> p 25.0 ⡗⠒⠒⢺⠒⠒⠒⠒⠒⡗⠒⠒⠒⡒⠒⡗⠒⠒⠒⠒⢺⠒⡒⠒⠒⠒⡗⠒⠒⠒⠒⢺⠒⠒⠒⠒⠒⢺⠒⠒⠒⠒⠒⡗⠒⠒⠒⠒⢺⠒⠒⢺  
+#> g 20.0 ⡯⠭⠭⢽⠭⠭⠭⠭⠭⡯⠭⠭⠭⠭⠭⡯⠯⠭⠭⠯⢽⠭⠭⠭⠭⢭⡯⠭⠭⠭⡭⢽⠭⠭⠭⠭⠭⢽⠭⠭⠭⠭⠭⡯⠭⠭⠭⠭⢽⠭⠭⢽  
+#>        ⡯⠭⠭⢽⠭⠭⠭⠭⠭⡯⠭⠭⠭⠭⠭⡯⠭⠭⠭⠭⢽⠭⢭⠭⠭⢭⣯⠭⠽⢭⠭⢽⠭⠭⠭⠭⠭⢽⠭⠭⠭⠭⠭⡯⠭⠭⠭⠭⢽⠭⠭⢽  
+#>   15.0 ⣗⣒⣒⣺⣒⣒⣒⣒⣒⣗⣒⣒⣒⣒⣒⣗⣒⣒⣒⣒⣺⣒⣒⣒⣒⣒⣗⣓⣒⣒⣒⣺⣒⣒⣒⣒⣒⣺⣒⣒⣒⣒⣒⣗⣒⣒⣒⣓⣺⣒⣒⣺  
+#>        ⡗⠒⠒⢺⠒⠒⠒⠒⠒⡗⠒⠒⠒⠒⠒⡗⠒⠒⠒⠒⢺⠒⠒⠒⠒⠒⡗⠒⠒⠒⠒⢺⠒⠒⠒⠒⠒⢺⠒⠒⠒⠒⠒⡗⠒⠒⠒⠒⢺⠒⠒⢺  
+#>   10.0 ⣇⣀⣀⣸⣀⣀⣀⣀⣀⣇⣀⣀⣀⣀⣀⣇⣀⣀⣀⣀⣸⣀⣀⣀⣀⣀⣇⣀⣀⣀⣀⣸⣀⣀⣀⣀⣀⣸⣀⣀⣀⣀⣀⣇⣀⣀⣀⣀⣸⣀⣀⣸  
+#>               2.0         3.0         4.0         5.0        
+#>                                wt                            
+#> 
+
+
+
+

Canvas Types

+

Three rendering modes are available:

+
wave <- ggplot(data.frame(x = 1:25, y = sin(1:25/4)*8), aes(x, y)) +
+  geom_line(color = "green")
+
+# Braille (highest resolution - 2x4 dots per character)
+ggplotcli(wave + labs(title = "Braille Canvas (highest resolution)"), 
+           width = 50, height = 8, canvas_type = "braille")
+#> 
+#>       Braille Canvas (highest resolution)          
+#>            ⢀⣀⠤⠔⠒⠒⠒⠒⠒⠒⠤⢄⡀                           
+#> y  5.0   ⠔⠊⠁           ⠈⠑⠤⣀                        
+#>   -5.0                     ⠉⠑⠢⢄⡀           ⣀⠤⠒⠉    
+#>                                ⠈⠑⠢⠤⠤⠤⠤⠤⠤⠒⠊⠉        
+#>        0      5.0    10.0    15.0   20.0    25.0   
+#>                           x                        
+#> 
+
+# Block (medium resolution - uses block characters)
+ggplotcli(wave + labs(title = "Block Canvas (medium resolution)"), 
+           width = 50, height = 8, canvas_type = "block")
+#> 
+#>         Block Canvas (medium resolution)           
+#>             ▄▄▄▀▀▀▀▀▄▄▄                            
+#> y  5.0   ▄▀▀           ▀▀▀▄▄                       
+#>   -5.0                      ▀▄▄▄           ▄▄▀▀    
+#>                                 ▀▀▀▄▄▄▄▄▀▀▀        
+#>        0      5.0    10.0    15.0   20.0    25.0   
+#>                           x                        
+#> 
+
+# ASCII (basic, most compatible)
+ggplotcli(wave + labs(title = "ASCII Canvas (most compatible)"), 
+           width = 50, height = 8, canvas_type = "ascii")
+#> 
+#>          ASCII Canvas (most compatible)            
+#>               *********                            
+#> y  5.0   *****         *****                       
+#>   -5.0                      ****         ******    
+#>                                 *********          
+#>        0      5.0    10.0    15.0   20.0    25.0   
+#>                           x                        
+#> 
+
+
+

Color Mapping

+

ggplotcli intelligently maps ggplot2 colors to terminal colors (red, +yellow, green, cyan, blue, magenta). The mapping prioritizes +color distinctness over hue accuracy to maximize visual +differentiation between groups.

+
+

Many Groups (8+)

+

Even with many groups, colors are distributed to minimize +repetition:

+
set.seed(123)
+df <- data.frame(
+  group = factor(rep(paste0("G", 1:8), each = 30)),
+  value = unlist(lapply(1:8, function(i) rnorm(30, mean = i * 2, sd = 1.5)))
+)
+p <- ggplot(df, aes(x = group, y = value, fill = group)) +
+  geom_boxplot() +
+  labs(title = "8 Groups with Optimized Color Distribution")
+ggplotcli(p, width = 85, height = 18, boxplot_style = "ascii")
+#> 
+#>                     8 Groups with Optimized Color Distribution                              
+#>                                                                            ─────            
+#>                                                            *      ─────   ┌─────┐    group  
+#>                                                            *     ┌─────┐  └─────┘    * G1   
+#>   15.0                                                   ─────   │─────│   ─────     * G2   
+#> v                                              ─────    ┌─────┐  └─────┘             * G3   
+#> a                                     ─────   ┌─────┐   └─────┘                      * G4   
+#> l 10.0                         *     ┌─────┐  │─────│                                * G5   
+#> u                  ─────     ─────   └─────┘  └─────┘                                * G6   
+#> e                    │      └─────┘   ─────                                          * G7   
+#>    5.0    ─────   ┌─────┐    ─────                                                   * G8   
+#>          ┌─────┐  └─────┘      *                                                            
+#>          └─────┘   ─────                                                                    
+#>      0    ─────                                                                             
+#>                                                                                             
+#>             G1       G2       G3       G4        G5       G6       G7       G8              
+#>                                           group                                             
+#> 
+
+
+
+

Showcase: Maximum Complexity

+
+

Complex Faceted Boxplot

+
set.seed(42)
+df <- data.frame(
+  treatment = factor(rep(c("Control", "Drug A", "Drug B"), each = 60)),
+  timepoint = factor(rep(rep(c("Baseline", "Week 4", "Week 8"), each = 20), 3)),
+  response = c(
+    rnorm(20, 50, 10), rnorm(20, 52, 10), rnorm(20, 51, 10),  # Control
+    rnorm(20, 50, 10), rnorm(20, 65, 12), rnorm(20, 70, 11),  # Drug A
+    rnorm(20, 50, 10), rnorm(20, 58, 11), rnorm(20, 62, 10)   # Drug B
+  )
+)
+
+p <- ggplot(df, aes(x = timepoint, y = response)) +
+  geom_boxplot(aes(fill = treatment)) +
+  labs(title = "Treatment Response Over Time",
+       subtitle = "Faceted by treatment group",
+       x = "Timepoint", y = "Response") +
+  theme_bw()
+
+ggplotcli(p, width = 100, height = 22, boxplot_style = "ascii")
+#> 
+#>                                    Treatment Response Over Time                                                
+#>                                     Faceted by treatment group                                                 
+#>        ⡏⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⢹            
+#>    100 ⡇                                                                        *                 ⢸            
+#>        ⡇                                                                                          ⢸            
+#>        ⡇                                                                        *                 ⢸            
+#> R 80.0 ⡇                                          ─────                       ──*──               ⢸            
+#> e      ⡇                                         ┌─────┐                        │    ─────        ⢸ treatment  
+#> s      ⡇        ─────                      ───── │     │   *                 ┌─────┐┌─────┐       ⢸ * Control  
+#> p      ⡇       ┌─────┐ ─────  ─────          │   │─────│ ─────         ───── └─────┘│─────│       ⢸ * Drug A   
+#> o 60.0 ⡇       │     │┌─────┐   │         ┌─────┐└─────┘┌─────┐       ┌─────┐   │   └─────┘       ⢸ * Drug B   
+#> n      ⡇       │─────││─────│┌─────┐      │─────│   │   └─────┘       │─────│ ──*──    │          ⢸            
+#> s      ⡇       └─────┘└─────┘│─────│      └─────┘ ─────  ─────        └─────┘        ──*──        ⢸            
+#> e      ⡇          │    ───── └─────┘         │             *           ─────                      ⢸            
+#>   40.0 ⡇          │             │            │                                                    ⢸            
+#>        ⡇          │           ─────        ─────                                                  ⢸            
+#>        ⡇        ─────                                                    *                        ⢸            
+#>   20.0 ⡇                                                                                          ⢸            
+#>        ⣇⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣸            
+#>                     Baseline                      Week 4                      Week 8                           
+#>                                                Timepoint                                                       
+#> 
+
+
+

Multi-Layer Scientific Plot

+
# Simulated experiment data
+set.seed(123)
+x <- seq(0, 10, length.out = 50)
+df <- data.frame(
+  x = rep(x, 3),
+  y = c(
+    2 * x + rnorm(50, 0, 1.5),
+    1.5 * x + 3 + rnorm(50, 0, 1.2),
+    x^1.2 + rnorm(50, 0, 1)
+  ),
+  group = rep(c("Linear", "Offset", "Power"), each = 50)
+)
+
+p <- ggplot(df, aes(x = x, y = y, color = group)) +
+  geom_point(alpha = 0.6) +
+  geom_smooth(method = "loess", se = FALSE) +
+  labs(title = "Multi-Group Regression Analysis",
+       subtitle = "Points with LOESS smoothing",
+       x = "Predictor", y = "Response") +
+  theme_minimal()
+
+suppressMessages(ggplotcli(p, width = 70, height = 18))
+#> 
+#>                   Multi-Group Regression Analysis                               
+#>                     Points with LOESS smoothing                                 
+#>                                                            ⠄    ⠠               
+#>   20.0                                                      ⠂⢀⡐⣤⢰⣾              
+#> R                                                      ⡀⣠⡄⣶⢰⣇⣿⣿⣿⣿⣿              
+#> e 15.0                                         ⢀⢀⠠⡀⣤⣠⣾⣸⣯⣿⣿⣿⣿⣿⣿⡟⣿⢹⠿    group     
+#> s                                          ⠂⡀⡀⣬⢰⣾⣸⣧⣿⣾⣿⣿⣿⣿⡟⣿⠹⠇⠛⢁⠁ ⠈    * Linear  
+#> p                              ⢀   ⡀  ⠐⠐⣀⣠⢠⣦⣿⣷⣿⣿⣿⢿⡟⣿⢻⠿⠸⠃⠋⠡ ⠂⠁         * Offset  
+#> o 10.0                        ⠠  ⡀⣠⢠⣴⢴⡇⣿⣷⣿⣿⡟⣿⡏⡿⢸⠛⠘⠁⡁  ⠈               * Power   
+#> n                         ⡀⣥⡆⣶⢰⣿⢸⡇⣿⣸⣿⣿⡿⣿⡯⠿⠘⠃⠉   ⠐                               
+#> s            ⡀ ⠐  ⢄⣀⢤⡆⣶⣖⣿⢸⡇⣿⣇⣿⣼⣿⢾⡟⡿⡹⠟⠘⠑⠁ ⠈                                      
+#> e  5.0    ⢀⡀⣠⢠⣴⢰⡇⣿⢸⣿⢸⡇⣿⣧⣿⣾⡿⣿⡟⡿⠹⠫⠈ ⠂                                             
+#>           ⣿⡇⣿⢸⣿⣸⣿⣿⢾⣿⢻⡟⠿⠃⠛⠈⠁                                                     
+#>      0    ⣿⡷⣿⠿⢿⠙⠣⠋⡊⠁   ⠈                                                        
+#>           ⠋                                                                     
+#>           0         2.0        4.0        6.0        8.0       10.0             
+#>                                 Predictor                                       
+#> 
+
+
+

Dense Scatter with Facets

+
p <- ggplot(iris, aes(x = Sepal.Length, y = Petal.Length, color = Species)) +
+  geom_point() +
+  facet_wrap(~Species) +
+  labs(title = "Iris Dataset: Sepal vs Petal Length",
+       subtitle = "Faceted by species with color legend") +
+  theme_bw()
+
+ggplotcli(p, width = 80, height = 16)
+#> 
+#>                      Iris Dataset: Sepal vs Petal Length                                      
+#>                      Faceted by species with color legend                                     
+#>               setosa, 1             versicolor, 1           virginica, 1                      
+#> P      ⡏⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⢹ ⡏⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⢹ ⡏⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⢹                
+#> e   6.0⡇                     ⢸ ⡇                     ⢸ ⡇                 ⢀⡄  ⢸                
+#> t      ⡇                     ⢸ ⡇                     ⢸ ⡇          ⡀⣄⠄⡤⡀⠴⠑ ⠂⠁ ⢸  Species       
+#> a      ⡇                     ⢸ ⡇       ⡀⣀⠠⣂⣄⣀⡢⢄      ⢸ ⡇    ⢀   ⠔⠒⠮⠎⠃⠊⠃      ⢸  * setosa      
+#> l   4.0⡇                     ⢸ ⡇     ⡀⠄⠸⣖⠖⠊⠉⠈⠁       ⢸ ⡇                     ⢸  * versicolor  
+#> .      ⡇                     ⢸ ⡇    ⠈⠑               ⢸ ⡇                     ⢸  * virginica   
+#> L   2.0⡇  ⡀⣀⣂⣰⣀⣄⢠            ⢸ ⡇                     ⢸ ⡇                     ⢸                
+#> e      ⡇ ⠈⠉⠊ ⠁ ⠉ ⠁           ⢸ ⡇                     ⢸ ⡇                     ⢸                
+#> n      ⣇⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣸ ⣇⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣸ ⣇⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣸                
+#> g          5.0  6.0   7.0   8.0    5.0  6.0   7.0   8.0    5.0  6.0   7.0   8.0               
+#>                                                                                               
+#>                                      Sepal.Length                                             
+#> 
+
+
+
+

Supported Features Summary

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureStatus
geom_point✓
geom_line, geom_path✓
geom_bar, geom_col, geom_histogram✓
geom_density✓
geom_smooth✓
geom_area✓
geom_segment, geom_hline, geom_vline✓
geom_rect✓
geom_text✓
geom_boxplot✓
Color/fill aesthetics✓
Legends (auto-generated)✓
facet_wrap, facet_grid✓
Titles, subtitles, captions✓
Theme auto-detection✓
Optimized color mapping✓
Multiple canvas types✓
geom_tile (heatmaps)Planned
geom_violinPlanned
+
+ + + + + + + + + + + diff --git a/inst/doc/plotcli_class.R b/inst/doc/plotcli_class.R new file mode 100644 index 0000000..b20822c --- /dev/null +++ b/inst/doc/plotcli_class.R @@ -0,0 +1,98 @@ +## ----setup, include = FALSE--------------------------------------------------- +knitr::opts_chunk$set( + collapse = TRUE, + comment = "#>" +) + +## ----------------------------------------------------------------------------- +library(plotcli) + +plot_width = 80 +plot_height = 40 + +# Create some example data +x <- seq(0, 2 * pi, length.out = 100) +y1 <- sin(x) +y2 <- cos(x) + +data_1 = list( + x = x, + y = y1, + name = "y1 = sin(x)", + color = "blue", + type = "line", + braille = FALSE + ) + +data_2 = list( + x = x, + y = y2, + name = "y2 = cos(x)", + color = "red", + type = "line", + braille = FALSE + ) + +# Create a plotcli object with specified dimensions +plot <- plotcli$new( + plot_width = plot_width, + plot_height = plot_height, + x_label = "X-axis", + y_label = "Y-axis" + ) + +# Add data sets to the plot +plot$add_data(data_1) +plot$add_data(data_2) + +# Print the plot +plot$print_plot() + +## ----------------------------------------------------------------------------- +library(plotcli) + +data(mtcars) + +# Fit a linear model +lm_fit <- lm(wt ~ mpg, data = mtcars) + +# Create a new dataset with the predicted values +predicted_data <- data.frame(mpg = mtcars$mpg, predicted_wt = predict(lm_fit, mtcars)) + +# we use braille characters for the regression line +data_1 = list( + x = predicted_data$mpg, + y = predicted_data$predicted_wt, + name = "Regression Line", + color = "red", + type = "line", + braille = TRUE + ) + +# and ascii characters for the raw data +data_2 = list( + x = mtcars$mpg, + y = mtcars$wt, + name = "Data Points", + color = "blue", + type = "scatter", + braille = FALSE + ) + +# Create a plotcli object +plot_width = 80 +plot_height = 40 +plot_obj <- plotcli$new( + plot_width, + plot_height, + x_label = "Miles per Gallon", + y_label = "Weight" + ) + +# Add raw data and regression line +plot_obj$add_data(data_1) +plot_obj$add_data(data_2) + +# Print the plot +plot_obj$print_plot() + diff --git a/inst/doc/plotcli_class.Rmd b/inst/doc/plotcli_class.Rmd new file mode 100644 index 0000000..e324c3e --- /dev/null +++ b/inst/doc/plotcli_class.Rmd @@ -0,0 +1,121 @@ +--- +title: "Using the plotcli R6 Class" +author: "Claas Heuer" +date: "`r Sys.Date()`" +output: rmarkdown::html_vignette +vignette: > + %\VignetteIndexEntry{Using the plotcli R6 Class} + %\VignetteEngine{knitr::rmarkdown} + %\VignetteEncoding{UTF-8} +--- + +```{r setup, include = FALSE} +knitr::opts_chunk$set( + collapse = TRUE, + comment = "#>" +) +``` + +## Using plotcli R6 class + +# Setting up a scatter plot with two data sets + +```{r} +library(plotcli) + +plot_width = 80 +plot_height = 40 + +# Create some example data +x <- seq(0, 2 * pi, length.out = 100) +y1 <- sin(x) +y2 <- cos(x) + +data_1 = list( + x = x, + y = y1, + name = "y1 = sin(x)", + color = "blue", + type = "line", + braille = FALSE + ) + +data_2 = list( + x = x, + y = y2, + name = "y2 = cos(x)", + color = "red", + type = "line", + braille = FALSE + ) + +# Create a plotcli object with specified dimensions +plot <- plotcli$new( + plot_width = plot_width, + plot_height = plot_height, + x_label = "X-axis", + y_label = "Y-axis" + ) + +# Add data sets to the plot +plot$add_data(data_1) +plot$add_data(data_2) + +# Print the plot +plot$print_plot() +``` + +# Combining Ascii and braille characters + +plotcli can use braille characters for plotting scatter +and line plots, which give a much higher resolution on supported terminals. +Whether to use braille or ascii characters can be specified for each data set. + +```{r} +library(plotcli) + +data(mtcars) + +# Fit a linear model +lm_fit <- lm(wt ~ mpg, data = mtcars) + +# Create a new dataset with the predicted values +predicted_data <- data.frame(mpg = mtcars$mpg, predicted_wt = predict(lm_fit, mtcars)) + +# we use braille characters for the regression line +data_1 = list( + x = predicted_data$mpg, + y = predicted_data$predicted_wt, + name = "Regression Line", + color = "red", + type = "line", + braille = TRUE + ) + +# and ascii characters for the raw data +data_2 = list( + x = mtcars$mpg, + y = mtcars$wt, + name = "Data Points", + color = "blue", + type = "scatter", + braille = FALSE + ) + +# Create a plotcli object +plot_width = 80 +plot_height = 40 +plot_obj <- plotcli$new( + plot_width, + plot_height, + x_label = "Miles per Gallon", + y_label = "Weight" + ) + +# Add raw data and regression line +plot_obj$add_data(data_1) +plot_obj$add_data(data_2) + +# Print the plot +plot_obj$print_plot() +``` \ No newline at end of file diff --git a/inst/doc/plotcli_class.html b/inst/doc/plotcli_class.html new file mode 100644 index 0000000..10793f9 --- /dev/null +++ b/inst/doc/plotcli_class.html @@ -0,0 +1,564 @@ + + + + + + + + + + + + + + + + +Using the plotcli R6 Class + + + + + + + + + + + + + + + + + + + + + + + + + + +

Using the plotcli R6 Class

+

Claas Heuer

+

2026-02-09

+ + + +
+

Using plotcli R6 class

+
+
+

Setting up a scatter plot with two data sets

+
library(plotcli)  
+
+plot_width = 80
+plot_height = 40
+
+# Create some example data
+x <- seq(0, 2 * pi, length.out = 100)
+y1 <- sin(x)
+y2 <- cos(x)
+
+data_1 = list(
+              x = x, 
+              y = y1, 
+              name = "y1 = sin(x)", 
+              color = "blue",
+              type = "line",
+              braille = FALSE
+              )
+
+data_2 = list(
+                x = x, 
+                y = y2, 
+                name = "y2 = cos(x)", 
+                color = "red",
+                type = "line",
+                braille = FALSE
+                )
+
+# Create a plotcli object with specified dimensions
+plot <- plotcli$new(
+                    plot_width = plot_width, 
+                    plot_height = plot_height, 
+                    x_label = "X-axis", 
+                    y_label = "Y-axis"
+                    )
+
+# Add data sets to the plot
+plot$add_data(data_1)
+plot$add_data(data_2)
+
+# Print the plot
+plot$print_plot()
+#> 
+#>                                                                                                         
+#>                 ┌────────────────────────────────────────────────────────────────────────────────┐      
+#>             1.0 │******         **********                                                  *****│      
+#>                 │      *       **         **                                               *     │      
+#>                 │      **     *             *                                             **     │      
+#>                 │        *  **               *                                           *       │      
+#>                 │         * *                 *                                         *        │      
+#>                 │          **                  *                                      **         │      
+#>                 │         * *                   *                                     *          │      
+#>                 │        *   *                   *                                   *           │      
+#>                 │       *     *                  *                                  *            │      
+#>                 │      *      *                   *                                *             │      
+#>             0.5 │      *       *                   *                               *             │      
+#>                 │     *         *                   *                             *              │      
+#>                 │     *         *                    *                            *              │      
+#>                 │    *           *                   *                           *               │      
+#>                 │   *             *                  *                          *                │      
+#>                 │  *              *                   *                        *                 │      
+#>                 │  *               *                   *                       *                 │      
+#>                 │ *                 *                   *                     *                  │      
+#>                 │ *                 *                    *                    *                  │   y1 = sin(x)  
+#>   Y-axis    0.0 │*                   *                   *                   *                  *│   y2 = cos(x)  
+#>                 │                    *                   *                  *                   *│      
+#>                 │                     *                   *                 *                  * │      
+#>                 │                      *                   *               *                   * │      
+#>                 │                       *                   *             *                    * │      
+#>                 │                       *                   *             *                   *  │      
+#>                 │                       *                    *           *                   *   │      
+#>                 │                        *                   *           *                  *    │      
+#>                 │                         *                   *         *                  *     │      
+#>                 │                          *                   *       *                   *     │      
+#>            -0.5 │                           *                   *     *                    *     │      
+#>                 │                           *                    *    *                   *      │      
+#>                 │                            *                   *   *                   *       │      
+#>                 │                             *                   * *                   *        │      
+#>                 │                              *                   *                   *         │      
+#>                 │                               *                 * *                 *          │      
+#>                 │                                *               *   *               **          │      
+#>                 │                                 *             *     *             *            │      
+#>                 │                                  **         **       **         **             │      
+#>                 │                                    *       *           **     ***              │      
+#>            -1.0 │                                     *******             ******                 │      
+#>                 └────────────────────────────────────────────────────────────────────────────────┘      
+#>                                                                                                         
+#>                   0.0                1.6                3.1                 4.7               6.3       
+#>                                                                                                         
+#>                                                      X-axis                                             
+#> 
+
+
+

Combining Ascii and braille characters

+

plotcli can use braille characters for plotting scatter and line +plots, which give a much higher resolution on supported terminals. +Whether to use braille or ascii characters can be specified for each +data set.

+
library(plotcli)  
+
+data(mtcars)
+
+# Fit a linear model
+lm_fit <- lm(wt ~ mpg, data = mtcars)
+
+# Create a new dataset with the predicted values
+predicted_data <- data.frame(mpg = mtcars$mpg, predicted_wt = predict(lm_fit, mtcars))
+
+# we use braille characters for the regression line
+data_1 = list(
+              x = predicted_data$mpg, 
+              y = predicted_data$predicted_wt, 
+              name = "Regression Line", 
+              color = "red",
+              type = "line",
+              braille = TRUE
+              )
+
+# and ascii characters for the raw data
+data_2 = list(
+                x = mtcars$mpg, 
+                y = mtcars$wt, 
+                name = "Data Points", 
+                color = "blue",
+                type = "scatter",
+                braille = FALSE
+                )
+
+# Create a plotcli object
+plot_width = 80
+plot_height = 40
+plot_obj <- plotcli$new(
+                        plot_width, 
+                        plot_height, 
+                        x_label = "Miles per Gallon", 
+                        y_label = "Weight"
+                        )
+
+# Add raw data and regression line
+plot_obj$add_data(data_1)
+plot_obj$add_data(data_2)
+
+# Print the plot
+plot_obj$print_plot()
+#> 
+#>                                                                                                         
+#>                 ┌────────────────────────────────────────────────────────────────────────────────┐      
+#>             5.4 │*              *                                                                │      
+#>                 │*                                                                               │      
+#>                 │                                                                                │      
+#>                 │                                                                                │      
+#>                 │                                                                                │      
+#>                 │                                                                                │      
+#>                 │                                                                                │      
+#>                 │⡀                                                                               │      
+#>                 │⠈⠒⢄                                                                             │      
+#>                 │   ⠑⠦⡀                                                                          │      
+#>             4.4 │     ⠈⠳⣄                                                                        │      
+#>                 │        ⠙⢦⡀                                                                     │      
+#>                 │          ⠉⠳⣄⡀      *                                                           │      
+#>                 │            ⠈⠛⢦⣀                                                                │      
+#>                 │          *    ⠙⠳⣄            *                                                 │      
+#>                 │                *⠈⠛⢦⡀  *                                                        │      
+#>                 │                    ⠙⠲⣄                                                         │      
+#>                 │             *  **    ⠈⠑⢦⡀                                                      │      
+#>                 │                *        **⣄* *                                                 │   Regression Line  
+#>   Weight    3.3 │                           ⠈⠙⢦⣀                                                 │   Data Points  
+#>                 │                              ⠉⠳⣄    *                                          │      
+#>                 │                  *             ⠈⠙⢦⡀      *     *                               │      
+#>                 │                                   ⠉⠲⣄                                          │      
+#>                 │                                     ⠈⠑⢦⡀                                       │      
+#>                 │                                    **  ⠙⠲⣄                                     │      
+#>                 │                                *         ⠈⠑⢦⡀                                  │      
+#>                 │                                    *        ⠈⠲⣄                                │      
+#>                 │                                                ⠑⢦⡀                             │      
+#>                 │                                      *           ⠈⠲⣄                           │      
+#>             2.3 │                                          *          ⠑⢦⡀                        │      
+#>                 │                                                       ⠈⠲⣄                 *    │      
+#>                 │                                                     *    ⠑⢤⡀                   │      
+#>                 │                                                            ⠉⠢⣄                 │      
+#>                 │                                                          *   ⠈⠑⢤⡀              │      
+#>                 │                                                                 ⠉⠢⣄           *│      
+#>                 │                                                                   ⠈⠑⢦⡀         │      
+#>                 │                                                                    * ⠉⠲⣄       │      
+#>                 │                                                                    *   ⠈⠓⢦⡀    │      
+#>                 │                                                                           ⠙⠢⡀  │      
+#>             1.3 │                                                                             ⠈⠒⢄│      
+#>                 └────────────────────────────────────────────────────────────────────────────────┘      
+#>                                                                                                         
+#>                  10.4               16.3               22.1                28.0              33.9       
+#>                                                                                                         
+#>                                                 Miles per Gallon                                        
+#> 
+
+ + + + + + + + + + + diff --git a/inst/doc/plotcli_wrappers.R b/inst/doc/plotcli_wrappers.R new file mode 100644 index 0000000..d391f04 --- /dev/null +++ b/inst/doc/plotcli_wrappers.R @@ -0,0 +1,35 @@ +## ----setup, include = FALSE--------------------------------------------------- +knitr::opts_chunk$set( + collapse = TRUE, + comment = "#>" +) + +## ----------------------------------------------------------------------------- +library(plotcli) +# Generate sample data +sample_data <- rnorm(1000, mean = 5, sd = 2) + +# Create a density plot +plotcli_density(sample_data, color = "blue", braille = TRUE) + +## ----------------------------------------------------------------------------- +# Generate sample data +sample_data <- rnorm(1000, mean = 5, sd = 2) + +# Create a histogram +plotcli_histogram(sample_data, color = "yellow") + +## ----------------------------------------------------------------------------- +# Create a scatter plot +plotcli_scatter(x = iris$`Sepal.Width`, y = iris$`Sepal.Length`, color = "magenta", braille = FALSE) + +## ----------------------------------------------------------------------------- + +# make sin +x <- seq(0, 2*pi, length.out = 50) +y <- sin(x) + +# Create a line plot +plotcli_line(x = x, y = cos(y), color = "green") +plotcli_line(x = x, y = x, color = "magenta", braille = FALSE) + diff --git a/inst/doc/plotcli_wrappers.Rmd b/inst/doc/plotcli_wrappers.Rmd new file mode 100644 index 0000000..d09462b --- /dev/null +++ b/inst/doc/plotcli_wrappers.Rmd @@ -0,0 +1,62 @@ +--- +title: "plotcli Convenience Wrappers" +author: "Claas Heuer" +date: "`r Sys.Date()`" +output: rmarkdown::html_vignette +vignette: > + %\VignetteIndexEntry{plotcli Convenience Wrappers} + %\VignetteEngine{knitr::rmarkdown} + %\VignetteEncoding{UTF-8} +--- + +```{r setup, include = FALSE} +knitr::opts_chunk$set( + collapse = TRUE, + comment = "#>" +) +``` + +## Using `plotcli` convenience wrappers + +# Density plot + +```{r} +library(plotcli) +# Generate sample data +sample_data <- rnorm(1000, mean = 5, sd = 2) + +# Create a density plot +plotcli_density(sample_data, color = "blue", braille = TRUE) +``` + +# Histogram + +```{r} +# Generate sample data +sample_data <- rnorm(1000, mean = 5, sd = 2) + +# Create a histogram +plotcli_histogram(sample_data, color = "yellow") +``` + +# Scatterplot + +```{r} +# Create a scatter plot +plotcli_scatter(x = iris$`Sepal.Width`, y = iris$`Sepal.Length`, color = "magenta", braille = FALSE) +``` + +# Lineplot + +```{r} + +# make sin +x <- seq(0, 2*pi, length.out = 50) +y <- sin(x) + +# Create a line plot +plotcli_line(x = x, y = cos(y), color = "green") +plotcli_line(x = x, y = x, color = "magenta", braille = FALSE) +``` + + diff --git a/inst/doc/plotcli_wrappers.html b/inst/doc/plotcli_wrappers.html new file mode 100644 index 0000000..de28e6e --- /dev/null +++ b/inst/doc/plotcli_wrappers.html @@ -0,0 +1,546 @@ + + + + + + + + + + + + + + + + +plotcli Convenience Wrappers + + + + + + + + + + + + + + + + + + + + + + + + + + +

plotcli Convenience Wrappers

+

Claas Heuer

+

2026-02-09

+ + + +
+

Using plotcli convenience wrappers

+
+
+

Density plot

+
library(plotcli)
+# Generate sample data
+sample_data <- rnorm(1000, mean = 5, sd = 2)
+
+# Create a density plot
+plotcli_density(sample_data, color = "blue", braille = TRUE)
+#> 
+#>                                                                                 
+#>                  ┌────────────────────────────────────────────────────────────┐ 
+#>              0.2 │                          ⢀⠞⠉⠉⢣⡀                            │ 
+#>                  │                         ⢀⡎    ⢣                            │ 
+#>                  │                         ⡜      ⢧                           │ 
+#>                  │                        ⣰⠁      ⠈⡆                          │ 
+#>                  │                       ⢠⠃        ⠹⡀                         │ 
+#>              0.2 │                       ⡎          ⢳⡀                        │ 
+#>                  │                      ⡜            ⢧                        │ 
+#>                  │                     ⡸⠁            ⠈⡆                       │ 
+#>                  │                    ⡜⠁              ⠸⡀                      │ 
+#>   Density    0.1 │                   ⡜                 ⢇                      │ 
+#>                  │                  ⡜                  ⠘⡄                     │ 
+#>                  │                 ⢸⠁                   ⢱                     │ 
+#>                  │                ⢠⠇                    ⠈⢇                    │ 
+#>                  │               ⢀⠎                      ⠈⢆                   │ 
+#>              0.1 │              ⢀⡜                        ⠈⢦⡀                 │ 
+#>                  │             ⢀⠞                           ⠱⡄                │ 
+#>                  │            ⣠⠋                             ⠙⣆               │ 
+#>                  │          ⢀⡜⠁                               ⠈⠳⣄⡀            │ 
+#>                  │        ⣀⡴⠋                                    ⠉⠙⠢⣄         │ 
+#>              0.0 │⣀⣀⣀⣠⠤⠔⠚⠉⠁                                         ⠈⠙⠲⠤⠤⠤⣄⣀⣀⣀│ 
+#>                  └────────────────────────────────────────────────────────────┘ 
+#>                                                                                 
+#>                   -1.9           1.7           5.4            9.1         12.8  
+#>                                                                                 
+#>                                                x                                
+#> 
+
+
+

Histogram

+
# Generate sample data
+sample_data <- rnorm(1000, mean = 5, sd = 2)
+
+# Create a histogram
+plotcli_histogram(sample_data, color = "yellow")
+#> 
+#>                                                                                   
+#>                    ┌────────────────────────────────────────────────────────────┐ 
+#>                209 │                            █                               │ 
+#>                    │                            █                               │ 
+#>                    │                            █   █                           │ 
+#>                    │                            █   █                           │ 
+#>                    │                            █   █    █                      │ 
+#>                157 │                       █    █   █    █                      │ 
+#>                    │                       █    █   █    █                      │ 
+#>                    │                       █    █   █    █                      │ 
+#>                    │                       █    █   █    █    █                 │ 
+#>   Frequency    104 │                       █    █   █    █    █                 │ 
+#>                    │                       █    █   █    █    █                 │ 
+#>                    │                  █    █    █   █    █    █                 │ 
+#>                    │                  █    █    █   █    █    █                 │ 
+#>                    │                  █    █    █   █    █    █                 │ 
+#>               52.2 │                  █    █    █   █    █    █                 │ 
+#>                    │              █   █    █    █   █    █    █                 │ 
+#>                    │              █   █    █    █   █    █    █   █             │ 
+#>                    │         █    █   █    █    █   █    █    █   █             │ 
+#>                    │         █    █   █    █    █   █    █    █   █    █        │ 
+#>                0.0 │█    █   █    █   █    █    █   █    █    █   █    █   █   █│ 
+#>                    └────────────────────────────────────────────────────────────┘ 
+#>                                                                                   
+#>                     -1.5           1.8           5.0            8.2         11.5  
+#>                                                                                   
+#>                                                  x                                
+#> 
+
+
+

Scatterplot

+
# Create a scatter plot
+plotcli_scatter(x = iris$`Sepal.Width`, y = iris$`Sepal.Length`, color = "magenta", braille = FALSE)
+#> 
+#>                                                                           
+#>            ┌────────────────────────────────────────────────────────────┐ 
+#>        7.9 │               *    *    *                   *              │ 
+#>            │                         *                                  │ 
+#>            │                    * *                                     │ 
+#>            │                         *    *         *                   │ 
+#>            │                              *                             │ 
+#>        7.0 │                    *    * *  *                             │ 
+#>            │            *         *  * *    *                           │ 
+#>            │                 *  * *  * *  *                             │ 
+#>            │     * *    *    *  * *         *  *                        │ 
+#>   y    6.1 │               *    * *  *                                  │ 
+#>            │     *           *    *  *    *    *                        │ 
+#>            │            *  * *  * *  *                   *    *        *│ 
+#>            │       *  * *  * *  * *  *           *                 *    │ 
+#>            │                         *         *      *    *            │ 
+#>        5.2 │                 *                 * *              *       │ 
+#>            │*      *    *            *    * *  * *  * *  *              │ 
+#>            │          * *            * *       *    *                   │ 
+#>            │                           *  *    *    *                   │ 
+#>            │       *              *  *    *                             │ 
+#>        4.3 │                         *                                  │ 
+#>            └────────────────────────────────────────────────────────────┘ 
+#>                                                                           
+#>              2.0           2.6           3.2            3.8          4.4  
+#>                                                                           
+#>                                          x                                
+#> 
+
+
+

Lineplot

+

+# make sin 
+x <- seq(0, 2*pi, length.out = 50)
+y <- sin(x)
+
+# Create a line plot
+plotcli_line(x = x, y = cos(y), color = "green")
+#> 
+#>                                                                           
+#>            ┌────────────────────────────────────────────────────────────┐ 
+#>        1.0 │***                         *****                         **│ 
+#>            │   *                       *     *                       *  │ 
+#>            │    *                     *      *                      *   │ 
+#>            │    *                     *       *                    *    │ 
+#>            │     *                   *         *                   *    │ 
+#>        0.9 │     *                  *           *                  *    │ 
+#>            │      *                 *           *                 *     │ 
+#>            │      *                *             *                *     │ 
+#>            │      *                *             *               *      │ 
+#>   y    0.8 │       *              *              *               *      │ 
+#>            │        *             *               *             *       │ 
+#>            │        *             *               *             *       │ 
+#>            │         *           *                 *           *        │ 
+#>            │         *           *                 *          *         │ 
+#>        0.7 │          *         *                  *          *         │ 
+#>            │          *         *                   *        *          │ 
+#>            │           *       *                     *       *          │ 
+#>            │           *      *                       *     *           │ 
+#>            │            *    *                         *    *           │ 
+#>        0.5 │             ****                           ****            │ 
+#>            └────────────────────────────────────────────────────────────┘ 
+#>                                                                           
+#>              0.0           1.6           3.1            4.7          6.3  
+#>                                                                           
+#>                                          x                                
+#> 
+plotcli_line(x = x, y = x, color = "magenta", braille = FALSE)
+#> 
+#>                                                                           
+#>            ┌────────────────────────────────────────────────────────────┐ 
+#>        6.3 │                                                        ****│ 
+#>            │                                                     ***    │ 
+#>            │                                                  ***       │ 
+#>            │                                               ***          │ 
+#>            │                                            ***             │ 
+#>        4.7 │                                          **                │ 
+#>            │                                      ****                  │ 
+#>            │                                    **                      │ 
+#>            │                                ****                        │ 
+#>   y    3.1 │                             ***                            │ 
+#>            │                          ***                               │ 
+#>            │                       ***                                  │ 
+#>            │                    ***                                     │ 
+#>            │                 ***                                        │ 
+#>        1.6 │               **                                           │ 
+#>            │           ****                                             │ 
+#>            │         **                                                 │ 
+#>            │     ****                                                   │ 
+#>            │  ***                                                       │ 
+#>        0.0 │**                                                          │ 
+#>            └────────────────────────────────────────────────────────────┘ 
+#>                                                                           
+#>              0.0           1.6           3.1            4.7          6.3  
+#>                                                                           
+#>                                          x                                
+#> 
+
+ + + + + + + + + + + diff --git a/man/AsciiCanvas.Rd b/man/AsciiCanvas.Rd new file mode 100644 index 0000000..ab8c989 --- /dev/null +++ b/man/AsciiCanvas.Rd @@ -0,0 +1,116 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/canvas.r +\name{AsciiCanvas} +\alias{AsciiCanvas} +\title{ASCII Canvas Class} +\description{ +ASCII Canvas Class + +ASCII Canvas Class +} +\details{ +Simple canvas using basic ASCII characters. +Resolution: 1x1 (one pixel per character) +} +\section{Super class}{ +\code{\link[plotcli:Canvas]{plotcli::Canvas}} -> \code{AsciiCanvas} +} +\section{Public fields}{ +\if{html}{\out{
}} +\describe{ +\item{\code{point_char}}{Character used for points} +} +\if{html}{\out{
}} +} +\section{Methods}{ +\subsection{Public methods}{ +\itemize{ +\item \href{#method-AsciiCanvas-new}{\code{AsciiCanvas$new()}} +\item \href{#method-AsciiCanvas-set_pixel}{\code{AsciiCanvas$set_pixel()}} +\item \href{#method-AsciiCanvas-clone}{\code{AsciiCanvas$clone()}} +} +} +\if{html}{\out{ +
Inherited methods + +
+}} +\if{html}{\out{
}} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-AsciiCanvas-new}{}}} +\subsection{Method \code{new()}}{ +Initialize ASCII canvas +\subsection{Usage}{ +\if{html}{\out{
}}\preformatted{AsciiCanvas$new(width, height, point_char = "*")}\if{html}{\out{
}} +} + +\subsection{Arguments}{ +\if{html}{\out{
}} +\describe{ +\item{\code{width}}{Character width} + +\item{\code{height}}{Character height} + +\item{\code{point_char}}{Character to use for points (default "*")} +} +\if{html}{\out{
}} +} +} +\if{html}{\out{
}} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-AsciiCanvas-set_pixel}{}}} +\subsection{Method \code{set_pixel()}}{ +Set a pixel +\subsection{Usage}{ +\if{html}{\out{
}}\preformatted{AsciiCanvas$set_pixel(x, y, color = NULL)}\if{html}{\out{
}} +} + +\subsection{Arguments}{ +\if{html}{\out{
}} +\describe{ +\item{\code{x}}{X coordinate (1-based)} + +\item{\code{y}}{Y coordinate (1-based, 1 = top)} + +\item{\code{color}}{Optional color name} +} +\if{html}{\out{
}} +} +} +\if{html}{\out{
}} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-AsciiCanvas-clone}{}}} +\subsection{Method \code{clone()}}{ +The objects of this class are cloneable with this method. +\subsection{Usage}{ +\if{html}{\out{
}}\preformatted{AsciiCanvas$clone(deep = FALSE)}\if{html}{\out{
}} +} + +\subsection{Arguments}{ +\if{html}{\out{
}} +\describe{ +\item{\code{deep}}{Whether to make a deep clone.} +} +\if{html}{\out{
}} +} +} +} diff --git a/man/BlockCanvas.Rd b/man/BlockCanvas.Rd new file mode 100644 index 0000000..d6ba576 --- /dev/null +++ b/man/BlockCanvas.Rd @@ -0,0 +1,132 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/canvas.r +\name{BlockCanvas} +\alias{BlockCanvas} +\title{Block Canvas Class} +\description{ +Block Canvas Class + +Block Canvas Class +} +\details{ +Canvas using Unicode block elements for 2x vertical resolution. +Uses half-block characters: upper half (U+2580), lower half (U+2584), full block (U+2588). + +Resolution: 1x2 (1 horizontal, 2 vertical pixels per character) +} +\section{Super class}{ +\code{\link[plotcli:Canvas]{plotcli::Canvas}} -> \code{BlockCanvas} +} +\section{Public fields}{ +\if{html}{\out{
}} +\describe{ +\item{\code{upper_block}}{Upper half block character} + +\item{\code{lower_block}}{Lower half block character} + +\item{\code{full_block}}{Full block character} + +\item{\code{pixel_state}}{Matrix tracking which half-pixels are set (0=none, 1=upper, 2=lower, 3=both)} +} +\if{html}{\out{
}} +} +\section{Methods}{ +\subsection{Public methods}{ +\itemize{ +\item \href{#method-BlockCanvas-new}{\code{BlockCanvas$new()}} +\item \href{#method-BlockCanvas-set_pixel}{\code{BlockCanvas$set_pixel()}} +\item \href{#method-BlockCanvas-clear}{\code{BlockCanvas$clear()}} +\item \href{#method-BlockCanvas-clone}{\code{BlockCanvas$clone()}} +} +} +\if{html}{\out{ +
Inherited methods + +
+}} +\if{html}{\out{
}} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-BlockCanvas-new}{}}} +\subsection{Method \code{new()}}{ +Initialize Block canvas +\subsection{Usage}{ +\if{html}{\out{
}}\preformatted{BlockCanvas$new(width, height)}\if{html}{\out{
}} +} + +\subsection{Arguments}{ +\if{html}{\out{
}} +\describe{ +\item{\code{width}}{Character width} + +\item{\code{height}}{Character height} +} +\if{html}{\out{
}} +} +} +\if{html}{\out{
}} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-BlockCanvas-set_pixel}{}}} +\subsection{Method \code{set_pixel()}}{ +Set a pixel in Block space +\subsection{Usage}{ +\if{html}{\out{
}}\preformatted{BlockCanvas$set_pixel(x, y, color = NULL)}\if{html}{\out{
}} +} + +\subsection{Arguments}{ +\if{html}{\out{
}} +\describe{ +\item{\code{x}}{X coordinate (1-based, in pixel space: 1 to width)} + +\item{\code{y}}{Y coordinate (1-based, in pixel space: 1 to height*2, 1 = top)} + +\item{\code{color}}{Optional color name} +} +\if{html}{\out{
}} +} +} +\if{html}{\out{
}} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-BlockCanvas-clear}{}}} +\subsection{Method \code{clear()}}{ +Clear the canvas +\subsection{Usage}{ +\if{html}{\out{
}}\preformatted{BlockCanvas$clear()}\if{html}{\out{
}} +} + +} +\if{html}{\out{
}} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-BlockCanvas-clone}{}}} +\subsection{Method \code{clone()}}{ +The objects of this class are cloneable with this method. +\subsection{Usage}{ +\if{html}{\out{
}}\preformatted{BlockCanvas$clone(deep = FALSE)}\if{html}{\out{
}} +} + +\subsection{Arguments}{ +\if{html}{\out{
}} +\describe{ +\item{\code{deep}}{Whether to make a deep clone.} +} +\if{html}{\out{
}} +} +} +} diff --git a/man/BrailleCanvas.Rd b/man/BrailleCanvas.Rd new file mode 100644 index 0000000..2446031 --- /dev/null +++ b/man/BrailleCanvas.Rd @@ -0,0 +1,146 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/canvas.r +\name{BrailleCanvas} +\alias{BrailleCanvas} +\title{Braille Canvas Class} +\description{ +Braille Canvas Class + +Braille Canvas Class +} +\details{ +High-resolution canvas using Unicode Braille patterns. +Resolution: 2x4 (2 horizontal, 4 vertical dots per character = 8x resolution) + +Braille dot layout (dot numbers and bit values): +\preformatted{ + Col 0 Col 1 Bit values +Row 0: 1 4 0x01 0x08 +Row 1: 2 5 0x02 0x10 +Row 2: 3 6 0x04 0x20 +Row 3: 7 8 0x40 0x80 +} +} +\section{Super class}{ +\code{\link[plotcli:Canvas]{plotcli::Canvas}} -> \code{BrailleCanvas} +} +\section{Public fields}{ +\if{html}{\out{
}} +\describe{ +\item{\code{braille_base}}{Unicode code point for empty Braille character} +} +\if{html}{\out{
}} +} +\section{Methods}{ +\subsection{Public methods}{ +\itemize{ +\item \href{#method-BrailleCanvas-new}{\code{BrailleCanvas$new()}} +\item \href{#method-BrailleCanvas-get_dot_bit}{\code{BrailleCanvas$get_dot_bit()}} +\item \href{#method-BrailleCanvas-set_pixel}{\code{BrailleCanvas$set_pixel()}} +\item \href{#method-BrailleCanvas-clone}{\code{BrailleCanvas$clone()}} +} +} +\if{html}{\out{ +
Inherited methods + +
+}} +\if{html}{\out{
}} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-BrailleCanvas-new}{}}} +\subsection{Method \code{new()}}{ +Initialize Braille canvas +\subsection{Usage}{ +\if{html}{\out{
}}\preformatted{BrailleCanvas$new(width, height)}\if{html}{\out{
}} +} + +\subsection{Arguments}{ +\if{html}{\out{
}} +\describe{ +\item{\code{width}}{Character width} + +\item{\code{height}}{Character height} +} +\if{html}{\out{
}} +} +} +\if{html}{\out{
}} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-BrailleCanvas-get_dot_bit}{}}} +\subsection{Method \code{get_dot_bit()}}{ +Get the bit value for a dot position +\subsection{Usage}{ +\if{html}{\out{
}}\preformatted{BrailleCanvas$get_dot_bit(dot_row, dot_col)}\if{html}{\out{
}} +} + +\subsection{Arguments}{ +\if{html}{\out{
}} +\describe{ +\item{\code{dot_row}}{Row within Braille cell (0-3)} + +\item{\code{dot_col}}{Column within Braille cell (0-1)} +} +\if{html}{\out{
}} +} +\subsection{Returns}{ +Bit value +} +} +\if{html}{\out{
}} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-BrailleCanvas-set_pixel}{}}} +\subsection{Method \code{set_pixel()}}{ +Set a pixel in Braille space +\subsection{Usage}{ +\if{html}{\out{
}}\preformatted{BrailleCanvas$set_pixel(x, y, color = NULL)}\if{html}{\out{
}} +} + +\subsection{Arguments}{ +\if{html}{\out{
}} +\describe{ +\item{\code{x}}{X coordinate (1-based, in pixel space: 1 to width*2)} + +\item{\code{y}}{Y coordinate (1-based, in pixel space: 1 to height*4, 1 = top)} + +\item{\code{color}}{Optional color name} +} +\if{html}{\out{
}} +} +} +\if{html}{\out{
}} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-BrailleCanvas-clone}{}}} +\subsection{Method \code{clone()}}{ +The objects of this class are cloneable with this method. +\subsection{Usage}{ +\if{html}{\out{
}}\preformatted{BrailleCanvas$clone(deep = FALSE)}\if{html}{\out{
}} +} + +\subsection{Arguments}{ +\if{html}{\out{
}} +\describe{ +\item{\code{deep}}{Whether to make a deep clone.} +} +\if{html}{\out{
}} +} +} +} diff --git a/man/Canvas.Rd b/man/Canvas.Rd new file mode 100644 index 0000000..3b1eb6f --- /dev/null +++ b/man/Canvas.Rd @@ -0,0 +1,492 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/canvas.r +\name{Canvas} +\alias{Canvas} +\title{Canvas Classes for Terminal Plotting} +\description{ +Abstract canvas system that provides different rendering backends: +- AsciiCanvas: Basic ASCII characters (*, -, |, +) +- BrailleCanvas: Unicode Braille patterns (2x4 dots per cell = 8x resolution) +- BlockCanvas: Unicode block elements (half-blocks for 2x vertical resolution) +} +\details{ +Abstract base class for all canvas types. Provides the interface +that all canvas implementations must follow. +} +\section{Public fields}{ +\if{html}{\out{
}} +\describe{ +\item{\code{width}}{Character width of the canvas} + +\item{\code{height}}{Character height of the canvas} + +\item{\code{pixel_width}}{Pixel width (may be higher than char width for Braille/Block)} + +\item{\code{pixel_height}}{Pixel height (may be higher than char height for Braille/Block)} + +\item{\code{matrix}}{Character matrix for rendering} + +\item{\code{color_matrix}}{Parallel matrix tracking colors per cell} + +\item{\code{x_mult}}{Horizontal multiplier (pixels per character)} + +\item{\code{y_mult}}{Vertical multiplier (pixels per character)} +} +\if{html}{\out{
}} +} +\section{Methods}{ +\subsection{Public methods}{ +\itemize{ +\item \href{#method-Canvas-new}{\code{Canvas$new()}} +\item \href{#method-Canvas-set_pixel}{\code{Canvas$set_pixel()}} +\item \href{#method-Canvas-draw_line}{\code{Canvas$draw_line()}} +\item \href{#method-Canvas-draw_polyline}{\code{Canvas$draw_polyline()}} +\item \href{#method-Canvas-draw_points}{\code{Canvas$draw_points()}} +\item \href{#method-Canvas-fill_rect}{\code{Canvas$fill_rect()}} +\item \href{#method-Canvas-fill_bar}{\code{Canvas$fill_bar()}} +\item \href{#method-Canvas-draw_text}{\code{Canvas$draw_text()}} +\item \href{#method-Canvas-apply_colors}{\code{Canvas$apply_colors()}} +\item \href{#method-Canvas-render}{\code{Canvas$render()}} +\item \href{#method-Canvas-print}{\code{Canvas$print()}} +\item \href{#method-Canvas-clear}{\code{Canvas$clear()}} +\item \href{#method-Canvas-draw_rect}{\code{Canvas$draw_rect()}} +\item \href{#method-Canvas-fill_area}{\code{Canvas$fill_area()}} +\item \href{#method-Canvas-draw_segment}{\code{Canvas$draw_segment()}} +\item \href{#method-Canvas-draw_hline}{\code{Canvas$draw_hline()}} +\item \href{#method-Canvas-draw_vline}{\code{Canvas$draw_vline()}} +\item \href{#method-Canvas-draw_circle}{\code{Canvas$draw_circle()}} +\item \href{#method-Canvas-fill_circle}{\code{Canvas$fill_circle()}} +\item \href{#method-Canvas-draw_polygon}{\code{Canvas$draw_polygon()}} +\item \href{#method-Canvas-clone}{\code{Canvas$clone()}} +} +} +\if{html}{\out{
}} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-Canvas-new}{}}} +\subsection{Method \code{new()}}{ +Initialize the canvas +\subsection{Usage}{ +\if{html}{\out{
}}\preformatted{Canvas$new(width, height)}\if{html}{\out{
}} +} + +\subsection{Arguments}{ +\if{html}{\out{
}} +\describe{ +\item{\code{width}}{Character width} + +\item{\code{height}}{Character height} +} +\if{html}{\out{
}} +} +} +\if{html}{\out{
}} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-Canvas-set_pixel}{}}} +\subsection{Method \code{set_pixel()}}{ +Set a pixel at the given coordinates +\subsection{Usage}{ +\if{html}{\out{
}}\preformatted{Canvas$set_pixel(x, y, color = NULL)}\if{html}{\out{
}} +} + +\subsection{Arguments}{ +\if{html}{\out{
}} +\describe{ +\item{\code{x}}{X coordinate (1-based, in pixel space)} + +\item{\code{y}}{Y coordinate (1-based, in pixel space, 1 = top)} + +\item{\code{color}}{Optional color name} +} +\if{html}{\out{
}} +} +} +\if{html}{\out{
}} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-Canvas-draw_line}{}}} +\subsection{Method \code{draw_line()}}{ +Draw a line between two points +\subsection{Usage}{ +\if{html}{\out{
}}\preformatted{Canvas$draw_line(x0, y0, x1, y1, color = NULL)}\if{html}{\out{
}} +} + +\subsection{Arguments}{ +\if{html}{\out{
}} +\describe{ +\item{\code{x0}}{Start X coordinate} + +\item{\code{y0}}{Start Y coordinate} + +\item{\code{x1}}{End X coordinate} + +\item{\code{y1}}{End Y coordinate} + +\item{\code{color}}{Optional color name} +} +\if{html}{\out{
}} +} +} +\if{html}{\out{
}} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-Canvas-draw_polyline}{}}} +\subsection{Method \code{draw_polyline()}}{ +Draw multiple connected line segments +\subsection{Usage}{ +\if{html}{\out{
}}\preformatted{Canvas$draw_polyline(xs, ys, color = NULL)}\if{html}{\out{
}} +} + +\subsection{Arguments}{ +\if{html}{\out{
}} +\describe{ +\item{\code{xs}}{Vector of X coordinates} + +\item{\code{ys}}{Vector of Y coordinates} + +\item{\code{color}}{Optional color name} +} +\if{html}{\out{
}} +} +} +\if{html}{\out{
}} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-Canvas-draw_points}{}}} +\subsection{Method \code{draw_points()}}{ +Draw points (scatter) +\subsection{Usage}{ +\if{html}{\out{
}}\preformatted{Canvas$draw_points(xs, ys, color = NULL)}\if{html}{\out{
}} +} + +\subsection{Arguments}{ +\if{html}{\out{
}} +\describe{ +\item{\code{xs}}{Vector of X coordinates} + +\item{\code{ys}}{Vector of Y coordinates} + +\item{\code{color}}{Optional color name} +} +\if{html}{\out{
}} +} +} +\if{html}{\out{
}} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-Canvas-fill_rect}{}}} +\subsection{Method \code{fill_rect()}}{ +Fill a rectangle +\subsection{Usage}{ +\if{html}{\out{
}}\preformatted{Canvas$fill_rect(x0, y0, x1, y1, color = NULL)}\if{html}{\out{
}} +} + +\subsection{Arguments}{ +\if{html}{\out{
}} +\describe{ +\item{\code{x0}}{Left X coordinate} + +\item{\code{y0}}{Top Y coordinate} + +\item{\code{x1}}{Right X coordinate} + +\item{\code{y1}}{Bottom Y coordinate} + +\item{\code{color}}{Optional color name} +} +\if{html}{\out{
}} +} +} +\if{html}{\out{
}} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-Canvas-fill_bar}{}}} +\subsection{Method \code{fill_bar()}}{ +Fill a vertical bar from bottom up to a height +\subsection{Usage}{ +\if{html}{\out{
}}\preformatted{Canvas$fill_bar(x, height, bar_width = 2, color = NULL)}\if{html}{\out{
}} +} + +\subsection{Arguments}{ +\if{html}{\out{
}} +\describe{ +\item{\code{x}}{X coordinate (center of bar in pixel space)} + +\item{\code{height}}{Height in pixels from bottom} + +\item{\code{bar_width}}{Width of bar in pixels (default 2)} + +\item{\code{color}}{Optional color name} +} +\if{html}{\out{
}} +} +} +\if{html}{\out{
}} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-Canvas-draw_text}{}}} +\subsection{Method \code{draw_text()}}{ +Place text at a position +\subsection{Usage}{ +\if{html}{\out{
}}\preformatted{Canvas$draw_text(x, y, text, color = NULL)}\if{html}{\out{
}} +} + +\subsection{Arguments}{ +\if{html}{\out{
}} +\describe{ +\item{\code{x}}{X coordinate (character position)} + +\item{\code{y}}{Y coordinate (character position)} + +\item{\code{text}}{Text string to place} + +\item{\code{color}}{Optional color name} +} +\if{html}{\out{
}} +} +} +\if{html}{\out{
}} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-Canvas-apply_colors}{}}} +\subsection{Method \code{apply_colors()}}{ +Apply colors to the matrix +\subsection{Usage}{ +\if{html}{\out{
}}\preformatted{Canvas$apply_colors()}\if{html}{\out{
}} +} + +\subsection{Returns}{ +Matrix with ANSI color codes applied +} +} +\if{html}{\out{
}} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-Canvas-render}{}}} +\subsection{Method \code{render()}}{ +Get the rendered matrix (with colors) +\subsection{Usage}{ +\if{html}{\out{
}}\preformatted{Canvas$render()}\if{html}{\out{
}} +} + +\subsection{Returns}{ +Character matrix +} +} +\if{html}{\out{
}} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-Canvas-print}{}}} +\subsection{Method \code{print()}}{ +Print the canvas to console +\subsection{Usage}{ +\if{html}{\out{
}}\preformatted{Canvas$print()}\if{html}{\out{
}} +} + +} +\if{html}{\out{
}} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-Canvas-clear}{}}} +\subsection{Method \code{clear()}}{ +Clear the canvas +\subsection{Usage}{ +\if{html}{\out{
}}\preformatted{Canvas$clear()}\if{html}{\out{
}} +} + +} +\if{html}{\out{
}} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-Canvas-draw_rect}{}}} +\subsection{Method \code{draw_rect()}}{ +Draw a rectangle outline +\subsection{Usage}{ +\if{html}{\out{
}}\preformatted{Canvas$draw_rect(x0, y0, x1, y1, color = NULL)}\if{html}{\out{
}} +} + +\subsection{Arguments}{ +\if{html}{\out{
}} +\describe{ +\item{\code{x0}}{Left X coordinate (pixel space)} + +\item{\code{y0}}{Top Y coordinate (pixel space)} + +\item{\code{x1}}{Right X coordinate (pixel space)} + +\item{\code{y1}}{Bottom Y coordinate (pixel space)} + +\item{\code{color}}{Optional color name} +} +\if{html}{\out{
}} +} +} +\if{html}{\out{
}} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-Canvas-fill_area}{}}} +\subsection{Method \code{fill_area()}}{ +Fill an area between a polyline and the bottom +\subsection{Usage}{ +\if{html}{\out{
}}\preformatted{Canvas$fill_area(xs, ys, color = NULL)}\if{html}{\out{
}} +} + +\subsection{Arguments}{ +\if{html}{\out{
}} +\describe{ +\item{\code{xs}}{Vector of X coordinates} + +\item{\code{ys}}{Vector of Y coordinates} + +\item{\code{color}}{Optional color name} +} +\if{html}{\out{
}} +} +} +\if{html}{\out{
}} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-Canvas-draw_segment}{}}} +\subsection{Method \code{draw_segment()}}{ +Draw a segment (line with optional arrowhead) +\subsection{Usage}{ +\if{html}{\out{
}}\preformatted{Canvas$draw_segment(x0, y0, x1, y1, arrow_end = FALSE, color = NULL)}\if{html}{\out{
}} +} + +\subsection{Arguments}{ +\if{html}{\out{
}} +\describe{ +\item{\code{x0}}{Start X coordinate} + +\item{\code{y0}}{Start Y coordinate} + +\item{\code{x1}}{End X coordinate} + +\item{\code{y1}}{End Y coordinate} + +\item{\code{arrow_end}}{Add arrowhead at end (default FALSE)} + +\item{\code{color}}{Optional color name} +} +\if{html}{\out{
}} +} +} +\if{html}{\out{
}} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-Canvas-draw_hline}{}}} +\subsection{Method \code{draw_hline()}}{ +Draw a horizontal line +\subsection{Usage}{ +\if{html}{\out{
}}\preformatted{Canvas$draw_hline(y, x0 = 1, x1 = NULL, color = NULL)}\if{html}{\out{
}} +} + +\subsection{Arguments}{ +\if{html}{\out{
}} +\describe{ +\item{\code{y}}{Y coordinate} + +\item{\code{x0}}{Start X (default 1)} + +\item{\code{x1}}{End X (default pixel_width)} + +\item{\code{color}}{Optional color name} +} +\if{html}{\out{
}} +} +} +\if{html}{\out{
}} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-Canvas-draw_vline}{}}} +\subsection{Method \code{draw_vline()}}{ +Draw a vertical line +\subsection{Usage}{ +\if{html}{\out{
}}\preformatted{Canvas$draw_vline(x, y0 = 1, y1 = NULL, color = NULL)}\if{html}{\out{
}} +} + +\subsection{Arguments}{ +\if{html}{\out{
}} +\describe{ +\item{\code{x}}{X coordinate} + +\item{\code{y0}}{Start Y (default 1)} + +\item{\code{y1}}{End Y (default pixel_height)} + +\item{\code{color}}{Optional color name} +} +\if{html}{\out{
}} +} +} +\if{html}{\out{
}} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-Canvas-draw_circle}{}}} +\subsection{Method \code{draw_circle()}}{ +Draw a circle outline +\subsection{Usage}{ +\if{html}{\out{
}}\preformatted{Canvas$draw_circle(cx, cy, r, color = NULL)}\if{html}{\out{
}} +} + +\subsection{Arguments}{ +\if{html}{\out{
}} +\describe{ +\item{\code{cx}}{Center X coordinate} + +\item{\code{cy}}{Center Y coordinate} + +\item{\code{r}}{Radius in pixels} + +\item{\code{color}}{Optional color name} +} +\if{html}{\out{
}} +} +} +\if{html}{\out{
}} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-Canvas-fill_circle}{}}} +\subsection{Method \code{fill_circle()}}{ +Fill a circle +\subsection{Usage}{ +\if{html}{\out{
}}\preformatted{Canvas$fill_circle(cx, cy, r, color = NULL)}\if{html}{\out{
}} +} + +\subsection{Arguments}{ +\if{html}{\out{
}} +\describe{ +\item{\code{cx}}{Center X coordinate} + +\item{\code{cy}}{Center Y coordinate} + +\item{\code{r}}{Radius in pixels} + +\item{\code{color}}{Optional color name} +} +\if{html}{\out{
}} +} +} +\if{html}{\out{
}} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-Canvas-draw_polygon}{}}} +\subsection{Method \code{draw_polygon()}}{ +Draw a polygon outline +\subsection{Usage}{ +\if{html}{\out{
}}\preformatted{Canvas$draw_polygon(xs, ys, closed = TRUE, color = NULL)}\if{html}{\out{
}} +} + +\subsection{Arguments}{ +\if{html}{\out{
}} +\describe{ +\item{\code{xs}}{Vector of X coordinates} + +\item{\code{ys}}{Vector of Y coordinates} + +\item{\code{closed}}{Whether to close the polygon (default TRUE)} + +\item{\code{color}}{Optional color name} +} +\if{html}{\out{
}} +} +} +\if{html}{\out{
}} +\if{html}{\out{}} +\if{latex}{\out{\hypertarget{method-Canvas-clone}{}}} +\subsection{Method \code{clone()}}{ +The objects of this class are cloneable with this method. +\subsection{Usage}{ +\if{html}{\out{
}}\preformatted{Canvas$clone(deep = FALSE)}\if{html}{\out{
}} +} + +\subsection{Arguments}{ +\if{html}{\out{
}} +\describe{ +\item{\code{deep}}{Whether to make a deep clone.} +} +\if{html}{\out{
}} +} +} +} diff --git a/man/GeomRegistry.Rd b/man/GeomRegistry.Rd new file mode 100644 index 0000000..cec0015 --- /dev/null +++ b/man/GeomRegistry.Rd @@ -0,0 +1,9 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/geom_registry.r +\name{GeomRegistry} +\alias{GeomRegistry} +\title{Geom Registry and Dispatch System} +\description{ +This module provides a registry for geom rendering functions and +a dispatch system for converting ggplot2 geoms to terminal plots. +} diff --git a/man/add_legend_to_output.Rd b/man/add_legend_to_output.Rd new file mode 100644 index 0000000..ccda965 --- /dev/null +++ b/man/add_legend_to_output.Rd @@ -0,0 +1,12 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/ggplotcli_helpers.r +\name{add_legend_to_output} +\alias{add_legend_to_output} +\title{Add Legend to Output Matrix} +\usage{ +add_legend_to_output(output, legend_info, position, top_margin, plot_height) +} +\description{ +Add Legend to Output Matrix +} +\keyword{internal} diff --git a/man/braille_dot_bit.Rd b/man/braille_dot_bit.Rd new file mode 100644 index 0000000..89ad484 --- /dev/null +++ b/man/braille_dot_bit.Rd @@ -0,0 +1,29 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/helper_functions.r +\name{braille_dot_bit} +\alias{braille_dot_bit} +\title{Get Braille dot bit value} +\usage{ +braille_dot_bit(dot_row, dot_col) +} +\arguments{ +\item{dot_row}{Row within the Braille cell (0-3, top to bottom)} + +\item{dot_col}{Column within the Braille cell (0-1, left to right)} +} +\value{ +The bit value for that dot position +} +\description{ +Returns the bit value for a specific dot position in a Braille cell. +Braille cells have a 2x4 dot matrix with the following bit values: +} +\details{ +\preformatted{ + Col 0 Col 1 +Row 0: 0x01 0x08 +Row 1: 0x02 0x10 +Row 2: 0x04 0x20 +Row 3: 0x40 0x80 +} +} diff --git a/man/braille_set_dot.Rd b/man/braille_set_dot.Rd new file mode 100644 index 0000000..65c1b1a --- /dev/null +++ b/man/braille_set_dot.Rd @@ -0,0 +1,21 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/helper_functions.r +\name{braille_set_dot} +\alias{braille_set_dot} +\title{Set a dot in a Braille character} +\usage{ +braille_set_dot(current_char, dot_row, dot_col) +} +\arguments{ +\item{current_char}{The current character (can be space or existing Braille)} + +\item{dot_row}{Row within the Braille cell (0-3)} + +\item{dot_col}{Column within the Braille cell (0-1)} +} +\value{ +The updated Braille character +} +\description{ +Set a dot in a Braille character +} diff --git a/man/build_plot_output.Rd b/man/build_plot_output.Rd new file mode 100644 index 0000000..bbd8118 --- /dev/null +++ b/man/build_plot_output.Rd @@ -0,0 +1,28 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/ggplotcli_helpers.r +\name{build_plot_output} +\alias{build_plot_output} +\title{Build Plot Output with Axes and Title (legacy)} +\usage{ +build_plot_output(canvas, scales, width, height, show_axes, title) +} +\arguments{ +\item{canvas}{The rendered canvas} + +\item{scales}{The scales object} + +\item{width}{Total width} + +\item{height}{Total height} + +\item{show_axes}{Whether to show axes} + +\item{title}{Optional title} +} +\value{ +Character matrix +} +\description{ +Build Plot Output with Axes and Title (legacy) +} +\keyword{internal} diff --git a/man/build_plot_output_v2.Rd b/man/build_plot_output_v2.Rd new file mode 100644 index 0000000..f66923d --- /dev/null +++ b/man/build_plot_output_v2.Rd @@ -0,0 +1,41 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/ggplotcli_helpers.r +\name{build_plot_output_v2} +\alias{build_plot_output_v2} +\title{Build Plot Output with Axes and Title (v2)} +\usage{ +build_plot_output_v2( + canvas, + scales, + width, + height, + style_opts, + left_margin, + top_margin, + legend_info = NULL +) +} +\arguments{ +\item{canvas}{The rendered canvas} + +\item{scales}{The scales object} + +\item{width}{Total width} + +\item{height}{Total height} + +\item{style_opts}{Style options} + +\item{left_margin}{Left margin size} + +\item{top_margin}{Top margin size} + +\item{legend_info}{Legend information from extract_legend_info} +} +\value{ +Character matrix +} +\description{ +Build Plot Output with Axes and Title (v2) +} +\keyword{internal} diff --git a/man/color_to_term.Rd b/man/color_to_term.Rd new file mode 100644 index 0000000..8d11639 --- /dev/null +++ b/man/color_to_term.Rd @@ -0,0 +1,18 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/geom_registry.r +\name{color_to_term} +\alias{color_to_term} +\title{Convert ggplot2 color to terminal color name} +\usage{ +color_to_term(color) +} +\arguments{ +\item{color}{A color value (hex, name, or R color)} +} +\value{ +A terminal color name (blue, red, green, etc.) or NULL +} +\description{ +If init_color_mapping() was called, uses the pre-computed mapping. +Otherwise falls back to simple hue-based matching. +} diff --git a/man/create_canvas.Rd b/man/create_canvas.Rd new file mode 100644 index 0000000..2279603 --- /dev/null +++ b/man/create_canvas.Rd @@ -0,0 +1,21 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/canvas.r +\name{create_canvas} +\alias{create_canvas} +\title{Create a canvas of the specified type} +\usage{ +create_canvas(width, height, type = "braille") +} +\arguments{ +\item{width}{Character width} + +\item{height}{Character height} + +\item{type}{Canvas type: "ascii", "braille", or "block"} +} +\value{ +A Canvas object +} +\description{ +Create a canvas of the specified type +} diff --git a/man/create_panel_scales.Rd b/man/create_panel_scales.Rd new file mode 100644 index 0000000..28a2b25 --- /dev/null +++ b/man/create_panel_scales.Rd @@ -0,0 +1,29 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/ggplotcli_helpers.r +\name{create_panel_scales} +\alias{create_panel_scales} +\title{Create Scales for a Single Panel} +\usage{ +create_panel_scales(panel_params, plot_width, plot_height, + has_border = FALSE, x_mult = 1, y_mult = 1) +} +\arguments{ +\item{panel_params}{Panel parameters from ggplot_build} + +\item{plot_width}{Pixel width} + +\item{plot_height}{Pixel height} + +\item{has_border}{Whether a border will be drawn (adds padding)} + +\item{x_mult}{X multiplier for canvas type (e.g., 2 for braille)} + +\item{y_mult}{Y multiplier for canvas type (e.g., 4 for braille)} +} +\value{ +List with scale functions +} +\description{ +Create Scales for a Single Panel +} +\keyword{internal} diff --git a/man/create_scales.Rd b/man/create_scales.Rd new file mode 100644 index 0000000..28f828f --- /dev/null +++ b/man/create_scales.Rd @@ -0,0 +1,27 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/geom_registry.r +\name{create_scales} +\alias{create_scales} +\title{Create Scale Object from ggplot_build data} +\usage{ +create_scales(built, plot_width, plot_height, has_border = FALSE, x_mult = 1, y_mult = 1) +} +\arguments{ +\item{built}{Result from ggplot_build()} + +\item{plot_width}{Canvas pixel width} + +\item{plot_height}{Canvas pixel height} + +\item{has_border}{Whether a border will be drawn (adds padding)} + +\item{x_mult}{X multiplier for canvas type (e.g., 2 for braille)} + +\item{y_mult}{Y multiplier for canvas type (e.g., 4 for braille)} +} +\value{ +List with x_scale and y_scale functions +} +\description{ +Create Scale Object from ggplot_build data +} diff --git a/man/dot-geom_registry.Rd b/man/dot-geom_registry.Rd new file mode 100644 index 0000000..2bd7154 --- /dev/null +++ b/man/dot-geom_registry.Rd @@ -0,0 +1,16 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/geom_registry.r +\docType{data} +\name{.geom_registry} +\alias{.geom_registry} +\title{Geom Registry Environment} +\format{ +An object of class \code{environment} of length 15. +} +\usage{ +.geom_registry +} +\description{ +Internal environment storing registered geom handlers +} +\keyword{internal} diff --git a/man/draw_border.Rd b/man/draw_border.Rd new file mode 100644 index 0000000..0e65e96 --- /dev/null +++ b/man/draw_border.Rd @@ -0,0 +1,12 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/ggplotcli_helpers.r +\name{draw_border} +\alias{draw_border} +\title{Draw Border Around Canvas} +\usage{ +draw_border(canvas) +} +\description{ +Draw Border Around Canvas +} +\keyword{internal} diff --git a/man/draw_grid.Rd b/man/draw_grid.Rd new file mode 100644 index 0000000..3597158 --- /dev/null +++ b/man/draw_grid.Rd @@ -0,0 +1,12 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/ggplotcli_helpers.r +\name{draw_grid} +\alias{draw_grid} +\title{Draw Grid Lines on Canvas} +\usage{ +draw_grid(canvas, scales, grid_type) +} +\description{ +Draw Grid Lines on Canvas +} +\keyword{internal} diff --git a/man/extract_legend_info.Rd b/man/extract_legend_info.Rd new file mode 100644 index 0000000..a9a5128 --- /dev/null +++ b/man/extract_legend_info.Rd @@ -0,0 +1,12 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/ggplotcli_helpers.r +\name{extract_legend_info} +\alias{extract_legend_info} +\title{Extract Legend Information from ggplot} +\usage{ +extract_legend_info(built) +} +\description{ +Extract Legend Information from ggplot +} +\keyword{internal} diff --git a/man/extract_plot_labels.Rd b/man/extract_plot_labels.Rd new file mode 100644 index 0000000..8ea9fb8 --- /dev/null +++ b/man/extract_plot_labels.Rd @@ -0,0 +1,12 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/ggplotcli_helpers.r +\name{extract_plot_labels} +\alias{extract_plot_labels} +\title{Extract Plot Labels from ggplot} +\usage{ +extract_plot_labels(built, title, subtitle, caption, axis_labels) +} +\description{ +Extract Plot Labels from ggplot +} +\keyword{internal} diff --git a/man/extract_plot_style.Rd b/man/extract_plot_style.Rd new file mode 100644 index 0000000..fa0f261 --- /dev/null +++ b/man/extract_plot_style.Rd @@ -0,0 +1,12 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/ggplotcli_helpers.r +\name{extract_plot_style} +\alias{extract_plot_style} +\title{Extract Plot Style from ggplot Theme} +\usage{ +extract_plot_style(built, border, grid, legend) +} +\description{ +Extract Plot Style from ggplot Theme +} +\keyword{internal} diff --git a/man/format_axis_label.Rd b/man/format_axis_label.Rd new file mode 100644 index 0000000..f8eb865 --- /dev/null +++ b/man/format_axis_label.Rd @@ -0,0 +1,18 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/ggplotcli_helpers.r +\name{format_axis_label} +\alias{format_axis_label} +\title{Format Axis Label} +\usage{ +format_axis_label(value) +} +\arguments{ +\item{value}{Numeric value} +} +\value{ +Formatted string +} +\description{ +Format Axis Label +} +\keyword{internal} diff --git a/man/geom_area_handler.Rd b/man/geom_area_handler.Rd new file mode 100644 index 0000000..42d4dfe --- /dev/null +++ b/man/geom_area_handler.Rd @@ -0,0 +1,12 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/geom_registry.r +\name{geom_area_handler} +\alias{geom_area_handler} +\title{GeomArea Handler} +\usage{ +geom_area_handler(data, canvas, scales, params, style_opts = NULL) +} +\description{ +Renders filled areas +} +\keyword{internal} diff --git a/man/geom_bar_handler.Rd b/man/geom_bar_handler.Rd new file mode 100644 index 0000000..6991d9a --- /dev/null +++ b/man/geom_bar_handler.Rd @@ -0,0 +1,12 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/geom_registry.r +\name{geom_bar_handler} +\alias{geom_bar_handler} +\title{GeomBar/GeomCol Handler} +\usage{ +geom_bar_handler(data, canvas, scales, params, style_opts = NULL) +} +\description{ +Renders bar charts +} +\keyword{internal} diff --git a/man/geom_boxplot_handler.Rd b/man/geom_boxplot_handler.Rd new file mode 100644 index 0000000..632ac44 --- /dev/null +++ b/man/geom_boxplot_handler.Rd @@ -0,0 +1,13 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/geom_registry.r +\name{geom_boxplot_handler} +\alias{geom_boxplot_handler} +\title{GeomBoxplot Handler} +\usage{ +geom_boxplot_handler(data, canvas, scales, params, style_opts = NULL) +} +\description{ +Renders boxplots with whiskers, box, median line, and outliers. +Supports two styles: "ascii" (box-drawing characters) and "braille" (Braille dots). +} +\keyword{internal} diff --git a/man/geom_density_handler.Rd b/man/geom_density_handler.Rd new file mode 100644 index 0000000..a7f1239 --- /dev/null +++ b/man/geom_density_handler.Rd @@ -0,0 +1,12 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/geom_registry.r +\name{geom_density_handler} +\alias{geom_density_handler} +\title{GeomDensity Handler} +\usage{ +geom_density_handler(data, canvas, scales, params, style_opts = NULL) +} +\description{ +Renders density curves +} +\keyword{internal} diff --git a/man/geom_histogram_handler.Rd b/man/geom_histogram_handler.Rd new file mode 100644 index 0000000..6807585 --- /dev/null +++ b/man/geom_histogram_handler.Rd @@ -0,0 +1,12 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/geom_registry.r +\name{geom_histogram_handler} +\alias{geom_histogram_handler} +\title{GeomHistogram Handler} +\usage{ +geom_histogram_handler(data, canvas, scales, params, style_opts = NULL) +} +\description{ +Renders histograms (same as bar) +} +\keyword{internal} diff --git a/man/geom_hline_handler.Rd b/man/geom_hline_handler.Rd new file mode 100644 index 0000000..40316c8 --- /dev/null +++ b/man/geom_hline_handler.Rd @@ -0,0 +1,12 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/geom_registry.r +\name{geom_hline_handler} +\alias{geom_hline_handler} +\title{GeomHline Handler} +\usage{ +geom_hline_handler(data, canvas, scales, params, style_opts = NULL) +} +\description{ +Renders horizontal lines +} +\keyword{internal} diff --git a/man/geom_line_handler.Rd b/man/geom_line_handler.Rd new file mode 100644 index 0000000..fdc5bb9 --- /dev/null +++ b/man/geom_line_handler.Rd @@ -0,0 +1,12 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/geom_registry.r +\name{geom_line_handler} +\alias{geom_line_handler} +\title{GeomLine Handler} +\usage{ +geom_line_handler(data, canvas, scales, params, style_opts = NULL) +} +\description{ +Renders connected lines +} +\keyword{internal} diff --git a/man/geom_path_handler.Rd b/man/geom_path_handler.Rd new file mode 100644 index 0000000..03c56ff --- /dev/null +++ b/man/geom_path_handler.Rd @@ -0,0 +1,12 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/geom_registry.r +\name{geom_path_handler} +\alias{geom_path_handler} +\title{GeomPath Handler} +\usage{ +geom_path_handler(data, canvas, scales, params, style_opts = NULL) +} +\description{ +Renders connected paths (order by data, not x) +} +\keyword{internal} diff --git a/man/geom_point_handler.Rd b/man/geom_point_handler.Rd new file mode 100644 index 0000000..50ce503 --- /dev/null +++ b/man/geom_point_handler.Rd @@ -0,0 +1,12 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/geom_registry.r +\name{geom_point_handler} +\alias{geom_point_handler} +\title{GeomPoint Handler} +\usage{ +geom_point_handler(data, canvas, scales, params, style_opts = NULL) +} +\description{ +Renders points as individual pixels or small shapes +} +\keyword{internal} diff --git a/man/geom_rect_handler.Rd b/man/geom_rect_handler.Rd new file mode 100644 index 0000000..43113e5 --- /dev/null +++ b/man/geom_rect_handler.Rd @@ -0,0 +1,12 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/geom_registry.r +\name{geom_rect_handler} +\alias{geom_rect_handler} +\title{GeomRect Handler} +\usage{ +geom_rect_handler(data, canvas, scales, params, style_opts = NULL) +} +\description{ +Renders rectangles +} +\keyword{internal} diff --git a/man/geom_segment_handler.Rd b/man/geom_segment_handler.Rd new file mode 100644 index 0000000..981fccc --- /dev/null +++ b/man/geom_segment_handler.Rd @@ -0,0 +1,12 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/geom_registry.r +\name{geom_segment_handler} +\alias{geom_segment_handler} +\title{GeomSegment Handler} +\usage{ +geom_segment_handler(data, canvas, scales, params, style_opts = NULL) +} +\description{ +Renders line segments +} +\keyword{internal} diff --git a/man/geom_smooth_handler.Rd b/man/geom_smooth_handler.Rd new file mode 100644 index 0000000..91568d5 --- /dev/null +++ b/man/geom_smooth_handler.Rd @@ -0,0 +1,12 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/geom_registry.r +\name{geom_smooth_handler} +\alias{geom_smooth_handler} +\title{GeomSmooth Handler} +\usage{ +geom_smooth_handler(data, canvas, scales, params, style_opts = NULL) +} +\description{ +Renders smoothed lines (just draws the line, ignores confidence interval) +} +\keyword{internal} diff --git a/man/geom_text_handler.Rd b/man/geom_text_handler.Rd new file mode 100644 index 0000000..1317d72 --- /dev/null +++ b/man/geom_text_handler.Rd @@ -0,0 +1,12 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/geom_registry.r +\name{geom_text_handler} +\alias{geom_text_handler} +\title{GeomText Handler} +\usage{ +geom_text_handler(data, canvas, scales, params, style_opts = NULL) +} +\description{ +Renders text labels +} +\keyword{internal} diff --git a/man/geom_vline_handler.Rd b/man/geom_vline_handler.Rd new file mode 100644 index 0000000..b983d19 --- /dev/null +++ b/man/geom_vline_handler.Rd @@ -0,0 +1,12 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/geom_registry.r +\name{geom_vline_handler} +\alias{geom_vline_handler} +\title{GeomVline Handler} +\usage{ +geom_vline_handler(data, canvas, scales, params, style_opts = NULL) +} +\description{ +Renders vertical lines +} +\keyword{internal} diff --git a/man/get_color_hue.Rd b/man/get_color_hue.Rd new file mode 100644 index 0000000..f66ced4 --- /dev/null +++ b/man/get_color_hue.Rd @@ -0,0 +1,18 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/geom_registry.r +\name{get_color_hue} +\alias{get_color_hue} +\title{Get the hue of a color (0-360 degrees)} +\usage{ +get_color_hue(color) +} +\arguments{ +\item{color}{A color value} +} +\value{ +Hue in degrees (0-360) or NA for grayscale +} +\description{ +Get the hue of a color (0-360 degrees) +} +\keyword{internal} diff --git a/man/get_facet_info.Rd b/man/get_facet_info.Rd new file mode 100644 index 0000000..bd4ce3a --- /dev/null +++ b/man/get_facet_info.Rd @@ -0,0 +1,18 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/ggplotcli_helpers.r +\name{get_facet_info} +\alias{get_facet_info} +\title{Get Facet Information from Layout} +\usage{ +get_facet_info(layout) +} +\arguments{ +\item{layout}{The layout object from ggplot_build} +} +\value{ +List with facet info +} +\description{ +Get Facet Information from Layout +} +\keyword{internal} diff --git a/man/get_geom_handler.Rd b/man/get_geom_handler.Rd new file mode 100644 index 0000000..139f3eb --- /dev/null +++ b/man/get_geom_handler.Rd @@ -0,0 +1,17 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/geom_registry.r +\name{get_geom_handler} +\alias{get_geom_handler} +\title{Get a Geom Handler} +\usage{ +get_geom_handler(geom_name) +} +\arguments{ +\item{geom_name}{Name of the geom} +} +\value{ +The handler function or NULL +} +\description{ +Retrieve the registered handler for a geom, or NULL if not found. +} diff --git a/man/ggplotcli.Rd b/man/ggplotcli.Rd index 930829b..e42bd37 100644 --- a/man/ggplotcli.Rd +++ b/man/ggplotcli.Rd @@ -2,22 +2,82 @@ % Please edit documentation in R/ggplotcli.r \name{ggplotcli} \alias{ggplotcli} -\title{ggplotcli - Render ggplot objects in the terminal} +\title{ggplotcli - Render ggplot2 objects in the terminal} \usage{ -ggplotcli(ggplot_obj, plot_width = 80, plot_height = 40, braille = TRUE) +ggplotcli( + p, + width = 60, + height = 20, + canvas_type = "braille", + border = "auto", + grid = "none", + show_axes = TRUE, + axis_labels = TRUE, + legend = "auto", + title_align = "center", + subtitle = TRUE, + caption = TRUE, + title = NULL, + boxplot_style = "ascii" +) } \arguments{ -\item{ggplot_obj}{A ggplot object to be rendered in the terminal.} +\item{p}{A ggplot2 object to render} -\item{plot_width}{Width of the terminal plot in characters (default: 80).} +\item{width}{Character width of the plot (default: 60)} -\item{plot_height}{Height of the terminal plot in characters (default: 40).} +\item{height}{Character height of the plot (default: 20)} -\item{braille}{Use Braille characters for higher resolution (default: TRUE).} +\item{canvas_type}{Type of canvas: "braille" (high-res), "block" (medium), or "ascii" (basic). Default: "braille"} + +\item{border}{Draw border around plot. "auto" uses ggplot theme, or TRUE/FALSE (default: "auto")} + +\item{grid}{Grid lines: "none", "major", "minor", "both", or "auto" (default: "none")} + +\item{show_axes}{Whether to show axis values (default: TRUE)} + +\item{axis_labels}{Whether to show axis labels from ggplot (default: TRUE)} + +\item{legend}{Legend display: "auto", "right", "bottom", "none" (default: "auto")} + +\item{title_align}{Title alignment: "center" or "left" (default: "center")} + +\item{subtitle}{Whether to show subtitle (default: TRUE)} + +\item{caption}{Whether to show caption (default: TRUE)} + +\item{title}{Optional title override (NULL uses ggplot title)} + +\item{boxplot_style}{Style for boxplots: "ascii" uses box-drawing characters (default), +"braille" uses Braille dots like other geoms} } \value{ -A TerminalPlot object. +Invisibly returns the canvas object } \description{ -This function takes a ggplot object and renders it in the terminal using ASCII or Braille characters. +Convert any ggplot2 plot to a terminal-based visualization using Unicode +Braille characters or ASCII. Supports 15+ geom types, faceting, themes, +and color aesthetics. +} +\examples{ +library(ggplot2) + +# Basic scatter plot +p <- ggplot(mtcars, aes(x = wt, y = mpg)) + geom_point() +ggplotcli(p) + +# With styling +ggplotcli(p, border = TRUE, grid = "major") + +# Faceted plot +p <- ggplot(mtcars, aes(x = wt, y = mpg)) + + geom_point() + + facet_wrap(~cyl) +ggplotcli(p, width = 70, height = 16) + +# Multiple geoms +p <- ggplot(mtcars, aes(x = mpg)) + + geom_histogram(aes(y = after_stat(density)), bins = 10) + + geom_density(color = "red") +ggplotcli(p) } diff --git a/man/init_color_mapping.Rd b/man/init_color_mapping.Rd new file mode 100644 index 0000000..f366037 --- /dev/null +++ b/man/init_color_mapping.Rd @@ -0,0 +1,15 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/geom_registry.r +\name{init_color_mapping} +\alias{init_color_mapping} +\title{Initialize color mapping for a set of ggplot colors} +\usage{ +init_color_mapping(ggplot_colors) +} +\arguments{ +\item{ggplot_colors}{Vector of unique colors from ggplot} +} +\description{ +This function takes all unique colors from a ggplot and assigns terminal +colors to minimize repetition while respecting hue similarity. +} diff --git a/man/is_geom_registered.Rd b/man/is_geom_registered.Rd new file mode 100644 index 0000000..b4f1a79 --- /dev/null +++ b/man/is_geom_registered.Rd @@ -0,0 +1,17 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/geom_registry.r +\name{is_geom_registered} +\alias{is_geom_registered} +\title{Check if a Geom is Registered} +\usage{ +is_geom_registered(geom_name) +} +\arguments{ +\item{geom_name}{Name of the geom} +} +\value{ +Logical +} +\description{ +Check if a Geom is Registered +} diff --git a/man/list_registered_geoms.Rd b/man/list_registered_geoms.Rd new file mode 100644 index 0000000..110a7a5 --- /dev/null +++ b/man/list_registered_geoms.Rd @@ -0,0 +1,14 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/geom_registry.r +\name{list_registered_geoms} +\alias{list_registered_geoms} +\title{List Registered Geoms} +\usage{ +list_registered_geoms() +} +\value{ +Character vector of registered geom names +} +\description{ +List Registered Geoms +} diff --git a/man/pixel_to_braille.Rd b/man/pixel_to_braille.Rd new file mode 100644 index 0000000..f653f73 --- /dev/null +++ b/man/pixel_to_braille.Rd @@ -0,0 +1,23 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/helper_functions.r +\name{pixel_to_braille} +\alias{pixel_to_braille} +\title{Convert pixel coordinates to Braille cell and dot position} +\usage{ +pixel_to_braille(px, py, canvas_rows, canvas_cols) +} +\arguments{ +\item{px}{Pixel x coordinate (1-based)} + +\item{py}{Pixel y coordinate (1-based, from top)} + +\item{canvas_rows}{Number of character rows in canvas} + +\item{canvas_cols}{Number of character columns in canvas} +} +\value{ +List with cell_row, cell_col, dot_row, dot_col +} +\description{ +Convert pixel coordinates to Braille cell and dot position +} diff --git a/man/register_geom.Rd b/man/register_geom.Rd new file mode 100644 index 0000000..c9b60ec --- /dev/null +++ b/man/register_geom.Rd @@ -0,0 +1,21 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/geom_registry.r +\name{register_geom} +\alias{register_geom} +\title{Register a Geom Handler} +\usage{ +register_geom(geom_name, handler) +} +\arguments{ +\item{geom_name}{Name of the geom (e.g., "GeomPoint", "GeomLine")} + +\item{handler}{Function that takes (data, canvas, scales, params) and draws to canvas} +} +\description{ +Register a function that can render a specific ggplot2 geom to a canvas. +} +\examples{ +register_geom("GeomPoint", function(data, canvas, scales, params) { + # Draw points on canvas +}) +} diff --git a/man/render_faceted_plot.Rd b/man/render_faceted_plot.Rd new file mode 100644 index 0000000..7381d99 --- /dev/null +++ b/man/render_faceted_plot.Rd @@ -0,0 +1,25 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/ggplotcli_helpers.r +\name{render_faceted_plot} +\alias{render_faceted_plot} +\title{Render Faceted Plot} +\usage{ +render_faceted_plot(built, facet_info, width, height, canvas_type, style_opts) +} +\arguments{ +\item{built}{Result from ggplot_build} + +\item{facet_info}{Facet information from get_facet_info} + +\item{width}{Total width} + +\item{height}{Total height} + +\item{canvas_type}{Canvas type} + +\item{style_opts}{Style options} +} +\description{ +Render Faceted Plot +} +\keyword{internal} diff --git a/man/render_single_panel.Rd b/man/render_single_panel.Rd new file mode 100644 index 0000000..2aabfba --- /dev/null +++ b/man/render_single_panel.Rd @@ -0,0 +1,12 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/ggplotcli_helpers.r +\name{render_single_panel} +\alias{render_single_panel} +\title{Render a single panel (non-faceted) plot} +\usage{ +render_single_panel(built, width, height, canvas_type, style_opts) +} +\description{ +Render a single panel (non-faceted) plot +} +\keyword{internal} diff --git a/man/safe_aes_name.Rd b/man/safe_aes_name.Rd new file mode 100644 index 0000000..f59ce70 --- /dev/null +++ b/man/safe_aes_name.Rd @@ -0,0 +1,18 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/ggplotcli.r +\name{safe_aes_name} +\alias{safe_aes_name} +\title{Safely extract aesthetic name from ggplot mapping} +\usage{ +safe_aes_name(aes_expr) +} +\arguments{ +\item{aes_expr}{The aesthetic expression (can be a quosure)} +} +\value{ +Character string of the column name, or NULL +} +\description{ +Handles quosures, simple symbols, and calls like factor(cyl) +} +\keyword{internal} diff --git a/plotcli_docs.Rmd b/plotcli_docs.Rmd deleted file mode 100755 index b8fe7a3..0000000 --- a/plotcli_docs.Rmd +++ /dev/null @@ -1,34 +0,0 @@ ---- -title: "plotcli Documentation" -output: html_document ---- - -# Introduction - -[plotcli](https://github.com/cheuerde/plotcli/blob/main/vignettes/plotcli_class.Rmd) is an R package that provides terminal-based plotting in R. It supports colored scatter plots, line plots, bar plots, and box plots. This documentation will guide you through the usage of [plotcli](file:///Users/cheuer/Library/CloudStorage/OneDrive-Bayer/GIT_Private/plotcli/vignettes/plotcli_class.Rmd#2%2C22-2%2C22) functions with examples. - -# Examples - -## Density Plot - -```{r} -library(plotcli) -sample_data <- rnorm(1000, mean = 5, sd = 2) -plotcli_density(sample_data, color = "blue", braille = TRUE) -``` - -## Histogram - -```{r} -sample_data <- rnorm(1000, mean = 5, sd = 2) -plotcli_histogram(sample_data, color = "yellow") -``` - -## Line Plot - -```{r} -x <- seq(0, 2*pi, length.out = 50) -y <- sin(x) -plotcli_line(x = x, y = cos(y), color = "green") -plotcli_line(x = x, y = x, color = "magenta", braille = FALSE) -``` \ No newline at end of file diff --git a/tests/testthat.R b/tests/testthat.R new file mode 100644 index 0000000..78b8cce --- /dev/null +++ b/tests/testthat.R @@ -0,0 +1,4 @@ +library(testthat) +library(plotcli) + +test_check("plotcli") diff --git a/tests/testthat/test-new-geoms.R b/tests/testthat/test-new-geoms.R new file mode 100755 index 0000000..abcb614 --- /dev/null +++ b/tests/testthat/test-new-geoms.R @@ -0,0 +1,136 @@ +library(testthat) +library(plotcli) +library(ggplot2) + +test_that("GeomTile works", { + df_tile <- expand.grid(x = 1:5, y = 1:5) + df_tile$z <- runif(25) + p <- ggplot(df_tile, aes(x, y, fill = z)) + geom_tile() + + expect_output(res <- ggplotcli(p)) + expect_s3_class(res, "Canvas") +}) + +test_that("GeomPolygon warns about missing handler", { + ids <- factor(c("1.1", "2.1", "1.2", "2.2", "1.3", "2.3")) + values <- data.frame( + id = ids, + value = c(3, 3.1, 3.1, 3.2, 3.15, 3.5) + ) + positions <- data.frame( + id = rep(ids, each = 4), + x = c(2, 1, 1.1, 2.2, 1, 0, 0.3, 1.1, 2.2, 1.1, 1.2, 2.5, 1.1, 0.3, 0.5, 1.2, 2.5, 1.2, 1.3, 2.7, 1.2, 0.5, 0.6, 1.3), + y = c(-0.5, 0, 1, 0.5, 0, 0.5, 1.5, 1, 0.5, 1, 2.1, 1.7, 1, 1.5, 2.2, 2.1, 1.7, 2.1, 3.2, 2.8, 2.1, 2.2, 3.3, 3.2) + ) + datapoly <- merge(values, positions, by = c("id")) + p <- ggplot(datapoly, aes(x = x, y = y)) + geom_polygon(aes(fill = value, group = id)) + + expect_warning(res <- ggplotcli(p), "No handler registered for geom: GeomPolygon") + expect_s3_class(res, "Canvas") +}) + +test_that("Faceting works", { + p <- ggplot(mtcars, aes(x = mpg, y = wt)) + + geom_point() + + facet_wrap(~ cyl) + + expect_output(res <- ggplotcli(p)) +}) + +test_that("GeomBar works", { + p <- ggplot(mtcars, aes(x = factor(cyl))) + geom_bar() + expect_output(res <- ggplotcli(p)) + expect_s3_class(res, "Canvas") +}) + +test_that("GeomStep works", { + df <- data.frame(x = 1:10, y = cumsum(rnorm(10))) + p <- ggplot(df, aes(x, y)) + geom_step() + expect_output(res <- ggplotcli(p)) + expect_s3_class(res, "Canvas") +}) + +test_that("GeomAbline works", { + p <- ggplot(mtcars, aes(wt, mpg)) + geom_point() + + geom_abline(intercept = 37, slope = -5, color = "red") + expect_output(res <- ggplotcli(p)) + expect_s3_class(res, "Canvas") +}) + +test_that("GeomRibbon works", { + df <- data.frame(x = 1:20, y = sin(1:20 / 3), + ymin = sin(1:20 / 3) - 0.5, ymax = sin(1:20 / 3) + 0.5) + p <- ggplot(df, aes(x, y)) + + geom_ribbon(aes(ymin = ymin, ymax = ymax), fill = "steelblue") + + geom_line() + expect_output(res <- ggplotcli(p)) + expect_s3_class(res, "Canvas") +}) + +test_that("GeomSmooth with ribbon works", { + p <- ggplot(mtcars, aes(wt, mpg)) + geom_point() + + geom_smooth(method = "lm") + expect_output(res <- suppressMessages(ggplotcli(p))) + expect_s3_class(res, "Canvas") +}) + +test_that("GeomErrorbar works", { + df <- data.frame(x = 1:5, y = c(2, 4, 3, 5, 4), + ymin = c(1, 3, 2, 4, 3), ymax = c(3, 5, 4, 6, 5)) + p <- ggplot(df, aes(x, y, ymin = ymin, ymax = ymax)) + + geom_errorbar(width = 0.3) + geom_point() + expect_output(res <- ggplotcli(p)) + expect_s3_class(res, "Canvas") +}) + +test_that("GeomLinerange works", { + df <- data.frame(x = 1:5, y = c(2, 4, 3, 5, 4), + ymin = c(1, 3, 2, 4, 3), ymax = c(3, 5, 4, 6, 5)) + p <- ggplot(df, aes(x, y, ymin = ymin, ymax = ymax)) + geom_linerange() + expect_output(res <- ggplotcli(p)) + expect_s3_class(res, "Canvas") +}) + +test_that("GeomPointrange works", { + df <- data.frame(x = 1:5, y = c(2, 4, 3, 5, 4), + ymin = c(1, 3, 2, 4, 3), ymax = c(3, 5, 4, 6, 5)) + p <- ggplot(df, aes(x, y, ymin = ymin, ymax = ymax)) + geom_pointrange() + expect_output(res <- ggplotcli(p)) + expect_s3_class(res, "Canvas") +}) + +test_that("GeomCrossbar works", { + df <- data.frame(x = 1:5, y = c(2, 4, 3, 5, 4), + ymin = c(1, 3, 2, 4, 3), ymax = c(3, 5, 4, 6, 5)) + p <- ggplot(df, aes(x, y, ymin = ymin, ymax = ymax)) + + geom_crossbar(fill = "lightblue") + expect_output(res <- ggplotcli(p)) + expect_s3_class(res, "Canvas") +}) + +test_that("GeomRug works", { + p <- ggplot(mtcars, aes(wt, mpg)) + geom_point() + geom_rug() + expect_output(res <- ggplotcli(p)) + expect_s3_class(res, "Canvas") +}) + +test_that("GeomLabel works", { + df <- data.frame(x = c(1, 2, 3), y = c(3, 1, 2), lab = c("A", "B", "C")) + p <- ggplot(df, aes(x, y, label = lab)) + geom_label() + expect_output(res <- ggplotcli(p)) + expect_s3_class(res, "Canvas") +}) + +test_that("GeomRaster works", { + df <- expand.grid(x = 1:10, y = 1:10) + df$z <- runif(100) + p <- ggplot(df, aes(x, y, fill = z)) + geom_raster() + expect_output(res <- ggplotcli(p)) + expect_s3_class(res, "Canvas") +}) + +test_that("GeomViolin works", { + p <- ggplot(mtcars, aes(factor(cyl), mpg)) + geom_violin() + expect_output(res <- ggplotcli(p)) + expect_s3_class(res, "Canvas") +}) diff --git a/tests/testthat/test-plotcli.R b/tests/testthat/test-plotcli.R index 80cd80f..2f040a1 100644 --- a/tests/testthat/test-plotcli.R +++ b/tests/testthat/test-plotcli.R @@ -36,4 +36,34 @@ test_that("plotcli R6 class works", { expect_silent(plot$add_data(data_1)) expect_silent(plot$add_data(data_2)) expect_output(plot$print_plot()) +}) + +test_that("constant y-values do not error", { + x <- seq(0, 10, length.out = 50) + y <- rep(1.0, length(x)) + expect_output(plotcli_line(x = x, y = y)$print_plot()) + expect_output(plotcli_line(x = x, y = y, braille = TRUE)$print_plot()) + expect_silent(plotcli_scatter(x = x, y = y)) + expect_silent(plotcli_scatter(x = x, y = y, braille = TRUE)) +}) + +test_that("constant x-values do not error", { + x <- rep(5, 50) + y <- seq(0, 10, length.out = 50) + expect_output(plotcli_line(x = x, y = y)$print_plot()) + expect_silent(plotcli_scatter(x = x, y = y)) +}) + +test_that("constant x and y values do not error", { + x <- rep(3, 50) + y <- rep(7, 50) + expect_output(plotcli_line(x = x, y = y)$print_plot()) + expect_silent(plotcli_scatter(x = x, y = y)) +}) + +test_that("constant zero values do not error", { + x <- seq(0, 10, length.out = 50) + y <- rep(0, length(x)) + expect_output(plotcli_line(x = x, y = y)$print_plot()) + expect_silent(plotcli_scatter(x = x, y = y)) }) \ No newline at end of file diff --git a/vignettes/ggplotcli.Rmd b/vignettes/ggplotcli.Rmd new file mode 100644 index 0000000..2f1e5dd --- /dev/null +++ b/vignettes/ggplotcli.Rmd @@ -0,0 +1,329 @@ +--- +title: "ggplotcli: Universal ggplot2 to Terminal Plotting" +author: "Claas Heuer" +date: "`r Sys.Date()`" +output: rmarkdown::html_vignette +vignette: > + %\VignetteIndexEntry{ggplotcli: Universal ggplot2 to Terminal Plotting} + %\VignetteEngine{knitr::rmarkdown} + %\VignetteEncoding{UTF-8} +--- + +```{r setup, include = FALSE} +knitr::opts_chunk$set( + collapse = TRUE, + comment = "#>" +) +``` + +## Introduction + +`ggplotcli` is a universal converter that renders any ggplot2 plot in the terminal using Unicode/ASCII characters. It automatically extracts data, aesthetics, and styling from ggplot objects, supporting 15+ geom types, faceting, color aesthetics, and legends. + +## Basic Usage + +```{r} +library(plotcli) +library(ggplot2) + +# Create a ggplot +p <- ggplot(mtcars, aes(x = wt, y = mpg, color = factor(cyl))) + + geom_point() + + labs(title = "MPG vs Weight by Cylinders") + +# Render in terminal +ggplotcli(p, width = 60, height = 16) +``` + +## Supported Geoms + +### Scatter Plots (geom_point) + +```{r} +p <- ggplot(iris, aes(x = Sepal.Length, y = Sepal.Width, color = Species)) + + geom_point() + + labs(title = "Iris: Sepal Dimensions by Species") +ggplotcli(p, width = 60, height = 16) +``` + +### Line Plots (geom_line) + +```{r} +# Multiple colored lines +df <- data.frame( + x = rep(1:30, 2), + y = c(sin(1:30/4) * 10, cos(1:30/4) * 10), + type = rep(c("sin", "cos"), each = 30) +) +p <- ggplot(df, aes(x, y, color = type)) + + geom_line() + + labs(title = "Sine and Cosine Waves") +ggplotcli(p, width = 60, height = 12) +``` + +### Histograms (geom_histogram) + +```{r} +p <- ggplot(mtcars, aes(x = mpg, fill = factor(cyl))) + + geom_histogram(bins = 10, position = "dodge") + + labs(title = "MPG Distribution by Cylinders") +ggplotcli(p, width = 60, height = 12) +``` + +### Density Plots (geom_density) + +```{r} +p <- ggplot(mtcars, aes(x = mpg, color = factor(cyl))) + + geom_density() + + labs(title = "MPG Density by Cylinders") +ggplotcli(p, width = 60, height = 12) +``` + +### Bar Charts (geom_col) + +```{r} +df <- data.frame( + category = c("A", "B", "C", "D", "E", "F"), + value = c(25, 45, 30, 60, 35, 50) +) +p <- ggplot(df, aes(x = category, y = value, fill = category)) + + geom_col() + + labs(title = "Category Values") +ggplotcli(p, width = 60, height = 12) +``` + +### Boxplots (geom_boxplot) + +Boxplots are rendered with box-drawing characters by default, showing whiskers, box (Q1-Q3), median line, and outliers: + +```{r} +set.seed(42) +df <- data.frame( + group = factor(rep(paste0("Group ", 1:6), each = 50)), + value = c(rnorm(50, 10, 3), rnorm(50, 5, 2), rnorm(50, 8, 4), + rnorm(50, 6, 2), rnorm(50, 12, 3), rnorm(50, 7, 2)) +) +p <- ggplot(df, aes(x = group, y = value, fill = group)) + + geom_boxplot() + + labs(title = "Boxplot Colored by Group", y = "Value", x = "Group") +ggplotcli(p, width = 80, height = 20, boxplot_style = "ascii") +``` + +You can also use Braille rendering for boxplots: + +```{r} +ggplotcli(p, width = 80, height = 20, boxplot_style = "braille") +``` + +## Combining Multiple Geoms + +```{r} +# Histogram with density overlay +p <- ggplot(mtcars, aes(x = mpg)) + + geom_histogram(aes(y = after_stat(density)), bins = 10, fill = "gray") + + geom_density(color = "red") + + labs(title = "Histogram with Density Overlay") +ggplotcli(p, width = 60, height = 12) +``` + +```{r} +# Points with smooth line +p <- ggplot(mtcars, aes(x = wt, y = mpg)) + + geom_point(color = "gray") + + geom_smooth(method = "loess", color = "red") + + labs(title = "Scatter with LOESS Smooth") +suppressMessages(ggplotcli(p, width = 60, height = 12)) +``` + +## Faceting + +### facet_wrap with Color Aesthetics + +Faceting works seamlessly with color/fill aesthetics and legends: + +```{r} +mtcars$cyl_fac <- factor(mtcars$cyl) +p <- ggplot(mtcars, aes(x = wt, y = mpg, color = cyl_fac)) + + geom_point() + + facet_wrap(~cyl_fac) + + labs(title = "MPG vs Weight: Faceted by Cylinders") +ggplotcli(p, width = 75, height = 16) +``` + +### facet_grid + +```{r} +p <- ggplot(mtcars, aes(x = wt, y = mpg, color = factor(gear))) + + geom_point() + + facet_grid(am ~ cyl) + + labs(title = "MPG: AM (rows) x Cylinders (cols)") +ggplotcli(p, width = 80, height = 20) +``` + +## Styling Options + +### Borders and Grid Lines + +```{r} +p <- ggplot(mtcars, aes(x = hp, y = qsec)) + + geom_point(color = "cyan") + + labs(title = "Quarter Mile Time vs HP") + +# With border +ggplotcli(p, width = 55, height = 12, border = TRUE) + +# With grid +ggplotcli(p, width = 55, height = 12, grid = "major") + +# Both +ggplotcli(p, width = 55, height = 12, border = TRUE, grid = "major") +``` + +### Theme Auto-Detection + +ggplotcli automatically respects ggplot2 themes: + +```{r} +p <- ggplot(mtcars, aes(x = wt, y = mpg)) + + geom_point(color = "blue") + + labs(title = "theme_bw() - Grid + Border") + +# theme_bw has both grid and border +ggplotcli(p + theme_bw(), width = 60, height = 14, border = "auto", grid = "auto") + +# theme_classic has border but no grid +ggplotcli(p + theme_classic() + labs(title = "theme_classic() - Border Only"), + width = 60, height = 14, border = "auto", grid = "auto") +``` + +## Canvas Types + +Three rendering modes are available: + +```{r} +wave <- ggplot(data.frame(x = 1:25, y = sin(1:25/4)*8), aes(x, y)) + + geom_line(color = "green") + +# Braille (highest resolution - 2x4 dots per character) +ggplotcli(wave + labs(title = "Braille Canvas (highest resolution)"), + width = 50, height = 8, canvas_type = "braille") + +# Block (medium resolution - uses block characters) +ggplotcli(wave + labs(title = "Block Canvas (medium resolution)"), + width = 50, height = 8, canvas_type = "block") + +# ASCII (basic, most compatible) +ggplotcli(wave + labs(title = "ASCII Canvas (most compatible)"), + width = 50, height = 8, canvas_type = "ascii") +``` + +## Color Mapping + +ggplotcli intelligently maps ggplot2 colors to terminal colors (red, yellow, green, cyan, blue, magenta). The mapping prioritizes **color distinctness** over hue accuracy to maximize visual differentiation between groups. + +### Many Groups (8+) + +Even with many groups, colors are distributed to minimize repetition: + +```{r} +set.seed(123) +df <- data.frame( + group = factor(rep(paste0("G", 1:8), each = 30)), + value = unlist(lapply(1:8, function(i) rnorm(30, mean = i * 2, sd = 1.5))) +) +p <- ggplot(df, aes(x = group, y = value, fill = group)) + + geom_boxplot() + + labs(title = "8 Groups with Optimized Color Distribution") +ggplotcli(p, width = 85, height = 18, boxplot_style = "ascii") +``` + +## Showcase: Maximum Complexity + +### Complex Faceted Boxplot + +```{r} +set.seed(42) +df <- data.frame( + treatment = factor(rep(c("Control", "Drug A", "Drug B"), each = 60)), + timepoint = factor(rep(rep(c("Baseline", "Week 4", "Week 8"), each = 20), 3)), + response = c( + rnorm(20, 50, 10), rnorm(20, 52, 10), rnorm(20, 51, 10), # Control + rnorm(20, 50, 10), rnorm(20, 65, 12), rnorm(20, 70, 11), # Drug A + rnorm(20, 50, 10), rnorm(20, 58, 11), rnorm(20, 62, 10) # Drug B + ) +) + +p <- ggplot(df, aes(x = timepoint, y = response)) + + geom_boxplot(aes(fill = treatment)) + + labs(title = "Treatment Response Over Time", + subtitle = "Faceted by treatment group", + x = "Timepoint", y = "Response") + + theme_bw() + +ggplotcli(p, width = 100, height = 22, boxplot_style = "ascii") +``` + +### Multi-Layer Scientific Plot + +```{r} +# Simulated experiment data +set.seed(123) +x <- seq(0, 10, length.out = 50) +df <- data.frame( + x = rep(x, 3), + y = c( + 2 * x + rnorm(50, 0, 1.5), + 1.5 * x + 3 + rnorm(50, 0, 1.2), + x^1.2 + rnorm(50, 0, 1) + ), + group = rep(c("Linear", "Offset", "Power"), each = 50) +) + +p <- ggplot(df, aes(x = x, y = y, color = group)) + + geom_point(alpha = 0.6) + + geom_smooth(method = "loess", se = FALSE) + + labs(title = "Multi-Group Regression Analysis", + subtitle = "Points with LOESS smoothing", + x = "Predictor", y = "Response") + + theme_minimal() + +suppressMessages(ggplotcli(p, width = 70, height = 18)) +``` + +### Dense Scatter with Facets + +```{r} +p <- ggplot(iris, aes(x = Sepal.Length, y = Petal.Length, color = Species)) + + geom_point() + + facet_wrap(~Species) + + labs(title = "Iris Dataset: Sepal vs Petal Length", + subtitle = "Faceted by species with color legend") + + theme_bw() + +ggplotcli(p, width = 80, height = 16) +``` + +## Supported Features Summary + +| Feature | Status | +|---------|--------| +| geom_point | ✓ | +| geom_line, geom_path | ✓ | +| geom_bar, geom_col, geom_histogram | ✓ | +| geom_density | ✓ | +| geom_smooth | ✓ | +| geom_area | ✓ | +| geom_segment, geom_hline, geom_vline | ✓ | +| geom_rect | ✓ | +| geom_text | ✓ | +| geom_boxplot | ✓ | +| Color/fill aesthetics | ✓ | +| Legends (auto-generated) | ✓ | +| facet_wrap, facet_grid | ✓ | +| Titles, subtitles, captions | ✓ | +| Theme auto-detection | ✓ | +| Optimized color mapping | ✓ | +| Multiple canvas types | ✓ | +| geom_tile (heatmaps) | Planned | +| geom_violin | Planned | + diff --git a/vignettes/ggplotcli2.Rmd b/vignettes/ggplotcli2.Rmd deleted file mode 100644 index b27344a..0000000 --- a/vignettes/ggplotcli2.Rmd +++ /dev/null @@ -1,209 +0,0 @@ ---- -title: "ggplotcli2: Universal ggplot2 to Terminal Plotting" -author: "Claas Heuer" -date: "`r Sys.Date()`" -output: rmarkdown::html_vignette -vignette: > - %\VignetteIndexEntry{ggplotcli2: Universal ggplot2 to Terminal Plotting} - %\VignetteEngine{knitr::rmarkdown} - %\VignetteEncoding{UTF-8} ---- - -```{r setup, include = FALSE} -knitr::opts_chunk$set( - collapse = TRUE, - comment = "#>" -) -``` - -## Introduction - -`ggplotcli2` is a universal converter that renders any ggplot2 plot in the terminal using Unicode/ASCII characters. It automatically extracts data, aesthetics, and styling from ggplot objects. - -## Basic Usage - -```{r} -library(plotcli) -library(ggplot2) - -# Create a ggplot -p <- ggplot(mtcars, aes(x = wt, y = mpg, color = factor(cyl))) + - geom_point() + - labs(title = "MPG vs Weight by Cylinders") - -# Render in terminal -ggplotcli2(p, width = 60, height = 14) -``` - -## Supported Geoms - -### Scatter Plots (geom_point) - -```{r} -p <- ggplot(iris, aes(x = Sepal.Length, y = Sepal.Width, color = Species)) + - geom_point() + - labs(title = "Iris: Sepal Dimensions") -ggplotcli2(p, width = 60, height = 12) -``` - -### Line Plots (geom_line) - -```{r} -df <- data.frame(x = 1:30, y = sin(1:30/4) * 10) -p <- ggplot(df, aes(x, y)) + - geom_line(color = "blue") + - labs(title = "Sine Wave") -ggplotcli2(p, width = 60, height = 12) -``` - -### Histograms (geom_histogram) - -```{r} -p <- ggplot(mtcars, aes(x = mpg)) + - geom_histogram(bins = 10, fill = "steelblue") + - labs(title = "MPG Distribution") -ggplotcli2(p, width = 60, height = 12) -``` - -### Density Plots (geom_density) - -```{r} -p <- ggplot(mtcars, aes(x = mpg, color = factor(cyl))) + - geom_density() + - labs(title = "MPG Density by Cylinders") -ggplotcli2(p, width = 60, height = 12) -``` - -### Bar Charts (geom_col) - -```{r} -df <- data.frame( - category = c("A", "B", "C", "D"), - value = c(25, 45, 30, 60) -) -p <- ggplot(df, aes(x = category, y = value, fill = category)) + - geom_col() + - labs(title = "Category Values") -ggplotcli2(p, width = 50, height = 12) -``` - -## Combining Multiple Geoms - -```{r} -# Histogram with density overlay -p <- ggplot(mtcars, aes(x = mpg)) + - geom_histogram(aes(y = after_stat(density)), bins = 10, fill = "gray") + - geom_density(color = "red") + - labs(title = "Histogram with Density Overlay") -ggplotcli2(p, width = 60, height = 12) -``` - -```{r} -# Points with smooth line -p <- ggplot(mtcars, aes(x = wt, y = mpg)) + - geom_point(color = "gray") + - geom_smooth(method = "loess", color = "red") + - labs(title = "Scatter with LOESS Smooth") -suppressMessages(ggplotcli2(p, width = 60, height = 12)) -``` - -## Faceting - -### facet_wrap - -```{r} -p <- ggplot(mtcars, aes(x = wt, y = mpg)) + - geom_point(color = "blue") + - facet_wrap(~cyl) + - labs(title = "MPG vs Weight by Cylinders") -ggplotcli2(p, width = 70, height = 16) -``` - -### facet_grid - -```{r} -p <- ggplot(mtcars, aes(x = wt, y = mpg)) + - geom_point(color = "green") + - facet_grid(am ~ cyl) + - labs(title = "MPG: AM (rows) x Cylinders (cols)") -ggplotcli2(p, width = 70, height = 20) -``` - -## Styling Options - -### Borders and Grid Lines - -```{r} -p <- ggplot(mtcars, aes(x = hp, y = qsec)) + - geom_point(color = "cyan") + - labs(title = "Quarter Mile Time vs HP") - -# With border -ggplotcli2(p, width = 55, height = 12, border = TRUE) - -# With grid -ggplotcli2(p, width = 55, height = 12, grid = "major") - -# Both -ggplotcli2(p, width = 55, height = 12, border = TRUE, grid = "major") -``` - -### Theme Auto-Detection - -ggplotcli2 automatically respects ggplot2 themes: - -```{r} -p <- ggplot(mtcars, aes(x = wt, y = mpg)) + - geom_point(color = "blue") + - labs(title = "theme_bw() - Grid + Border") - -# theme_bw has both grid and border -ggplotcli2(p + theme_bw(), width = 55, height = 12, border = "auto", grid = "auto") - -# theme_classic has border but no grid -ggplotcli2(p + theme_classic() + labs(title = "theme_classic() - Border Only"), - width = 55, height = 12, border = "auto", grid = "auto") -``` - -## Canvas Types - -Three rendering modes are available: - -```{r} -wave <- ggplot(data.frame(x = 1:25, y = sin(1:25/4)*8), aes(x, y)) + - geom_line(color = "green") - -# Braille (highest resolution) -ggplotcli2(wave + labs(title = "Braille Canvas"), - width = 50, height = 8, canvas_type = "braille") - -# Block (medium resolution) -ggplotcli2(wave + labs(title = "Block Canvas"), - width = 50, height = 8, canvas_type = "block") - -# ASCII (basic, most compatible) -ggplotcli2(wave + labs(title = "ASCII Canvas"), - width = 50, height = 8, canvas_type = "ascii") -``` - -## Supported Features Summary - -| Feature | Status | -|---------|--------| -| geom_point | ✓ | -| geom_line, geom_path | ✓ | -| geom_bar, geom_col, geom_histogram | ✓ | -| geom_density | ✓ | -| geom_smooth | ✓ | -| geom_area | ✓ | -| geom_segment, geom_hline, geom_vline | ✓ | -| geom_rect | ✓ | -| geom_text | ✓ | -| Color/fill aesthetics | ✓ | -| facet_wrap, facet_grid | ✓ | -| Titles, subtitles, captions | ✓ | -| Theme auto-detection | ✓ | -| geom_tile (heatmaps) | Planned | -| geom_boxplot | Planned | -| geom_violin | Planned | - diff --git a/vignettes/ggplotli.R b/vignettes/ggplotli.R deleted file mode 100644 index 953a41f..0000000 --- a/vignettes/ggplotli.R +++ /dev/null @@ -1,22 +0,0 @@ -## ----setup, include = FALSE--------------------------------------------------- -knitr::opts_chunk$set( - collapse = TRUE, - comment = "#>" -) - -## ----------------------------------------------------------------------------- -library(plotcli) -library(ggplot2) - -mtcars$cf = as.character(mtcars$cyl) - -mtcars_ggplot <- ggplot(mtcars, aes(x = mpg, y = wt)) + - geom_point() + - geom_smooth(method = "lm", color = "red") + - labs(title = "Mtcars Dataset with Regression Line", - x = "Miles per Gallon", - y = "Weight") - -pp = ggplotcli(mtcars_ggplot, braille = FALSE) -pp$print_plot() - diff --git a/vignettes/ggplotli.Rmd b/vignettes/ggplotli.Rmd deleted file mode 100644 index f6e487b..0000000 --- a/vignettes/ggplotli.Rmd +++ /dev/null @@ -1,35 +0,0 @@ ---- -title: "Vignette For ggplotcli" -author: "Claas Heuer" -date: "`r Sys.Date()`" -output: rmarkdown::html_vignette -vignette: > - %\VignetteIndexEntry{Introduction to ggplotcli} - %\VignetteEngine{knitr::rmarkdown} - %\VignetteEncoding{UTF-8} ---- - -```{r setup, include = FALSE} -knitr::opts_chunk$set( - collapse = TRUE, - comment = "#>" -) -``` - -## Using `ggplotcli` with `ggplot2` - -```{r} -library(plotcli) - -mtcars$cf = as.character(mtcars$cyl) - -mtcars_ggplot <- ggplot(mtcars, aes(x = mpg, y = wt)) + - geom_point() + - geom_smooth(method = "lm", color = "red") + - labs(title = "Mtcars Dataset with Regression Line", - x = "Miles per Gallon", - y = "Weight") - -pp = ggplotcli(mtcars_ggplot, braille = FALSE) -pp$print_plot() -``` \ No newline at end of file diff --git a/vignettes/plotcli_class.Rmd b/vignettes/plotcli_class.Rmd index 17b1d16..e324c3e 100644 --- a/vignettes/plotcli_class.Rmd +++ b/vignettes/plotcli_class.Rmd @@ -1,10 +1,10 @@ --- -title: "Vignette For plotcli R6 class usage" +title: "Using the plotcli R6 Class" author: "Claas Heuer" date: "`r Sys.Date()`" output: rmarkdown::html_vignette vignette: > - %\VignetteIndexEntry{Vignette plotcli_class} + %\VignetteIndexEntry{Using the plotcli R6 Class} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- diff --git a/vignettes/plotcli_wrappers.Rmd b/vignettes/plotcli_wrappers.Rmd index a7f6ba6..d09462b 100644 --- a/vignettes/plotcli_wrappers.Rmd +++ b/vignettes/plotcli_wrappers.Rmd @@ -1,10 +1,10 @@ --- -title: "Vignette For plotcli R6 class usage" +title: "plotcli Convenience Wrappers" author: "Claas Heuer" date: "`r Sys.Date()`" output: rmarkdown::html_vignette vignette: > - %\VignetteIndexEntry{Vignette plotcli wrappers} + %\VignetteIndexEntry{plotcli Convenience Wrappers} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} ---