### Installation - Python Source: https://github.com/kroitor/asciichart/blob/master/_autodocs/usage-guide.md Install the asciichartpy library using pip. ```bash pip install asciichartpy ``` -------------------------------- ### Python Quick Start Source: https://github.com/kroitor/asciichart/blob/master/_autodocs/README.md Quick start example for using asciichartpy in Python. ```python import asciichartpy data = [1, 2, 3, 4, 5, 4, 3, 2, 1] print(asciichartpy.plot(data)) ``` -------------------------------- ### JavaScript Quick Start Source: https://github.com/kroitor/asciichart/blob/master/_autodocs/README.md Quick start example for using asciichart in JavaScript (Node.js or Browser). ```javascript const asciichart = require('asciichart') const data = [1, 2, 3, 4, 5, 4, 3, 2, 1] console.log(asciichart.plot(data)) ``` -------------------------------- ### Installation Source: https://github.com/kroitor/asciichart/blob/master/_autodocs/quick-reference.md Install the asciichart library for JavaScript or Python. ```bash # JavaScript npm install asciichart # Python pip install asciichartpy ``` -------------------------------- ### Data Flow Example - Input Source: https://github.com/kroitor/asciichart/blob/master/_autodocs/architecture.md Example input data for the data flow. ```javascript series = [1, 2, 3, 4, 5] cfg = { height: 4 } ``` -------------------------------- ### Example Configuration Python Source: https://github.com/kroitor/asciichart/blob/master/_autodocs/types.md Example configuration dictionary for the plot function in Python. ```python config = { 'height': 8, 'offset': 5, 'min': 0, 'max': 100, 'colors': [asciichartpy.blue, asciichartpy.green], 'format': '{:8.0f}' } ``` -------------------------------- ### NodeJS Usage Source: https://github.com/kroitor/asciichart/blob/master/README.md Install the package using npm and then import it into your JavaScript file. The example shows how to generate a sine wave and plot it. ```sh npm install asciichart ``` ```javascript var asciichart = require ('asciichart') var s0 = new Array (120) for (var i = 0; i < s0.length; i++) s0[i] = 15 * Math.sin (i * ((Math.PI * 4) / s0.length)) console.log (asciichart.plot (s0)) ``` -------------------------------- ### Example: ASCII-Art Alternative Source: https://github.com/kroitor/asciichart/blob/master/_autodocs/types.md An example of how to configure AsciiChart to use ASCII characters for symbols. ```javascript const config = { symbols: ['+', '|', '-', '-', '-', '\\', '/', '/', '\\', '|'] } asciichart.plot(data, config) ``` -------------------------------- ### NodeJS Installation Source: https://github.com/kroitor/asciichart/blob/master/README.rst Install the asciichart package using npm. ```sh npm install asciichart ``` -------------------------------- ### Minimal Examples Source: https://github.com/kroitor/asciichart/blob/master/_autodocs/quick-reference.md Basic examples of plotting a simple data series in JavaScript and Python. ```javascript const data = [1, 2, 3, 4, 5] console.log(asciichart.plot(data)) ``` ```python data = [1, 2, 3, 4, 5] print(asciichartpy.plot(data)) ``` -------------------------------- ### Plot and Save Example (Python) Source: https://github.com/kroitor/asciichart/blob/master/_autodocs/quick-reference.md Example of plotting chart data and saving it to a file in Python. ```python chart = asciichartpy.plot(data) with open('chart.txt', 'w') as f: f.write(chart) ``` -------------------------------- ### Unit Testing Chart Output (JavaScript) Source: https://github.com/kroitor/asciichart/blob/master/_autodocs/usage-guide.md Provides examples of unit tests for AsciiChart in JavaScript, verifying constant series, multiple series, and custom height. ```JavaScript const asciichart = require('asciichart') const assert = require('assert') function testConstantSeries() { const data = [5, 5, 5, 5] const result = asciichart.plot(data) // Should contain the value label assert(result.includes('5.00'), 'Should contain value label') // Should contain axis assert(result.includes('┤'), 'Should contain axis marker') console.log('✓ testConstantSeries passed') } function testMultipleSeries() { const data = [[1, 2, 3], [3, 2, 1]] const result = asciichart.plot(data) assert(result.includes('\n'), 'Should contain newlines') assert(result.length > 0, 'Should produce output') console.log('✓ testMultipleSeries passed') } function testCustomHeight() { const data = [1, 2, 3, 4, 5] const result = asciichart.plot(data, { height: 2 }) const lines = result.split('\n') assert(lines.length <= 3, 'Height should limit line count') console.log('✓ testCustomHeight passed') } // Run tests testConstantSeries() testMultipleSeries() testCustomHeight() console.log('\nAll tests passed!') ``` -------------------------------- ### Example 4: Currency Values with Custom Format (Python) Source: https://github.com/kroitor/asciichart/blob/master/_autodocs/configuration.md Example demonstrating how to format currency values with a custom format string in Python. ```python import asciichartpy revenue = [1000, 1500, 2200, 2800, 2400, 3100] config = { 'format': '${:7.0f}', 'height': 5, 'colors': [asciichartpy.green] } print(asciichartpy.plot(revenue, config)) ``` -------------------------------- ### Custom Format Example (Python) Source: https://github.com/kroitor/asciichart/blob/master/_autodocs/quick-reference.md Example of defining a custom format string for labels in Python. ```python { 'format': '{:8.2f}' # Python format spec } ``` -------------------------------- ### Plot and Save Example (JavaScript) Source: https://github.com/kroitor/asciichart/blob/master/_autodocs/quick-reference.md Example of plotting chart data and saving it to a file using Node.js. ```javascript const fs = require('fs') const chart = asciichart.plot(data) fs.writeFileSync('chart.txt', chart) ``` -------------------------------- ### Usage Example Source: https://github.com/kroitor/asciichart/blob/master/_autodocs/api-reference/asciichartpy.md A basic example demonstrating how to plot two series with custom colors using asciichartpy. ```python import asciichartpy series1 = [1, 2, 3, 4, 5] series2 = [5, 4, 3, 2, 1] config = { 'colors': [asciichartpy.blue, asciichartpy.green] } print(asciichartpy.plot([series1, series2], config)) ``` -------------------------------- ### Common Configuration Example Source: https://github.com/kroitor/asciichart/blob/master/_autodocs/quick-reference.md Example of using common configuration options for chart height, colors, and offset in JavaScript and Python. ```javascript asciichart.plot(data, { height: 8, colors: [asciichart.red, asciichart.green], offset: 5 }) ``` ```python asciichartpy.plot(data, { 'height': 8, 'colors': [asciichartpy.red, asciichartpy.green], 'offset': 5 }) ``` -------------------------------- ### Example 1: High-Resolution Chart with Custom Colors Source: https://github.com/kroitor/asciichart/blob/master/_autodocs/configuration.md Example demonstrating a high-resolution chart with custom colors for multiple series. ```javascript const data1 = [Math.sin(i * 0.1) * 10 for i in range(100)] const data2 = [Math.cos(i * 0.1) * 10 for i in range(100)] const config = { height: 16, offset: 6, colors: [asciichart.red, asciichart.green] } console.log(asciichart.plot([data1, data2], config)) ``` -------------------------------- ### Python height example Source: https://github.com/kroitor/asciichart/blob/master/_autodocs/configuration.md Example of setting the chart height to 4 rows in Python. ```python data = [10, 20, 30, 40, 50, 40, 30, 20, 10] print(asciichartpy.plot(data, {'height': 4})) ``` -------------------------------- ### Custom symbols example Source: https://github.com/kroitor/asciichart/blob/master/_autodocs/configuration.md Example of using custom symbols for chart rendering. ```javascript const data = [1, 2, 3, 4, 5] const config = { symbols: ['#', '|', '<', '>', '-', '\\', '/', '/', '\\', '|'] } console.log(asciichart.plot(data, config)) ``` -------------------------------- ### Example 2: Comparing Data with Fixed Bounds (Python) Source: https://github.com/kroitor/asciichart/blob/master/_autodocs/configuration.md Example showing how to compare two datasets using fixed y-axis bounds and custom colors in Python. ```python import asciichartpy historical_data = [10, 15, 12, 18, 20, 17, 22] current_data = [14, 16, 15, 19, 21, 18, 23] # Both charts will use same y-axis scale for comparison config = { 'min': 5, 'max': 25, 'height': 8, 'colors': [asciichartpy.blue, asciichartpy.yellow] } print("Historical:") print(asciichartpy.plot(historical_data, config)) print("\nCurrent:") print(asciichartpy.plot(current_data, config)) ``` -------------------------------- ### Custom Format Example (JavaScript) Source: https://github.com/kroitor/asciichart/blob/master/_autodocs/quick-reference.md Example of defining a custom format function for labels in JavaScript. ```javascript { format: function(x) { return (padding + x.toFixed(2)).slice(-padding.length) } } ``` -------------------------------- ### Streaming Data Example (Python) Source: https://github.com/kroitor/asciichart/blob/master/_autodocs/quick-reference.md Example of continuously updating and displaying a chart with streaming data in Python. ```python import time import os buffer = [] while True: buffer.append(new_value) if len(buffer) > 50: buffer.pop(0) os.system('clear') print(asciichartpy.plot(buffer)) time.sleep(1) ``` -------------------------------- ### JavaScript height example Source: https://github.com/kroitor/asciichart/blob/master/_autodocs/configuration.md Example of setting the chart height to 4 rows in JavaScript. ```javascript const data = [10, 20, 30, 40, 50, 40, 30, 20, 10] console.log(asciichart.plot(data, { height: 4 })) ``` -------------------------------- ### JavaScript min/max example Source: https://github.com/kroitor/asciichart/blob/master/_autodocs/configuration.md Example of using 'min' and 'max' to explicitly set y-axis bounds in JavaScript. ```javascript const data = [5, 10, 15, 20, 15, 10, 5] // Auto-scale to data range (5 to 20) console.log(asciichart.plot(data)) // Force axis to show 0 to 25 console.log(asciichart.plot(data, { min: 0, max: 25 })) ``` -------------------------------- ### JavaScript offset examples Source: https://github.com/kroitor/asciichart/blob/master/_autodocs/configuration.md Examples demonstrating the 'offset' configuration option in JavaScript to control y-axis label space. ```javascript const data = [1, 2, 3, 4, 5] // Offset of 3 (default) console.log(asciichart.plot(data, { offset: 3 })) // Offset of 8 (more room for labels) console.log(asciichart.plot(data, { offset: 8 })) ``` -------------------------------- ### Custom format example (Python) Source: https://github.com/kroitor/asciichart/blob/master/_autodocs/configuration.md Example of using a custom Python format string for y-axis labels. ```python data = [100, 200, 300, 400, 500] config = { 'height': 4, 'format': '{:8.0f}' # 8 characters wide, no decimal places } print(asciichartpy.plot(data, config)) ``` -------------------------------- ### JavaScript padding and format example Source: https://github.com/kroitor/asciichart/blob/master/_autodocs/configuration.md Example showing custom padding and a format function for y-axis labels in JavaScript. ```javascript const data = [1.234, 5.678, 9.012] const config = { padding: ' ', // 7 spaces format: function(x, i) { return (padding + x.toFixed(2)).slice(-padding.length) } } console.log(asciichart.plot(data, config)) ``` -------------------------------- ### Streaming Data Example (JavaScript) Source: https://github.com/kroitor/asciichart/blob/master/_autodocs/quick-reference.md Example of continuously updating and displaying a chart with streaming data in JavaScript. ```javascript const buffer = [] setInterval(() => { buffer.push(newValue) if (buffer.length > 50) buffer.shift() console.clear() console.log(asciichart.plot(buffer)) }, 1000) ``` -------------------------------- ### Example 3: Minimal Axis with Integer Labels Source: https://github.com/kroitor/asciichart/blob/master/_autodocs/configuration.md Example of a minimal axis chart with integer labels and custom padding. ```javascript const data = [42, 57, 68, 73, 81, 92] const config = { height: 4, offset: 2, padding: ' ', format: function(x) { return (padding + Math.round(x)).slice(-padding.length) } } console.log(asciichart.plot(data, config)) ``` -------------------------------- ### Custom Symbols Example Source: https://github.com/kroitor/asciichart/blob/master/_autodocs/quick-reference.md Example of providing custom symbols for chart rendering in JavaScript. ```javascript { symbols: ['+', '|', '-', '-', '-', '\\', '/', '/', '\\', '|'] } ``` -------------------------------- ### Custom formatter example (JavaScript) Source: https://github.com/kroitor/asciichart/blob/master/_autodocs/configuration.md Example of using a custom JavaScript function to format y-axis labels. ```javascript const data = [100, 200, 300, 400, 500] const config = { padding: ' ', format: function(x, i) { return (' ' + x.toFixed(0) + ' %').slice(-' '.length) } } console.log(asciichart.plot(data, config)) ``` -------------------------------- ### NaN Handling Example (Python) Source: https://github.com/kroitor/asciichart/blob/master/_autodocs/types.md Example demonstrating how NaN values are handled in Python to create gaps in the chart. ```python import asciichartpy data = [1, 2, float('nan'), 4, 5] print(asciichartpy.plot(data)) ``` -------------------------------- ### Color Constants Example Source: https://github.com/kroitor/asciichart/blob/master/_autodocs/quick-reference.md Example of using color constants for chart elements in JavaScript and Python. ```javascript colors: [asciichart.blue, asciichart.green, asciichart.red] ``` ```python colors: [asciichartpy.blue, asciichartpy.green, asciichartpy.red] ``` -------------------------------- ### Validation Tips (Python) Source: https://github.com/kroitor/asciichart/blob/master/_autodocs/quick-reference.md Example of handling potential configuration errors, such as min exceeding max, in Python. ```python # Python validates min <= max and raises ValueError if not try: result = asciichartpy.plot(data, cfg) except ValueError as e: print(f"Config error: {e}") ``` -------------------------------- ### NaN Handling Example (Python) Source: https://github.com/kroitor/asciichart/blob/master/_autodocs/quick-reference.md Example demonstrating how NaN values are handled in Python, creating gaps in the chart. ```python import math data = [1, 2, float('nan'), 4, 5] asciichartpy.plot(data) # Creates gap at NaN ``` -------------------------------- ### Value to Grid Row Mapping Example Source: https://github.com/kroitor/asciichart/blob/master/_autodocs/architecture.md Shows the mapping from data values to scaled values and finally to grid rows. ```text data_value → scaled_value → grid_row 5 → 4 → 0 4 → 3 → 1 3 → 2 → 2 2 → 1 → 3 1 → 0 → 4 Formula: `grid_row = rows - (scaled_value)` ``` -------------------------------- ### Import - Python Source: https://github.com/kroitor/asciichart/blob/master/_autodocs/usage-guide.md Import the asciichartpy library in a Python environment. ```python import asciichartpy # or from asciichartpy import plot, blue, green, reset ``` -------------------------------- ### JavaScript colors example Source: https://github.com/kroitor/asciichart/blob/master/_autodocs/configuration.md Example of using the 'colors' option to assign ANSI colors to multiple series in JavaScript. ```javascript const series1 = [1, 2, 3, 4, 5] const series2 = [5, 4, 3, 2, 1] const series3 = [3, 3, 3, 3, 3] const config = { colors: [ asciichart.blue, asciichart.green // series3 will cycle back to blue ] } console.log(asciichart.plot([series1, series2, series3], config)) ``` -------------------------------- ### Multiple Series Example Source: https://github.com/kroitor/asciichart/blob/master/_autodocs/quick-reference.md Example of plotting multiple data series simultaneously in JavaScript and Python. ```javascript const s1 = [1, 2, 3] const s2 = [3, 2, 1] asciichart.plot([s1, s2]) ``` ```python s1 = [1, 2, 3] s2 = [3, 2, 1] asciichartpy.plot([s1, s2]) ``` -------------------------------- ### Grid Coordinate System Example Source: https://github.com/kroitor/asciichart/blob/master/_autodocs/architecture.md Illustrates the grid coordinate system used for rendering the chart, showing rows and columns with value mapping. ```text col → r 0 1 2 3 4 5 6 7 o ═════════════════ w 5.00 ┤ ╭ ← row 0 (top, highest value) 4.00 ┤ ╭╯ ← row 1 3.00 ┤ ╭╯ ← row 2 2.00 ┤╭╯ ← row 3 ↓ 1.00 ┼╯ ← row 4 (bottom, lowest value) (offset area) (data area) ``` -------------------------------- ### Error Message Example (Python) Source: https://github.com/kroitor/asciichart/blob/master/_autodocs/quick-reference.md Example of a ValueError raised in Python when the minimum value exceeds the maximum value in configuration. ```python ValueError: The min value cannot exceed the max value. (Raised when cfg['min'] > cfg['max']) ``` -------------------------------- ### Data Flow Example - Normalized Source: https://github.com/kroitor/asciichart/blob/master/_autodocs/architecture.md Normalized input data for the data flow. ```javascript series = [[1, 2, 3, 4, 5]] // Wrapped in array ``` -------------------------------- ### Validation Tips (JavaScript) Source: https://github.com/kroitor/asciichart/blob/master/_autodocs/quick-reference.md Example of input validation for the series data in JavaScript. ```javascript // Always validate input if (!Array.isArray(series) || series.length === 0) { throw new Error('Invalid series') } ``` -------------------------------- ### Import - JavaScript (Node.js) Source: https://github.com/kroitor/asciichart/blob/master/_autodocs/usage-guide.md Import the asciichart library in a Node.js environment. ```javascript const asciichart = require('asciichart') ``` -------------------------------- ### JavaScript undefined color example Source: https://github.com/kroitor/asciichart/blob/master/_autodocs/configuration.md Example showing how to omit color for a specific series using 'undefined' in the colors array in JavaScript. ```javascript const config = { colors: [asciichart.red, undefined, asciichart.blue] // series2 will use no color (default terminal color) } ``` -------------------------------- ### Data Flow Example - Scaled Points Source: https://github.com/kroitor/asciichart/blob/master/_autodocs/architecture.md Mapping of data values to grid coordinates. ```javascript Value 1 → Math.round(1 * 1) - 1 = 0 → grid row 4 - 0 = 4 (bottom) Value 2 → Math.round(2 * 1) - 1 = 1 → grid row 4 - 1 = 3 Value 3 → Math.round(3 * 1) - 1 = 2 → grid row 4 - 2 = 2 Value 4 → Math.round(4 * 1) - 1 = 3 → grid row 4 - 3 = 1 Value 5 → Math.round(5 * 1) - 1 = 4 → grid row 4 - 4 = 0 (top) ``` -------------------------------- ### Simple Line Chart (Python) Source: https://github.com/kroitor/asciichart/blob/master/_autodocs/README.md Example of plotting a simple line chart using Python. ```python # Python data = [1, 2, 3, 4, 5] print(asciichartpy.plot(data)) ``` -------------------------------- ### colored function example Source: https://github.com/kroitor/asciichart/blob/master/_autodocs/api-reference/asciichartpy.md Demonstrates using the colored helper function to apply ANSI color codes to a character. ```python import asciichartpy # Apply color print(asciichartpy.colored('X', asciichartpy.red)) # Output: \033[31mX\033[0m # No color print(asciichartpy.colored('X', None)) # Output: X ``` -------------------------------- ### NodeJS Usage Example Source: https://github.com/kroitor/asciichart/blob/master/README.rst Basic usage of asciichart in a NodeJS environment to plot a sine wave. ```javascript var asciichart = require ('asciichart') var s0 = new Array (120) for (var i = 0; i < s0.length; i++) s0[i] = 15 * Math.sin (i * ((Math.PI * 4) / s0.length)) console.log (asciichart.plot (s0)) ``` -------------------------------- ### Usage Example Source: https://github.com/kroitor/asciichart/blob/master/_autodocs/api-reference/asciichart.md Demonstrates how to use the asciichart library to plot multiple series with custom colors. ```javascript const asciichart = require('asciichart') const series1 = [1, 2, 3, 4, 5] const series2 = [5, 4, 3, 2, 1] const config = { colors: [asciichart.blue, asciichart.green] } console.log(asciichart.plot([series1, series2], config)) ``` -------------------------------- ### Data Flow Example - Calculated Values Source: https://github.com/kroitor/asciichart/blob/master/_autodocs/architecture.md Calculated values during the data flow process. ```javascript min = 1, max = 5 range = 4 ratio = 4 / 4 = 1 min2 = 1, max2 = 5 rows = 4 width = 5 + 3 = 8 ``` -------------------------------- ### Moving Average Example (Python) Source: https://github.com/kroitor/asciichart/blob/master/_autodocs/quick-reference.md Python function to calculate a moving average for a data series. ```python def ma(data, n=3): result = [] for i in range(len(data)): slice_data = data[max(0, i - n + 1):i + 1] result.append(sum(slice_data) / len(slice_data)) return result ``` -------------------------------- ### Benchmark Results Visualization Source: https://github.com/kroitor/asciichart/blob/master/_autodocs/usage-guide.md Visualizes benchmark results for multiple algorithms, displaying labels and using custom formatting for time in milliseconds. ```javascript const asciichart = require('asciichart') const benchmarks = { 'Algorithm A': [1.2, 1.3, 1.1, 1.4, 1.25], 'Algorithm B': [0.8, 0.9, 0.85, 0.95, 0.9], 'Algorithm C': [2.1, 2.0, 2.2, 1.9, 2.05] } const series = Object.values(benchmarks) const labels = Object.keys(benchmarks) const config = { height: 10, colors: [asciichart.green, asciichart.yellow, asciichart.red], format: function(x) { return (' ' + x.toFixed(2) + 'ms').slice(-' ms'.length) } } console.log(labels.join(' | ')) console.log(asciichart.plot(series, config)) ``` ```python import asciichartpy benchmarks = { 'Algorithm A': [1.2, 1.3, 1.1, 1.4, 1.25], 'Algorithm B': [0.8, 0.9, 0.85, 0.95, 0.9], 'Algorithm C': [2.1, 2.0, 2.2, 1.9, 2.05] } series = list(benchmarks.values()) labels = list(benchmarks.keys()) config = { 'height': 10, 'colors': [asciichartpy.green, asciichartpy.yellow, asciichartpy.red], 'format': '{:8.2f}ms' } print(' | '.join(labels)) print(asciichartpy.plot(series, config)) ``` -------------------------------- ### Auto-range Example Source: https://github.com/kroitor/asciichart/blob/master/README.md Illustrates how the chart can automatically adjust its range based on the input data, creating a dynamic visualization. ```javascript var s2 = new Array (120) s2[0] = Math.round (Math.random () * 15) for (i = 1; i < s2.length; i++) s2[i] = s2[i - 1] + Math.round (Math.random () * (Math.random () > 0.5 ? 2 : -2)) console.log (asciichart.plot (s2)) ``` -------------------------------- ### File-Based Logging Source: https://github.com/kroitor/asciichart/blob/master/_autodocs/usage-guide.md Saves an ASCII chart of daily user growth to a text file named 'user_growth.txt' with specified height and color. ```javascript const asciichart = require('asciichart') const fs = require('fs') function saveChart(data, filename, cfg = {}) { const chart = asciichart.plot(data, cfg) fs.writeFileSync(filename, chart, 'utf8') console.log(`Chart saved to ${filename}`) } // Usage const dailyUsers = [100, 150, 200, 180, 250, 280, 320] saveChart(dailyUsers, 'user_growth.txt', { height: 8, colors: [asciichart.green] }) ``` ```python import asciichartpy def save_chart(data, filename, cfg=None): chart = asciichartpy.plot(data, cfg) with open(filename, 'w') as f: f.write(chart) print(f"Chart saved to {filename}") # Usage daily_users = [100, 150, 200, 180, 250, 280, 320] save_chart(daily_users, 'user_growth.txt', { 'height': 8, 'colors': [asciichartpy.green] }) ``` -------------------------------- ### Simple Line Chart (JavaScript) Source: https://github.com/kroitor/asciichart/blob/master/_autodocs/README.md Example of plotting a simple line chart using JavaScript. ```javascript // JavaScript const data = [1, 2, 3, 4, 5] console.log(asciichart.plot(data)) ``` -------------------------------- ### Multiple Series with Colors (Python) Source: https://github.com/kroitor/asciichart/blob/master/_autodocs/README.md Example of plotting multiple series with custom colors in Python. ```python # Python series1 = [1, 2, 3, 4, 5] series2 = [5, 4, 3, 2, 1] config = {'colors': [asciichartpy.blue, asciichartpy.green]} print(asciichartpy.plot([series1, series2], config)) ``` -------------------------------- ### Fixed Range Comparison (Python with NaN) Source: https://github.com/kroitor/asciichart/blob/master/_autodocs/README.md Example demonstrating fixed range and handling NaN values in Python. ```python import asciichartpy import math data_with_gap = [1, 2, math.nan, 4, 5] config = { 'min': 0, 'max': 10, 'height': 8 } print(asciichartpy.plot(data_with_gap, config)) ``` -------------------------------- ### Moving Average Example (JavaScript) Source: https://github.com/kroitor/asciichart/blob/master/_autodocs/quick-reference.md JavaScript function to calculate a moving average for a data series. ```javascript function ma(data, n = 3) { const result = [] for (let i = 0; i < data.length; i++) { const slice = data.slice(Math.max(0, i - n + 1), i + 1) result.push(slice.reduce((a, b) => a + b) / slice.length) } return result } ``` -------------------------------- ### Safe Plotting with Validation (Python) Source: https://github.com/kroitor/asciichart/blob/master/_autodocs/usage-guide.md Demonstrates how to safely plot data with input validation for data types, formats, and configuration parameters in Python. ```Python import asciichartpy import math def plot_safe(data, cfg=None): # Validate input if not isinstance(data, list): print('Error: data must be a list') return '' if not data: print('Warning: empty data series') return '' # Check if single or multiple series is_single_series = not isinstance(data[0], list) if is_single_series: # Validate single series try: for v in data: if not isinstance(v, (int, float)): raise ValueError(f'Invalid value type: {type(v)}') except Exception as e: print(f'Error: invalid data format - {e}') return '' else: # Validate multiple series try: for i, series in enumerate(data): if not isinstance(series, list): raise ValueError(f'Series {i} is not a list') except Exception as e: print(f'Error: invalid data format - {e}') return '' # Validate configuration if cfg: if 'min' in cfg and 'max' in cfg and cfg['min'] > cfg['max']: print('Error: min cannot be greater than max') return '' if 'offset' in cfg and cfg['offset'] < 2: print('Warning: offset should be at least 2') cfg['offset'] = 2 try: return asciichartpy.plot(data, cfg) except Exception as error: print(f'Error plotting chart: {error}') return '' # Usage result = plot_safe([1, 2, 3, 4, 5], {'height': 8}) if result: print(result) ``` -------------------------------- ### Custom Height and Formatting (Python) Source: https://github.com/kroitor/asciichart/blob/master/_autodocs/README.md Example of customizing chart height and y-axis label formatting in Python. ```python # Python data = [10, 20, 30, 40, 50] config = { 'height': 6, 'format': '{:4.0f}%' } print(asciichartpy.plot(data, config)) ``` -------------------------------- ### Step 5: Grid Initialization (Python) Source: https://github.com/kroitor/asciichart/blob/master/_autodocs/architecture.md Initializes the 2D character grid for rendering in Python. ```python # Python width = 0 for i in range(0, len(series)): width = max(width, len(series[i])) width += offset result = [[' '] * width for i in range(rows + 1)] ``` -------------------------------- ### JSON Data Source (Python) Source: https://github.com/kroitor/asciichart/blob/master/_autodocs/usage-guide.md Shows how to read and plot data from JSON files using Python, supporting various JSON structures. ```Python import asciichartpy import json def plot_from_json(filename, cfg=None): try: with open(filename, 'r') as f: data = json.load(f) # Handle different JSON structures if isinstance(data, list): return asciichartpy.plot(data, cfg) elif 'series' in data: config = {**cfg} if cfg else {} if 'config' in data: config.update(data['config']) return asciichartpy.plot(data['series'], config) else: raise ValueError('Unexpected JSON structure') except Exception as error: print(f'Error reading JSON: {error}') return '' # Usage chart = plot_from_json('data.json', {'height': 8}) print(chart) ``` -------------------------------- ### JSON Data Source (JavaScript) Source: https://github.com/kroitor/asciichart/blob/master/_autodocs/usage-guide.md Illustrates how to read and plot data from JSON files using JavaScript, handling different JSON structures. ```JavaScript const asciichart = require('asciichart') const fs = require('fs') function plotFromJSON(filename, cfg = {}) { try { const json = fs.readFileSync(filename, 'utf8') const data = JSON.parse(json) // Handle different JSON structures if (Array.isArray(data)) { return asciichart.plot(data, cfg) } else if (data.series) { return asciichart.plot(data.series, { ...cfg, ...data.config }) } else { throw new Error('Unexpected JSON structure') } } catch (error) { console.error(`Error reading JSON: ${error.message}`) return '' } } // Usage const chart = plotFromJSON('data.json', { height: 8 }) console.log(chart) ``` -------------------------------- ### Pattern 1: Simple Single Series - Python Source: https://github.com/kroitor/asciichart/blob/master/_autodocs/usage-guide.md Generate a basic chart from an array of numbers in Python. ```python import asciichartpy temperatures = [20.5, 21.2, 22.1, 21.8, 20.9, 19.5] print(asciichartpy.plot(temperatures)) ``` -------------------------------- ### Step 2: Configuration Defaults (JavaScript) Source: https://github.com/kroitor/asciichart/blob/master/_autodocs/architecture.md Default configuration values for the JavaScript implementation. ```javascript // JavaScript defaults let offset = cfg.offset !== 'undefined' ? cfg.offset : 3 let padding = cfg.padding !== 'undefined' ? cfg.padding : ' ' let height = cfg.height !== 'undefined' ? cfg.height : range let colors = cfg.colors !== 'undefined' ? cfg.colors : [] let symbols = cfg.symbols !== 'undefined' ? cfg.symbols : defaultSymbols let format = cfg.format !== 'undefined' ? cfg.format : defaultFormatter ``` -------------------------------- ### Step 2: Configuration Defaults (Python) Source: https://github.com/kroitor/asciichart/blob/master/_autodocs/architecture.md Default configuration values for the Python implementation. ```python # Python defaults offset = cfg.get('offset', 3) height = cfg.get('height', interval) colors = cfg.get('colors', [None]) symbols = cfg.get('symbols', default_symbols) format = cfg.get('format', '{:8.2f} ') ``` -------------------------------- ### Gap Filling (Python) Source: https://github.com/kroitor/asciichart/blob/master/_autodocs/usage-guide.md Demonstrates how to handle missing data (NaN) in a series by filling with NaN, zero, or using linear interpolation before plotting. ```python import asciichartpy import math def fill_gaps(data, strategy='nan'): """ strategy: 'nan' - leave as NaN 'zero' - fill with 0 'interpolate' - linear interpolation """ if strategy == 'nan': return data if strategy == 'zero': return [0 if math.isnan(v) else v for v in data] if strategy == 'interpolate': result = [] for i, v in enumerate(data): if not math.isnan(v): result.append(v) else: # Find next non-NaN value next_val = None for j in range(i + 1, len(data)): if not math.isnan(data[j]): next_val = data[j] break # Find previous non-NaN value prev_val = None for j in range(i - 1, -1, -1): if not math.isnan(data[j]): prev_val = data[j] break # Linear interpolation if prev_val is not None and next_val is not None: result.append((prev_val + next_val) / 2) elif prev_val is not None: result.append(prev_val) elif next_val is not None: result.append(next_val) else: result.append(0) return result # Usage data = [1, 2, float('nan'), 4, 5, float('nan'), 7] print("With NaN gaps:") print(asciichartpy.plot(data)) print("\nFilled with zeros:") print(asciichartpy.plot(fill_gaps(data, 'zero'))) print("\nInterpolated:") print(asciichartpy.plot(fill_gaps(data, 'interpolate'))) ``` -------------------------------- ### Offset Minimum Value Example Source: https://github.com/kroitor/asciichart/blob/master/_autodocs/errors.md Illustrates the minimum valid value for the offset parameter and potential issues with values less than 2. ```javascript // Values less than 2 may produce incorrect output asciichart.plot(data, { offset: 1 }) // May render incorrectly asciichart.plot(data, { offset: 0 }) // May render incorrectly // Recommended: use offset >= 2 asciichart.plot(data, { offset: 2 }) // Minimum valid value ``` -------------------------------- ### Step 5: Grid Initialization (JavaScript) Source: https://github.com/kroitor/asciichart/blob/master/_autodocs/architecture.md Initializes the 2D character grid for rendering in JavaScript. ```javascript // JavaScript let width = 0 for (let i = 0; i < series.length; i++) { width = Math.max(width, series[i].length) } width = width + offset // Add offset for y-axis let result = new Array(rows + 1) // +1 for header row for (let i = 0; i <= rows; i++) { result[i] = new Array(width) for (let j = 0; j < width; j++) { result[i][j] = ' ' } } ``` -------------------------------- ### Configuration Options Source: https://github.com/kroitor/asciichart/blob/master/README.md Demonstrates how to configure the chart's appearance using a configuration object, including offset, padding, and height. ```javascript var config = { offset: 3, // axis offset from the left (min 2) padding: ' ', // padding string for label formatting (can be overridden) height: 10, // any height you want // the label format function applies default padding format: function (x, i) { return (padding + x.toFixed (2)).slice (-padding.length) } } ``` -------------------------------- ### Unit Testing Chart Output (Python) Source: https://github.com/kroitor/asciichart/blob/master/_autodocs/usage-guide.md Demonstrates how to unit test the output of asciichartpy.plot for various scenarios including constant series, multiple series, custom height, and NaN handling. ```python import asciichartpy import unittest class TestAsciichart(unittest.TestCase): def test_constant_series(self): data = [5, 5, 5, 5] result = asciichartpy.plot(data) self.assertIn('5.00', result) self.assertIn('┤', result) def test_multiple_series(self): data = [[1, 2, 3], [3, 2, 1]] result = asciichartpy.plot(data) self.assertIn('\n', result) self.assertGreater(len(result), 0) def test_custom_height(self): data = [1, 2, 3, 4, 5] result = asciichartpy.plot(data, {'height': 2}) lines = result.split('\n') self.assertLessEqual(len(lines), 3) def test_nan_handling(self): data = [1, 2, float('nan'), 4, 5] result = asciichartpy.plot(data) # Should produce output with gap self.assertGreater(len(result), 0) if __name__ == '__main__': unittest.main() ``` -------------------------------- ### Step 1: Input Normalization (Python) Source: https://github.com/kroitor/asciichart/blob/master/_autodocs/architecture.md Ensures consistent internal representation for single-series input in Python, handling all-NaN cases. ```python # Python if not isinstance(series[0], list): if all(isnan(n) for n in series): return '' else: series = [series] ``` -------------------------------- ### SeriesData Python Usage Source: https://github.com/kroitor/asciichart/blob/master/_autodocs/types.md Examples of using SeriesData in Python. ```python # Single series data = [1, 2, 3, 4, 5] asciichartpy.plot(data) # Multiple series data = [[1, 2, 3], [3, 2, 1]] asciichartpy.plot(data) # With missing values data = [1, 2, float('nan'), 4, 5] asciichartpy.plot(data) ``` -------------------------------- ### SeriesData JavaScript Usage Source: https://github.com/kroitor/asciichart/blob/master/_autodocs/types.md Examples of using SeriesData in JavaScript. ```javascript // Single series (number[]) const data = [1, 2, 3, 4, 5] asciichart.plot(data) // Multiple series (number[][]) const data = [[1, 2, 3], [3, 2, 1]] asciichart.plot(data) ``` -------------------------------- ### Using configuration options Source: https://github.com/kroitor/asciichart/blob/master/_autodocs/api-reference/asciichart.md Demonstrates using a configuration object with `height`, `offset`, and `padding` options for the `plot` function. ```javascript const data = [1, 2, 3, 4, 5, 4, 3, 2, 1] const config = { height: 4, offset: 5, padding: ' ' } console.log(asciichart.plot(data, config)) ``` -------------------------------- ### Key Components Source: https://github.com/kroitor/asciichart/blob/master/_autodocs/architecture.md A list of the main components involved in the charting process. ```text 1. Input Normalization: Converts single series to multi-series format 2. Range Calculation: Determines min/max values and scaling 3. Grid Initialization: Creates a 2D array of characters 4. Rendering Engine: Draws axis, labels, and data lines 5. Output Formatting: Joins grid into multi-line string ``` -------------------------------- ### Step 1: Input Normalization (JavaScript) Source: https://github.com/kroitor/asciichart/blob/master/_autodocs/architecture.md Ensures consistent internal representation for single-series input in JavaScript. ```javascript // JavaScript if (typeof(series[0]) == "number"){ series = [series] } ``` -------------------------------- ### No color Source: https://github.com/kroitor/asciichart/blob/master/_autodocs/api-reference/asciichart.md Example showing the `colored` function returning the character unchanged when no color is specified. ```javascript const asciichart = require('asciichart') // No color console.log(asciichart.colored('X', undefined)) ``` -------------------------------- ### Multiple Series with Colors (JavaScript) Source: https://github.com/kroitor/asciichart/blob/master/_autodocs/README.md Example of plotting multiple series with custom colors in JavaScript. ```javascript // JavaScript const series1 = [1, 2, 3, 4, 5] const series2 = [5, 4, 3, 2, 1] const config = { colors: [asciichart.blue, asciichart.green] } console.log(asciichart.plot([series1, series2], config)) ``` -------------------------------- ### Apply color Source: https://github.com/kroitor/asciichart/blob/master/_autodocs/api-reference/asciichart.md Example of using the `colored` function to apply ANSI red color to a character. ```javascript const asciichart = require('asciichart') // Apply color console.log(asciichart.colored('X', asciichart.red)) ``` -------------------------------- ### Imports Source: https://github.com/kroitor/asciichart/blob/master/_autodocs/quick-reference.md Import the necessary modules for using asciichart in JavaScript or Python. ```javascript const asciichart = require('asciichart') ``` ```python import asciichartpy # or from asciichartpy import plot, blue, green, red ``` -------------------------------- ### Scale To Desired Height Source: https://github.com/kroitor/asciichart/blob/master/README.md Example showing how to rescale the graph to a specific height by passing a height option to the plot function. ```javascript var s = [] for (var i = 0; i < 120; i++) s[i] = 15 * Math.cos (i * ((Math.PI * 8) / 120)) // values range from -15 to +15 console.log (asciichart.plot (s, { height: 6 })) // this rescales the graph to ±3 lines ``` -------------------------------- ### Custom Height and Formatting (JavaScript) Source: https://github.com/kroitor/asciichart/blob/master/_autodocs/README.md Example of customizing chart height and y-axis label formatting in JavaScript. ```javascript // JavaScript const data = [10, 20, 30, 40, 50] const config = { height: 6, padding: ' ', format: function(x) { return (' ' + x.toFixed(0) + '%').slice(-' '.length) } } console.log(asciichart.plot(data, config)) ``` -------------------------------- ### Configuring Scale and Height Source: https://github.com/kroitor/asciichart/blob/master/index.html Demonstrates configuring the chart's height and axis offset. ```javascript var width = 60 var line = "\n" + '='.repeat (width + 9) + "\n" console.log ("\nbasic\n") var s0 = new Array (width) for (var i = 0; i < s0.length; i++) s0[i] = 15 * Math.sin (i * ((Math.PI * 4) / s0.length)) console.log (asciichart.plot (s0)) console.log (line) console.log ("configuring / scale to desired height\n") var config = { padding: ' ', offset: 3, height: 10, format: function (x, i) { return (' ' + x.toFixed (2)).slice (-' '.length) } } var s = [] for (var i = 0; i < width; i++) s[i] = 15 * Math.cos (i * ((Math.PI * 8) / width)) console.log (asciichart.plot (s, config)) ``` -------------------------------- ### Pattern 1: Simple Single Series - JavaScript Source: https://github.com/kroitor/asciichart/blob/master/_autodocs/usage-guide.md Generate a basic chart from an array of numbers in JavaScript. ```javascript const asciichart = require('asciichart') const temperatures = [20.5, 21.2, 22.1, 21.8, 20.9, 19.5] console.log(asciichart.plot(temperatures)) ``` -------------------------------- ### Basic Usage Source: https://github.com/kroitor/asciichart/blob/master/index.html Demonstrates plotting a sine wave. ```javascript var s0 = new Array (120) for (var i = 0; i < s0.length; i++) s0[i] = 15 * Math.sin (i * ((Math.PI * 4) / s0.length)) console.log (asciichart.plot (s0) + '\n\n') ``` -------------------------------- ### Python Behavior: Empty Series Source: https://github.com/kroitor/asciichart/blob/master/_autodocs/errors.md Example of plotting an empty series in Python, which returns an empty string. ```python asciichartpy.plot([]) # Returns: '' ``` -------------------------------- ### Step 3: Range Calculation (JavaScript) Source: https://github.com/kroitor/asciichart/blob/master/_autodocs/architecture.md Calculates the minimum and maximum data values for scaling in JavaScript. ```javascript // JavaScript let min = (typeof cfg.min !== 'undefined') ? cfg.min : series[0][0] let max = (typeof cfg.max !== 'undefined') ? cfg.max : series[0][0] for (let j = 0; j < series.length; j++) { for (let i = 0; i < series[j].length; i++) { min = Math.min(min, series[j][i]) max = Math.max(max, series[j][i]) } } ```