Files
text_graph/README.md
Your Name 311c9e1e6d .
2025-10-17 08:22:55 -04:00

348 lines
9.8 KiB
Markdown

# ASCII Bar Chart
A dynamic, real-time ASCII-based vertical bar chart library that renders beautiful terminal-style visualizations using monospaced characters. Perfect for dashboards, monitoring tools, or any application that needs lightweight, text-based data visualization.
## Features
- 📊 **Real-time Updates**: Add data points dynamically and watch the chart animate
- 📏 **Auto-scaling**: Y-axis automatically adjusts to show min/max values
- 🔤 **Monospaced Rendering**: Uses 'X' characters in Courier font for clean visualization
- 📱 **Responsive**: Automatically adjusts font size to fit container width
- 🏷️ **Customizable Labels**: Add title, X-axis, and vertical Y-axis labels
- 🎯 **Scrolling Data**: Old data automatically scrolls off as new data arrives
- 🎨 **Terminal Theme**: Retro green-on-black aesthetic
- ⏱️ **Time Bin Mode**: Aggregate data into configurable time bins (e.g., count events per 10-second window)
- 📈 **Multiple X-Axis Formats**: Display elapsed time, bin numbers, timestamps, or time ranges
- 👁️ **Active Bin Indicator**: Visual marker shows which bin is currently accumulating data
## Demo
```
Real-Time Data Visualization
486 | X
484 | X X
482 | X X X
481 | X X X
479 | X X X X X X X
477 | X X X X X X X X
475 | X X X X X X X X X
C 473 | X X X X X X X X X X
o 472 | X X X X X X X X X X X X X
u 470 | X X X X X X X X X X X X X X X
n 468 | X X X X X X X X X X X X X X X X
t 466 | X X X X X X X X X X X X X X X X X X
465 | X X X X X X X X X X X X X X X X X X X X
463 | X X X X X X X X X X X X X X X X X X X X X X X
461 | X X X X X X X X X X X X X X X X X X X X X X X
459 | X X X X X X X X X X X X X X X X X X X X X X X X
457 | X X X X X X X X X X X X X X X X X X X X X X X X X X X X X
456 | X X X X X X X X X X X X X X X X X X X X X X X X X X X X X
454 | X X X X X X X X X X X X X X X X X X X X X X X X X X X X X
452 | X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X
+------------------------------------------------------------
453 458 463 468 473 478
Time (seconds)
```
## Installation
Simply include the JavaScript file in your HTML:
```html
<script src="text_graph.js"></script>
```
## Quick Start
```html
<!DOCTYPE html>
<html>
<head>
<style>
#chart {
font-family: 'Courier New', monospace;
background: #000;
color: #0f0;
padding: 20px;
white-space: pre;
}
</style>
</head>
<body>
<div id="chart"></div>
<script src="text_graph.js"></script>
<script>
// Create chart
const chart = new ASCIIBarChart('chart', {
maxHeight: 20,
maxDataPoints: 30,
title: 'My Chart',
xAxisLabel: 'Time',
yAxisLabel: 'Value'
});
// Add data
chart.addValue(15);
chart.addValue(23);
chart.addValue(18);
</script>
</body>
</html>
```
## API Reference
### Constructor
```javascript
new ASCIIBarChart(containerId, options)
```
Creates a new ASCII bar chart instance.
**Parameters:**
| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `containerId` | string | Yes | ID of the HTML element to render the chart in |
| `options` | object | No | Configuration options (see below) |
**Options:**
| Option | Type | Default | Description |
|--------|------|---------|-------------|
| `maxHeight` | number | `20` | Maximum height of the chart in rows |
| `maxDataPoints` | number | `30` | Maximum number of columns before old data scrolls off |
| `title` | string | `''` | Chart title (displayed centered at top) |
| `xAxisLabel` | string | `''` | X-axis label (displayed centered at bottom) |
| `yAxisLabel` | string | `''` | Y-axis label (displayed vertically on left side) |
| `autoFitWidth` | boolean | `true` | Automatically adjust font size to fit container width |
| `useBinMode` | boolean | `false` | Enable time bin mode for data aggregation |
| `binDuration` | number | `4000` | Duration of each time bin in milliseconds (4 seconds default) |
| `xAxisLabelFormat` | string | `'elapsed'` | X-axis label format: `'elapsed'`, `'bins'`, `'timestamps'`, `'ranges'` |
**Example:**
```javascript
const chart = new ASCIIBarChart('my-chart', {
maxHeight: 25,
maxDataPoints: 50,
title: 'Server Response Times',
xAxisLabel: 'Request Number',
yAxisLabel: 'Milliseconds',
autoFitWidth: true
});
```
### Methods
#### `addValue(value)`
Adds a new data point to the chart.
**Parameters:**
- `value` (number): The numeric value to add to the chart
**Example:**
```javascript
chart.addValue(42);
chart.addValue(38);
chart.addValue(45);
```
#### `clear()`
Clears all data from the chart and resets it to initial state.
**Example:**
```javascript
chart.clear();
```
## Features in Detail
### Auto-Scaling Y-Axis
The Y-axis automatically scales to show the full range of your data:
- Minimum value always displays as one 'X' at the bottom
- Maximum value uses the full chart height
- Y-axis labels show actual data values, not just row numbers
- Dynamically adjusts as new data arrives
### Scrolling Data Window
When the number of data points exceeds `maxDataPoints`:
- Old data automatically scrolls off the left side
- X-axis labels update to show actual data point numbers
- Maintains a sliding window of the most recent data
### Responsive Font Sizing
When `autoFitWidth` is enabled:
- Font size automatically adjusts to fill container width
- Responds to window resizing in real-time
- Maintains readability with min/max font size bounds (4px-20px)
- Uses ResizeObserver for efficient updates
### Vertical Y-Axis Label
The Y-axis label is rendered vertically, one character per row:
```
V
a
l
u
e
```
## Advanced Usage
### Real-Time Data Streaming
```javascript
const chart = new ASCIIBarChart('chart', {
maxHeight: 20,
maxDataPoints: 60,
title: 'Live Metrics'
});
// Simulate real-time data
setInterval(() => {
const value = Math.random() * 100;
chart.addValue(value);
}, 1000);
```
### Integration with Data Sources
```javascript
// WebSocket example
const ws = new WebSocket('ws://your-server.com/data');
ws.onmessage = (event) => {
const data = JSON.parse(event.data);
chart.addValue(data.value);
};
// API polling example
async function fetchAndUpdate() {
const response = await fetch('/api/metrics');
const data = await response.json();
chart.addValue(data.currentValue);
}
setInterval(fetchAndUpdate, 5000);
```
### Multiple Charts
```javascript
const cpuChart = new ASCIIBarChart('cpu-chart', {
title: 'CPU Usage %',
yAxisLabel: 'Percent'
});
const memChart = new ASCIIBarChart('mem-chart', {
title: 'Memory Usage MB',
yAxisLabel: 'Megabytes'
});
// Update both charts
cpuChart.addValue(45);
memChart.addValue(2048);
```
## Time Bin Mode
Time bin mode aggregates data points into time-based bins, showing the count of events within each time window. This is useful for visualizing event frequency over time.
### Basic Time Bin Usage
```javascript
const chart = new ASCIIBarChart('chart-container', {
useBinMode: true,
binDuration: 10000, // 10-second bins
xAxisLabelFormat: 'elapsed', // Show elapsed time
title: 'Event Counter',
yAxisLabel: 'Count'
});
// Each addValue() increments the count in the current active bin
chart.addValue(1); // Bin 1: count = 1
chart.addValue(1); // Bin 1: count = 2
// ... after 10 seconds, automatically creates Bin 2
```
### X-Axis Label Formats
- **`'elapsed'`** (default): Shows elapsed seconds since chart start ("0s", "10s", "20s")
- **`'bins'`**: Shows bin numbers ("Bin 1", "Bin 2", "Bin 3")
- **`'timestamps'`**: Shows actual timestamps ("103000", "103010", "103020")
- **`'ranges'`**: Shows time ranges ("0-10s", "10-20s", "20-30s")
### Visual Indicators
- **X**: Regular bin data
- **O**: Active bin currently accumulating data
- Chart automatically scales when bin counts exceed chart height
### Manual Bin Rotation
```javascript
// Force rotation to new bin (useful for testing)
chart.rotateBin();
```
## Styling
The chart uses monospaced fonts and renders as plain text. Style the container element:
```css
#chart-container {
font-family: 'Courier New', Courier, monospace;
background-color: #000;
color: #0f0;
padding: 20px;
border: 2px solid #0f0;
border-radius: 5px;
white-space: pre;
overflow-x: auto;
font-size: 12px;
line-height: 1.0;
}
```
## Browser Support
- Modern browsers with ES6 support
- ResizeObserver API (for auto-fit width feature)
- All major browsers: Chrome, Firefox, Safari, Edge
## License
MIT License - feel free to use in your projects!
## Examples
See [`text_graph.html`](text_graph.html) for a complete working example with:
- Interactive controls (Start/Stop/Reset)
- Configurable settings (update interval, max columns, chart height)
- Test data generator with increasing trend
- Full styling and layout
## Contributing
Contributions welcome! This is a simple, focused library for ASCII-based charting.
## Changelog
### v1.0.0
- Initial release
- Dynamic vertical bar charts
- Auto-scaling Y-axis
- Scrolling data window
- Responsive font sizing
- Customizable labels and titles