Files
Cactidocumentation/Card-API-Charts.md
T
TheWitnessandCopilot 1f5a67262b docs: [1.2.x] add a Card API chart reference with a runnable gallery (#338)
* docs: [1.2.x] add a Card API chart reference with a runnable gallery

Add Card-API-Charts.md, a reference for all sixteen Card API chart
helpers in lib/html.php: what each chart is for, its signature, an
example and a screenshot. It covers the rules every helper shares
(escaping, translation, unknown and non-finite samples, severity and
series colours) and how a third-party plugin uses the charts: bundling
card-widgets.css behind a file_exists() gate with a pinned hash, calling
a helper behind function_exists(), or writing the markup directly, as the
supported plugins do. A final section builds an Intropage panel from the
charts, next to the existing panel registration walkthrough.

The example plugin (resources/carddemo.zip) gains charts.php, a gallery
of every example from charts-examples.php, and a second Intropage panel,
Traffic overview. Every code block on the page is that source verbatim,
and the screenshots were taken from it running in Cacti 1.2.x and
develop. Card-API.md, Plugin-Intropage.md and the index link the new page.

Documents Cacti/cacti#9322 and Cacti/cacti#9323.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Signed-off-by: TheWitness <thewitness@cacti.net>

* docs: say exactly how the chart helpers draw unknown values

Review follow-up. Trend series skip unknown samples, but elsewhere U,
empty strings and NULL count as 0, and only NAN or INF leave a bullet or
box plot part out; values shown as text are printed as given, so callers
must supply "No data" themselves. The multi-line chart joins across a
skipped sample instead of drawing a break.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Signed-off-by: TheWitness <thewitness@cacti.net>

* docs: tell fill percentages apart from the statistic change

Review follow-up: only percentages that fill a chart are clamped to
0-100; the card_stat() $delta is a signed change shown as given.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Signed-off-by: TheWitness <thewitness@cacti.net>

---------

Signed-off-by: TheWitness <thewitness@cacti.net>
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-12-05 15:57:01 -05:00

20 KiB

Card API Chart Reference

Cacti's Card API includes sixteen PHP helpers that draw a chart as plain HTML and inline SVG. They need no JavaScript and no charting library, so a chart renders the same in a plugin page, a dashboard card, a table cell or an Intropage panel. This page shows what each chart is for, how to call it and how to use the charts from a third-party plugin, including one that must still run on an older Cacti.

Every Card API chart, rendered by the example plugin

For the card grid, its controls and saving a layout, see the Card API Developer Guide. That guide also shows how to publish a card in Intropage.

Where the charts come from

Part Location
PHP helpers lib/html.php, one card_*() function per chart
Styles include/css/card-widgets.css, loaded by the standard page header
Colours The --cc-sev-* and --cc-series-* custom properties

The gauge, bar, statistic, stacked bar, bullet and sparkline helpers came with the original Card API. The distribution, tiles, mini bar, pill, donut, ring, box plot, column, multi-line and waffle helpers, the gauge ticks and the statistic's change indicator were added for Cacti 1.2.32 and 1.3.0 by Cacti/cacti#9322 (1.2.x) and Cacti/cacti#9323 (develop). The helpers and the stylesheet are identical on both branches.

Try the examples

Every example on this page is a function in charts-examples.php in the example plugin. Install it as described in Build the example plugin, sign in with View Card API Example and open plugins/carddemo/charts.php. The page draws each chart in its own card, so you can compare your Cacti with the images here. On a Cacti without a helper, its card says so instead of failing.

The screenshots on this page were taken from that page and from the example's Intropage panel, installed in Cacti 1.2.x and develop.

Rules that apply to every chart

  • Print the result. Every helper returns an HTML string. Print it once, or concatenate several into a card body or an Intropage panel.
  • Pass plain text. Labels, captions and values are escaped by the helper: visible text with html_escape() and attributes such as title and aria-label with html_escape_attr(). Translate labels with __() before passing them.
  • Format numbers yourself. A value shown as text, such as '12.4 ms', is printed as given. A percentage that fills a chart (gauge, ring, bar, mini bar, waffle, segment) is a number from 0 to 100 and is clamped to that range. The statistic's $delta is different: a signed percentage change, such as -3 or 150, shown as given to one decimal place.
  • Know how unknown values are drawn. A trend series (sparkline, multi-line and column charts) skips RRD's U, empty strings, NULL, other non-numeric values, NAN and INF. Elsewhere U, empty strings, NULL and other non-numeric values count as 0. A non-finite value (NAN or INF) counts as 0 for a gauge, ring, bar or waffle, and leaves its part out of a bullet or box plot. Coordinates never contain nan, and finite values far apart, such as -1e308 and 1e308, still plot.
  • Handle missing measurements yourself. A value shown as text, such as a statistic, a tile value or a distribution row's display text, is printed as given. Pass text such as No data when there is no sample, and pass NAN to a bullet or box plot for a part that should be left out rather than drawn at 0.
  • Name every chart. Trend charts, the waffle and the mini bar take an accessible name. Make it say what is measured and over what period.
  • Do not rely on colour. Pair a coloured state with words, such as a legend, a tile label or the statistic's Better and Worse text.

Severity and series colours

Most helpers take a severity that colours the chart. card_severity() accepts these tokens:

Token passed Colour Custom property
up, good Green --cc-sev-up
warn, warning, recovering Orange --cc-sev-warn
down, bad, error Red --cc-sev-down
anything else, or omitted Neutral grey

The multi-line chart, and donut segments given no severity, use the series palette --cc-series-1 to --cc-series-6 in order. Its defaults are the Okabe-Ito colour-blind-safe colours. Set any of these properties on a grid, a card or the theme to retint the charts.

Single values

Gauge

card_gauge($percent, $center_label, $sub_label = '', $severity = 'none', $ticks = [])

A semicircle filled from 0 to 100. $ticks marks percentages across the arc, such as warning and alert thresholds or the window's minimum and maximum. A gauge at 0% draws no arc.

// UPS load, with ticks at the 80% warning and 95% alert thresholds
return card_gauge(68, '68%', __('UPS load', 'carddemo'), 'warn', [80, 95]);

Gauge at 68% with two threshold ticks

Progress ring

card_ring($percent, $center_label, $sub_label = '', $severity = 'none')

A full circle filled clockwise from the top. The stylesheet draws it from the --cc-pct custom property, so it is the one chart a plugin can write as markup on a Cacti that has the stylesheet but not the helper. See Write the markup yourself.

return card_ring(42, '42%', __('CPU', 'carddemo'), 'up');

Progress ring at 42%

Usage bar

card_bar($percent, $label = '', $severity = 'none')

A horizontal bar for one percentage, with an optional caption beneath it.

return card_bar(42, __('/var: 42% of 20 GB used', 'carddemo'), 'up');

Usage bar at 42%

Mini bar

card_minibar($percent, $label = '', $severity = 'none')

A thin inline bar sized for a table cell. $label becomes its tooltip and accessible name. Keep the number in a neighbouring cell so it can be read and sorted.

$rows = [
    ['/', 87, 'warn'],
    ['/var', 42, 'up'],
    ['/home', 96, 'down'],
];

$html = '<table class="cactiTable"><tbody>';

foreach ($rows as [$mount, $used, $severity]) {
    $text  = __('%d%% used', $used, 'carddemo');
    $html .= '<tr><td>' . html_escape($mount) . '</td><td>' . card_minibar($used, $text, $severity) . '</td><td>' . html_escape($text) . '</td></tr>';
}

return $html . '</tbody></table>';

Three mini bars in a table

Statistic with change

card_stat($value, $label, $delta = null, $higher_is_better = true)

A large value with a caption. Pass $delta, a change in percent, to add an arrow for its direction. The colour, a tooltip and text for screen readers say whether that change is better or worse. Set $higher_is_better to false for measurements such as latency or errors. Without $delta the markup is the same as before the change indicator existed.

// latency rose 6.2%, and for latency a rise is worse
return card_stat('12.4 ms', __('Average latency', 'carddemo'), 6.2, false);

Average latency with a red +6.2% change

Status pills

card_pill($text, $severity = 'none')

A small coloured label for a state, inline with text or in a table.

return card_pill(__('Online', 'carddemo'), 'up') . ' '
    . card_pill(__('On battery', 'carddemo'), 'warn') . ' '
    . card_pill(__('Replace battery', 'carddemo'), 'down') . ' '
    . card_pill(__('Self test pending', 'carddemo'));

Four status pills

Status and proportions

Status tiles

card_tiles($tiles)

A grid of counts. Each tile is an array of value, label and an optional severity that colours its border and value. The grid fits as many tiles on a line as the card allows.

return card_tiles([
    ['value' => 42, 'label' => __('Up', 'carddemo'), 'severity' => 'up'],
    ['value' => 3, 'label' => __('Recovering', 'carddemo'), 'severity' => 'recovering'],
    ['value' => 2, 'label' => __('Down', 'carddemo'), 'severity' => 'down'],
    ['value' => 1, 'label' => __('Disabled', 'carddemo')],
]);

Four status tiles

Stacked bar

card_stackbar($segments, $legend = false)

One bar split into parts of a whole. Each segment is an array of percent, severity and an optional label. Calculate the percentages from one total. Set $legend to true to list the labelled segments.

return card_stackbar([
    ['percent' => 87.5, 'severity' => 'up', 'label' => __('42 up', 'carddemo')],
    ['percent' => 6.25, 'severity' => 'warn', 'label' => __('3 recovering', 'carddemo')],
    ['percent' => 4.17, 'severity' => 'down', 'label' => __('2 down', 'carddemo')],
    ['percent' => 2.08, 'label' => __('1 disabled', 'carddemo')],
], true);

Stacked bar of device states with a legend

Donut

card_donut($segments, $center_label = '', $sub_label = '', $legend = false)

Parts of a whole drawn clockwise from the top. A segment with a severity takes that colour. A segment without one takes the next series colour, so the same helper suits states and categories. Segments stop at 100%. The chart's accessible name lists the centre label and each labelled segment with its share, such as 18.3k: kern 46%, daemon 27%, auth 18%, local7 9%.

// segments without a severity take the series colours in order
return card_donut([
    ['percent' => 46, 'label' => 'kern'],
    ['percent' => 27, 'label' => 'daemon'],
    ['percent' => 18, 'label' => 'auth'],
    ['percent' => 9, 'label' => 'local7'],
], '18.3k', __('messages', 'carddemo'), true);

Keep the centre text short. A long caption overflows the hole, so put detail in the legend or the card instead.

Donut of syslog facilities

Waffle

card_waffle($percent, $label, $severity = 'none')

A 10 by 10 grid in which each filled cell is one percent, rounded to whole cells. It reads more precisely than a pie for one proportion.

return card_waffle(93, __('93% of devices up', 'carddemo'), 'up');

Waffle with 93 of 100 cells filled

Ranges and distributions

Top N distribution

card_distribution($rows, $scale_max = null)

Ranked rows of a label, a bar and the value. Each row is an array of label, value and optional display text and severity. Bars are scaled against $scale_max, or against the largest value when it is omitted. Pass rows in the order to show them. A long label is cut short on screen and kept whole in its tooltip.

// the busiest interfaces, scaled against the busiest one
return card_distribution([
    ['label' => 'core-01 Te1/1', 'value' => 812, 'display' => '812 Mb/s', 'severity' => 'warn'],
    ['label' => 'core-01 Te1/2', 'value' => 604, 'display' => '604 Mb/s'],
    ['label' => 'edge-03 Gi0/1', 'value' => 377, 'display' => '377 Mb/s'],
    ['label' => 'wan-02 Gi0/0', 'value' => 96, 'display' => '96 Mb/s'],
]);

Four interfaces ranked by traffic

Bullet

card_bullet($min, $avg, $max, $label, $summary = '', $severity = 'none', $scale_min = 0.0, $scale_max = 100.0)

A band from minimum to maximum with a marker at the average, on a scale you choose. Use the same unit and sampling window for all five numbers. A NAN minimum or maximum leaves the band out, and a NAN average leaves the marker out.

return card_bullet(18, 41, 77, __('CPU, last 24 hours', 'carddemo'), __('18 / 41 / 77%', 'carddemo'), 'up', 0, 100);

Bullet from 18 to 77 with a marker at 41

Box and whisker

card_boxplot($min, $q1, $median, $q3, $max, $label, $summary = '', $severity = 'none', $scale_min = 0.0, $scale_max = 100.0)

The spread of many measurements: whiskers from minimum to maximum, a box from the first to the third quartile and a marker at the median. It shares the bullet's heading and scale. A part whose input is NAN or INF is left out. U, empty strings and NULL count as 0, so convert a missing quartile or median to NAN before the call rather than let it plot at 0.

// response time across 48 devices: minimum, quartiles, median and maximum
return card_boxplot(0.8, 2.1, 3.4, 6.9, 18.2, __('Response time, 48 devices', 'carddemo'), __('median 3.4 ms', 'carddemo'), 'up', 0, 20);

Box plot of device response times

Sparkline

card_sparkline($values, $label, $severity = 'none')

A small line with a shaded area, oldest sample on the left. The line is scaled to its own minimum and maximum, so it shows shape rather than size. Pair it with a value or a statistic. Fewer than two usable samples draw an empty placeholder of the same height.

return card_sparkline([99.2, 99.6, 99.1, 98.4, 97.9, 99.0, 99.7, 99.8], __('Availability, last 8 hours', 'carddemo'), 'up');

Availability sparkline

Multi-line trend

card_multiline($series, $label, $legend = true)

Several lines on one shared scale, such as inbound and outbound traffic. Each series is an array of values and an optional label, and takes the next series colour. Sample N of every series is drawn at the same position. An unknown sample is skipped and the line joins the samples on either side of it, so the later samples keep their position but the line shows no break; say so in the card if missing periods matter. A series with fewer than two usable samples is left out.

// 'U' is an unknown RRD sample: that hour is skipped, the later ones stay in place
return card_multiline([
    ['label' => __('Inbound', 'carddemo'), 'values' => [310, 420, 'U', 515, 480, 610, 590, 640]],
    ['label' => __('Outbound', 'carddemo'), 'values' => [120, 160, 150, 210, 230, 220, 260, 250]],
], __('Traffic, last 8 hours', 'carddemo'));

Inbound and outbound traffic lines

Column chart

card_columns($values, $label, $severity = 'none')

One bar per sample, rising from a drawn zero line. Unlike a sparkline the heights compare as absolute values, and negative samples hang below the line. Use it for counts per interval and for changes.

// hour-on-hour change in open alerts; falls hang below the zero line
return card_columns([3, 5, -2, 0, 4, -6, -1, 2], __('Change in open alerts per hour', 'carddemo'), 'warn');

Columns above and below a zero line

Use the charts from a third-party plugin

A plugin that requires Cacti 1.2.32 or later can call every helper directly. A plugin that also supports older releases has three options, all used by the supported plugins.

Bundle the stylesheet

Copy include/css/card-widgets.css into the plugin, unchanged, as css/card-widgets.css. Load it only when core does not ship the file, so a newer Cacti uses its own copy. The Host MIB, APC UPS, TopX, Intropage, MacTrack, Syslog and Alarm Manager plugins load their copies this way:

if (!file_exists($config['base_path'] . '/include/css/card-widgets.css')) {
    print get_md5_include_css('plugins/myplugin/css/card-widgets.css');
}

Keep the copy byte-identical with core. The supported plugins pin its SHA-256 hash in a unit test, so an edit to the copy alone fails the test, and update the copy and the hash together when core changes:

test('the bundled card widget stylesheet is the pinned copy of the core file', function () {
    $file = dirname(__DIR__, 2) . '/css/card-widgets.css';

    expect(hash_file('sha256', $file))->toBe('<sha256 of include/css/card-widgets.css>');
});

Remove the copy and its loader once the plugin's minimum Cacti version ships the stylesheet.

Call a helper only when it exists

Check for the helper and fall back to markup of your own. Intropage draws its trend sparklines this way, with a fallback that writes the same markup as card_sparkline():

function command_sparkline(array $values, string $label, string $severity): string {
    return function_exists('card_sparkline') ? card_sparkline($values, $label, $severity) : command_sparkline_markup($values, $label, $severity);
}

The example's charts.php checks each helper the same way before calling it.

Write the markup yourself

The class names in card-widgets.css are a stable markup contract. The Host MIB, APC UPS and TopX dashboards write .ccTiles, .ccBullet, .ccGauge and .ccStack markup directly, so their charts work with the bundled stylesheet on any Cacti. Escape every value you write.

The progress ring needs no geometry, only its percentage in --cc-pct:

print '<div class="ccRing ccRing--warn" style="--cc-pct:81"><span class="ccRingValue">81%</span>'
    . '<span class="ccRingSub">' . __esc('Memory', 'carddemo') . '</span></div>';

Progress ring written as markup

The other charts compute SVG coordinates. Call their helpers rather than copying their arithmetic.

Show charts in an Intropage panel

A panel body can combine several charts. The example registers a second panel, Traffic overview, whose update function prints three of the examples above and falls back to a statistic on a Cacti without the newer helpers:

function carddemo_update_traffic($panel, $user_id) {
    require_once __DIR__ . '/charts-examples.php';

    $panel['alarm'] = 'green';

    if (function_exists('card_multiline')) {
        $panel['data'] = carddemo_chart_multiline() . carddemo_chart_donut() . carddemo_chart_stat();
    } else {
        $panel['data'] = card_stat('640 Mb/s', __('Inbound traffic', 'carddemo'));
    }

    save_panel_result($panel, $user_id);
}

Run php plugins/carddemo/register-panel.php from the Cacti root to register both example panels. Expect Registered carddemo_capacity. and Registered carddemo_traffic. Add Carddemo - Traffic overview from the dashboard's Panels menu. The panel shows No Data Present until the Intropage poller runs its update function, which happens once the panel's 300-second refresh interval has passed.

Traffic overview panel on an Intropage dashboard

Register, authorize and remove panels as described in Publish a card in Intropage.

Implementation references


Copyright (c) 2004-2026 The Cacti Group