# plot

URL: https://tuios.dev/docs/libraries/plot

> Bar, line, area, sparkline, gauge, histogram, heatmap, pie, mirrored and inline bar charts and a world map as terminal cells, in braille, block elements or ASCII, with theme roles in place of colours.

`tuios.dev/plot` draws charts as terminal cells. It has eleven chart kinds: bar (horizontal and vertical), line, area, sparkline, gauge, histogram, heatmap, pie (a donut or a full disc), mirrored bars, inline bars for table cells, and a world map. It holds no colour and writes no escape sequence. Each cell has a role, and your program picks the colour.

![Every chart kind drawn by plot through loom: stat tiles with sparklines, gauges, horizontal bars with values, columns with an axis and a legend, a two-series line, an area, a heatmap, a donut with its legend, a histogram and sparklines](https://tuios.dev/libs/plot/hero.webp)

*Every chart kind in one TML document, drawn through loom. Click to open it at full size.*

The API reference is on [pkg.go.dev](https://pkg.go.dev/tuios.dev/plot).

## Quickstart

```bash
go get tuios.dev/plot
```

```go title="main.go"
package main

import (
	"fmt"

	"tuios.dev/plot"
)

func main() {
	bar := plot.Bar{
		Values:     []float64{6.2, 4.8, 3.1},
		Labels:     []string{"session", "app", "vt"},
		Horizontal: true,
	}
	g := bar.Draw(30, 3, plot.Blocks)

	// plot holds no colour. Your program maps each role to one, here an
	// ANSI colour, so the chart follows the terminal's theme.
	sgr := map[plot.Role]string{plot.Series1: "34", plot.Mute: "90"}
	for y := 0; y < g.H; y++ {
		for x := 0; x < g.W; x++ {
			c := g.At(x, y)
			if c.Width == 0 {
				continue // the second cell of a wide glyph
			}
			text := c.Text
			if text == "" {
				text = " "
			}
			if code, ok := sgr[c.Role]; ok {
				text = "\x1b[" + code + "m" + text + "\x1b[0m"
			}
			fmt.Print(text)
		}
		fmt.Println()
	}
}

```

![The output of the program: three horizontal bars for session, app and vt with their values, in the terminal's blue](https://tuios.dev/libs/plot/quickstart.webp)

The program maps two roles to ANSI colours, so the chart takes the colours of the terminal's theme.

## The tplot command

`tplot` draws a chart from CSV, TSV, JSON or plain numbers, from a file or standard input. It needs Go 1.25 or newer:

```bash
go install tuios.dev/plot/cmd/tplot@latest
```

Each tuios release from v0.11.0 also carries a `tplot` archive for Linux, macOS, Windows and FreeBSD, on x86\_64 and arm64. Download it from the [releases page](https://github.com/Gaurav-Gosain/tuios/releases), or install it with a package manager:

```bash
brew install --cask gaurav-gosain/tap/tuios-plot   # macOS and Linux
yay -S tuios-plot-bin                              # Arch Linux, from the AUR
```

```bash
printf 'session,6.2\napp,4.8\nvt,3.1\n' | tplot
seq 1 50 | awk '{print sin($1/5)}' | tplot --kind line
tplot --kind pie shares.csv
echo '{"US": 410, "DE": 120, "SG": 14}' | tplot --kind map --log
```

- A text column gives the labels. Each column of numbers is a series. A first row of names is a header.
- JSON can be `[1, 2, 3]`, `{"a": 1}`, `{"rx": [1, 2], "tx": [3, 4]}`, rows as arrays, or rows as objects.
- Without `--kind`, a few labelled values draw as bars, and other data as a line chart. The kinds are `bar`, `column`, `line`, `area`, `spark`, `hist`, `heatmap`, `pie`, `donut`, `gauge` and `map`.
- The colours are the 16 ANSI colours, so the chart takes the colours of the terminal's theme. Without colour, a chart that needs colour to tell its parts apart uses ASCII marks.
- `tplot -h` lists every flag.

The command is `tplot`, because GNU plotutils already has a `plot` command. The Homebrew cask and the AUR package keep the library's name.

## How it works

- A chart draws into a grid of the size you give it. The grid is always that size, and each row is exactly that wide.
- Each cell holds one grapheme, its width, a role such as `series1` or `mute`, and a background role for half blocks.
- `g.At(x, y)` gives one cell. `g.String()` gives the text with no colours.
- Your program maps each role to a colour at the colour depth of the terminal. [loom](https://tuios.dev/docs/libraries/loom) does this with its `Palette`.

## Chart kinds

Each picture is the code above it. `m` is the mode, such as `plot.Braille`. Helpers such as `wave` make the sample data. The pictures colour the roles with the theme of this site.

### Bar

```go
bar := plot.Bar{
	Values:     []float64{6.2, 4.8, 3.1, 1.4, 0.9},
	Labels:     []string{"session", "app", "vt", "tape", "config"},
	Horizontal: true,
	Guide:      true, // a dotted line to the value
}
grid := bar.Draw(48, 5, m)

```

![Five horizontal bars with labels at the left, dotted guides and values at the right](https://tuios.dev/libs/plot/bar.webp)

Horizontal bars keep a value column that never clips. The labels give way first.

### Columns

```go
cols := plot.Bar{
	Values: []float64{41, 39, 44, 40, 52, 47, 38, 45, 49, 43, 41, 50},
	Labels: []string{"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"},
	Axis:   true, // tick labels, a base line, and x labels
	Role:   plot.Series2,
}
grid := cols.Draw(48, 9, m)

```

![Twelve columns, one per month, with tick labels at the left and the first, middle and last month under the base line](https://tuios.dev/libs/plot/columns.webp)

Columns whose values all sit far above zero start from a round base under the smallest value. The axis labels that base, so the chart says where it starts.

### Line

```go
line := plot.Line{
	Series: []plot.Series{
		{Name: "p50", Values: wave(40, 20, 4)},
		{Name: "p95", Values: wave(40, 34, 9)},
	},
	Labels: hours(40),
	Axis:   true,
}
// The legend goes on the first row, the chart under it.
grid := plot.NewGrid(56, 11)
plot.DrawLegend(grid, 6, 0, line.Legend(), m)
paste(grid, line.Draw(56, 10, m), 0, 1)

```

![Two lines of braille dots, p50 and p95, with a legend above, tick labels at the left and times under the axis](https://tuios.dev/libs/plot/line.webp)

A line with more values than cells is reduced with largest triangle three buckets, which keeps the peaks. `Line.Legend` returns the legend items, and `DrawLegend` draws them.

### Area

```go
area := plot.Line{
	Series: []plot.Series{{Name: "memory", Values: wave(48, 120, 30), Role: plot.Series3}},
	Fill:   true, // an area chart
	Axis:   true,
	Labels: hours(48),
}
grid := area.Draw(56, 9, m)

```

![A filled area chart of memory with an axis from 0 to 200](https://tuios.dev/libs/plot/area.webp)

### Sparkline

```go
spark := plot.Sparkline{Values: []float64{3, 5, 4, 8, 6, 9, 7, 12, 10, 14, 11, 16, 13, 18, 15, 21}}
grid := spark.Draw(16, 1, m)

```

![A one-row trend of sixteen values in eighth blocks, rising from left to right](https://tuios.dev/libs/plot/sparkline.webp)

On more than one row, a sparkline is a column chart with no axis.

### Gauge

```go
cpu := plot.Gauge{Value: 43, Max: 100}
pass := plot.Gauge{Value: 0.988, Role: plot.Success, Style: plot.GaugeBlocks}
grid := plot.NewGrid(40, 3)
paste(grid, cpu.Draw(40, 1, m), 0, 0)
paste(grid, pass.Draw(40, 1, m), 0, 2)

```

![A thin line gauge at 43 percent, and a thick green block gauge at 98.8 percent](https://tuios.dev/libs/plot/gauge.webp)

### Histogram

```go
hist := plot.Histogram{
	Values: latencies(400), // request times in ms
	Bins:   24,
	Format: func(v float64) string { return fmt.Sprintf("%.0fms", v) },
}
grid := hist.Draw(52, 9, m)

```

![A histogram of request times with most values near 100 ms and a long tail to the right, with counts at the left and the range under it](https://tuios.dev/libs/plot/histogram.webp)

A histogram has at most one bin per cell and 1000 bins.

### Heatmap

```go
heat := plot.Heatmap{
	Values:    commits(), // 7 rows of 24 hours
	RowLabels: []string{"Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"},
	ColLabels: hoursOfDay(), // 00h to 23h
}
grid := heat.Draw(56, 11, m)

```

![A heatmap of a week of commits by hour, busy in the afternoon on weekdays, with day labels, hour labels and a five-step scale](https://tuios.dev/libs/plot/heatmap.webp)

The heat roles `heat1` to `heat5` are a ramp from low to high. A heatmap uses whole cells, or half blocks when the rows do not fit.

### Pie

```go
pie := plot.Pie{
	Values: []float64{900, 240, 120, 60},
	Labels: []string{"Go", "Shell", "TOML", "Nix"},
	Donut:  true,
	Aspect: 2.0, // a cell's height over its width
}
grid := pie.Draw(40, 9, m)

```

![A donut of four languages with a legend of their shares: Go 68 percent, Shell 18, TOML 9 and Nix 5](https://tuios.dev/libs/plot/pie.webp)

A pie is a disc of half-block pixels. Set `Aspect` to the height of a cell over its width, and the disc is round. A pie draws 12 slices, and folds the rest into one called "other".

### Mirrored bars

```go
net := plot.Mirror{
	Up:     plot.Series{Name: "▼ download", Values: rx, Role: plot.Series3},
	Down:   plot.Series{Name: "▲ upload", Values: tx, Role: plot.Series5},
	Peaks:  true, // • 120M over the highest column of each half
	Stats:  true, // peak · avg · Σ in each corner row
	Format: plot.Compact,
}
grid := net.Draw(56, 10, m)

```

![Download as green dot columns above a baseline and upload as pink dot columns below it, a peak marker with its value over each half, and peak, average and total in the corners](https://tuios.dev/libs/plot/mirror.webp)

`Mirror` draws two series around one baseline, such as download and upload, tokens in and out, or reads and writes. Each value is one column of braille dots, and the newest value is at the right edge. Each half scales to its own peak, and `Shared` gives both one scale. The columns are graded by height with faded roles, such as `series3/2`. A column with no value shows a dotted track on the baseline.

Credit: the idea and the look come from [iptop](https://github.com/franlol/iptop) by franlol (MIT).

### Inline bars

```go
hosts := []string{"fra1.example.net", "ams3.example.net", "nyc2.example.net", "sgp1.example.net"}
rates := []float64{30e6, 12.4e6, 3.1e6, 840e3}
grid := plot.NewGrid(44, len(hosts))
for i, h := range hosts {
	grid.Text(0, i, h, plot.Fg, false)
	bar := plot.InlineBar{Value: rates[i], Max: rates[0], Track: true}
	paste(grid, bar.Draw(16, 1, m), 18, i) // the bar column
	grid.TextRight(44, i, plot.Compact(rates[i]), plot.Info, false)
}

```

![Four hosts in a table, each with a thin share bar on a track and its rate at the right](https://tuios.dev/libs/plot/inline.webp)

`InlineBar` is a bar one row high for a table cell. It draws no label, so the cell next to it can hold the value. By default it is a lower half block, exact to half a cell, so the bars of a table stay apart. `Style: plot.BarBlocks` fills the row with eighth blocks. Give every row the same `Max`, so the bars compare.

```go
services := []string{"https", "quic", "ssh", "dns", "http"}
down := []float64{24e6, 6e6, 40e3, 900, 1.2e6}
up := []float64{1.1e6, 3.2e6, 220e3, 2.4e3, 9e6}
grid := plot.NewGrid(30, len(services))
for i, s := range services {
	grid.Text(0, i, s, plot.Fg, false)
	bar := plot.DivergingBar{
		Left: down[i], Right: up[i], Max: 24e6, // one Max for every row
		LeftRole: plot.Series3, RightRole: plot.Series5, Track: true,
	}
	paste(grid, bar.Draw(23, 1, m), 7, i)
}

```

![Five services, each with a download bar growing left and an upload bar growing right from a dotted centre mark](https://tuios.dev/libs/plot/diverging.webp)

`DivergingBar` grows left from a centre mark for `Left` and right for `Right`.

Credit: the idea and the look come from [iptop](https://github.com/franlol/iptop) by franlol (MIT).

### World map

```go
world := plot.Map{
	Values: map[string]float64{ // by ISO 3166-1 alpha-2 code
		"US": 410e6, "DE": 120e6, "NL": 95e6, "GB": 60e6, "CA": 35e6,
		"FR": 22e6, "JP": 18e6, "SG": 14e6, "IN": 9e6, "BR": 6e6,
		"AU": 2.5e6, "CN": 1.2e6, "ZA": 400e3,
	},
	Log:     true, // spread values that span orders of magnitude
	Markers: []plot.Marker{{Lat: 52.37, Lon: 4.9}, {Lat: 1.35, Lon: 103.82}},
}
_, rows := world.Fit(72, 40, m) // the rows the map takes at this width
grid := plot.NewGrid(72, rows+1)
paste(grid, world.Draw(72, rows, m), 0, 0)
plot.DrawLegend(grid, 0, rows, world.Legend(m), m) // right under the map

```

![A world map in braille dots, with thirteen countries shaded by traffic on a log scale, two host markers, and a legend of five shades right under the map](https://tuios.dev/libs/plot/map.webp)

`Map` draws the land in the `track` role, and fills each country with a value with a shade of `Ramp`, `heat1` to `heat5` by default. Countries are ISO 3166-1 alpha-2 codes. The projection is equirectangular, from 180° W to 180° E and from 84° N to 60° S. The map keeps its true shape and is centred, and fills a box at most a tenth past that shape. `Fit` returns the cells it takes, so the legend can go right under it. Codes are case-blind, and when two keys name one country the larger value counts. A country that is the larger part of no cell, such as Singapore, takes the cell it covers most, or the nearest free cell, and shows only when it has a value. `Legend` writes `>=` in ASCII. A program that draws no map does not link the map data.

Credit: the idea and the look come from [iptop](https://github.com/franlol/iptop) by franlol (MIT).

Map data: [Natural Earth](https://www.naturalearthdata.com/) 1:50m Admin 0 Countries, version 5.1.1, which is in the public domain.

## Modes

A mode sets the glyphs a chart can use. Use the best mode that the terminal and its font can show.

| Mode      | Lines and areas               | Bars, sparklines, gauges |
| --------- | ----------------------------- | ------------------------ |
| `Braille` | Braille dots, 2 by 4 per cell | Eighth blocks            |
| `Blocks`  | Eighth blocks                 | Eighth blocks            |
| `ASCII`   | `*` and `:`                   | `#`, `-` and `[ ]`       |

The same line chart, sparkline and gauge in each mode:

![In braille: two smooth dotted lines, a sparkline and a thin gauge](https://tuios.dev/libs/plot/mode-braille.webp)

*Braille*

![In blocks: two lines drawn as stepped eighth blocks, a sparkline and a thin gauge](https://tuios.dev/libs/plot/mode-blocks.webp)

*Blocks*

![In ASCII: one line drawn with asterisks and one with plus signs, a sparkline of ASCII marks, and a gauge of hash signs in brackets](https://tuios.dev/libs/plot/mode-ascii.webp)

*ASCII*

In ASCII, each series, slice and heat level has its own mark, so they stay apart without colour.

## Theme roles

A role names a colour. The names are the TML roles, plus `track` for the empty part of a gauge or a bar, and `heat1` to `heat5`. `plot.Fade(role, k)` names a role faded `k` steps toward the ground, such as `series1/2`, and `Role.Faded` splits it. Draw fade `k` as the base colour mixed about `k` fifths toward the ground. `plot.SeriesRole(i)` gives the role of series i, and cycles after six.

![Every role a chart uses, each written in its own colour: fg, dim, mute, edge, track, the accent and status roles, series1 to series6, and heat1 to heat5](https://tuios.dev/libs/plot/roles.webp)

## How do I

- **Fix the range of a chart?** Set `Min` and `Max`. Both 0 means automatic.
- **Format the values?** Set `Format`, such as `plot.Compact` or your own function.
- **Draw a legend?** Call `DrawLegend(grid, x, y, chart.Legend(), mode)`, and give it a row of its own.
- **Colour one bar?** Set `Roles`, one role per bar.
- **Draw a chart in a TML document?** Use the chart components through [loom](https://tuios.dev/docs/libraries/loom), such as `<bar data="state.rows" x="pkg" y="secs"/>`.
- **Print a chart with no colour?** Call `grid.String()`.

## API overview

| Name                                                                                                                                                                               | Does                                                 |
| ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------- |
| [`Bar`](https://pkg.go.dev/tuios.dev/plot#Bar)                                                                                                                                     | Horizontal bars or columns.                          |
| [`Line`](https://pkg.go.dev/tuios.dev/plot#Line), [`Series`](https://pkg.go.dev/tuios.dev/plot#Series)                                                                             | A line chart, or an area chart with `Fill`.          |
| [`Sparkline`](https://pkg.go.dev/tuios.dev/plot#Sparkline)                                                                                                                         | A one-row trend.                                     |
| [`Gauge`](https://pkg.go.dev/tuios.dev/plot#Gauge)                                                                                                                                 | A value against a maximum.                           |
| [`Histogram`](https://pkg.go.dev/tuios.dev/plot#Histogram)                                                                                                                         | Counts of values in bins.                            |
| [`Heatmap`](https://pkg.go.dev/tuios.dev/plot#Heatmap)                                                                                                                             | A grid of values as shades.                          |
| [`Pie`](https://pkg.go.dev/tuios.dev/plot#Pie)                                                                                                                                     | Shares of a whole, as a donut or a disc.             |
| [`Mirror`](https://pkg.go.dev/tuios.dev/plot#Mirror)                                                                                                                               | Two series above and below one baseline.             |
| [`InlineBar`](https://pkg.go.dev/tuios.dev/plot#InlineBar), [`DivergingBar`](https://pkg.go.dev/tuios.dev/plot#DivergingBar)                                                       | One-row bars for a table cell.                       |
| [`Map`](https://pkg.go.dev/tuios.dev/plot#Map), [`Marker`](https://pkg.go.dev/tuios.dev/plot#Marker)                                                                               | A world map with countries shaded by value.          |
| [`Grid`](https://pkg.go.dev/tuios.dev/plot#Grid), [`Cell`](https://pkg.go.dev/tuios.dev/plot#Cell), [`Role`](https://pkg.go.dev/tuios.dev/plot#Role)                               | The output of a chart.                               |
| [`Fade`](https://pkg.go.dev/tuios.dev/plot#Fade)                                                                                                                                   | A role faded toward the ground, such as `series1/2`. |
| [`Mode`](https://pkg.go.dev/tuios.dev/plot#Mode)                                                                                                                                   | `Braille`, `Blocks` or `ASCII`.                      |
| [`DrawLegend`](https://pkg.go.dev/tuios.dev/plot#DrawLegend), [`Compact`](https://pkg.go.dev/tuios.dev/plot#Compact), [`Downsample`](https://pkg.go.dev/tuios.dev/plot#Downsample) | Helpers.                                             |

## Rules

- Every chart is total. NaN and infinite values count as missing. Empty data draws an empty grid.
- Sizes that a caller could pass unchecked are bounded: a grid is at most 4096 cells a side, and a line draws at most 64 series.
- Labels are cut with an ellipsis to fit. Control characters are dropped, and invalid UTF-8 shows as `?`.

## Where it fits

- [loom](https://tuios.dev/docs/libraries/loom) uses plot to draw the TML chart components, and maps the roles with its palette.
- tuios draws the charts of `tuios tml show` surfaces with it.
- Widths come from `charmbracelet/x/ansi`, the same width functions that tuios uses. The package imports nothing else outside the standard library.

## Versions

The module is at v0. The API can change between minor versions. Its tags have the folder name as a prefix, such as `plot/v0.1.0`. The source is in the [plot folder](https://github.com/Gaurav-Gosain/tuios/tree/main/plot) of the tuios repository, under the MIT licence.
