Lines
99.68 %
Functions
85 %
Branches
100 %
//! Backend-agnostic chart drawing. Both `render_svg` and
//! `render_canvas` call `draw_on` with their own drawing area, so a
//! chart drawn to SVG looks identical to one drawn to a canvas.
use plotters::coord::Shift;
use plotters::coord::cartesian::Cartesian2d;
use plotters::coord::types::RangedCoordf64;
use plotters::prelude::*;
use plotters::style::text_anchor::{HPos, Pos, VPos};
mod hbar;
mod legend;
use legend::{Legend, pixels};
use crate::layout::{Metrics, Slots};
use crate::spec::{ChartKind, ChartSpec, SeriesPoint};
/// Palette cycled through series. Deliberately short — in practice
/// reports have 2-5 series.
const PALETTE: &[RGBColor] = &[
RGBColor(31, 119, 180),
RGBColor(255, 127, 14),
RGBColor(44, 160, 44),
RGBColor(214, 39, 40),
RGBColor(148, 103, 189),
RGBColor(140, 86, 75),
RGBColor(227, 119, 194),
];
/// Axes, grid, labels and title: about 4.5:1 against both white and black, so
/// the unfilled chart reads on a light and on a dark background.
pub(crate) const NEUTRAL: RGBColor = RGBColor(118, 118, 118);
fn color_for(index: usize) -> RGBColor {
PALETTE[index % PALETTE.len()]
}
type Chart<'a, DB> = ChartContext<'a, DB, Cartesian2d<RangedCoordf64, RangedCoordf64>>;
type DrawResult<DB> = Result<(), DrawingAreaErrorKind<<DB as DrawingBackend>::ErrorType>>;
/// Draw `spec` onto `root`. Common layout for every chart kind: title
/// across the top, chart in the middle, notes (if any) across the
/// bottom.
///
/// # Errors
/// Returns an error if the backend rejects a draw call (e.g. the
/// drawing area is zero-sized). Callers fall back to a plain-text
/// representation on failure.
pub fn draw_on<DB>(
root: &DrawingArea<DB, Shift>,
spec: &ChartSpec,
text_px: u32,
ink: RGBColor,
) -> DrawResult<DB>
where
DB: DrawingBackend,
{
// Before any text is drawn: without the embedded face plotters would look for
// a system font, which a static musl binary cannot even attempt (see font.rs).
#[cfg(not(target_arch = "wasm32"))]
crate::font::ensure_registered();
let metrics = Metrics::new(text_px, ink);
let (_, total_h) = root.dim_in_pixel();
let total_h = i32::try_from(total_h).unwrap_or(0);
let spec = &hbar::capped(spec, metrics, total_h);
let chart_h = total_h
.saturating_sub(note_height(metrics, spec.notes.len()))
.max(0);
let (chart_area, notes_area) = root.split_vertically(chart_h);
let x_labels = x_labels(spec);
if x_labels.is_empty() || spec.series.is_empty() {
chart_area.draw_text(
&spec.title,
&("sans-serif", metrics.px(TITLE_FONT), &metrics.ink).into_text_style(&chart_area),
(metrics.px_i32(10), metrics.px_i32(20)),
)?;
draw_notes(¬es_area, spec, metrics)?;
return Ok(());
let (y_min, y_max) = y_range(spec);
let horizontal = matches!(spec.kind, ChartKind::HBar);
// Grouped bars share a slot between the series that have a point there;
// stacked bars and lines use one bar or point per period.
let slots = match spec.kind {
ChartKind::Bar | ChartKind::HBar => Slots::grouped(spec, &x_labels),
ChartKind::StackedBar | ChartKind::Line => Slots::single(x_labels.len()),
};
let decimals = y_decimals(y_max - y_min);
let title_h = title_height(metrics, chart_h);
let (title_area, below) = chart_area.split_vertically(title_h);
title_area.draw_text(
&("sans-serif", metrics.px(TITLE_FONT), &metrics.ink)
.into_text_style(&title_area)
.pos(Pos::new(HPos::Center, VPos::Center)),
(
i32::try_from(title_area.dim_in_pixel().0 / 2).unwrap_or(0),
title_h / 2,
),
let legend = Legend::new(&below, spec, metrics, (chart_h - title_h) / 3);
let (legend_area, plot_area) = below.split_vertically(legend.height());
legend.draw(&legend_area, spec)?;
let row_labels = match horizontal {
true => hbar::row_labels(root, &x_labels, metrics),
false => Vec::new(),
let y_area = match horizontal {
true => hbar::axis_width(root, &row_labels, metrics),
false => metrics.px(60),
let value_ticks = match horizontal {
true => {
let plot_w =
pixels(plot_area.dim_in_pixel().0) - pixels(y_area) - 2 * metrics.px_i32(MARGIN);
hbar::tick_count(root, plot_w, (y_min, y_max), decimals, metrics)
false => 6,
let (x_range, y_axis) = match horizontal {
true => (y_min..y_max, slots.len()..0.0),
false => (0.0..slots.len(), y_min..y_max),
let mut chart = ChartBuilder::on(&plot_area)
.x_label_area_size(metrics.px(X_AREA))
.y_label_area_size(y_area)
.margin(metrics.px(MARGIN))
.build_cartesian_2d(x_range, y_axis)?;
configure_mesh(&mut chart, spec, metrics, decimals, value_ticks)?;
match spec.kind {
ChartKind::Line => draw_line(&mut chart, spec, &x_labels, metrics)?,
ChartKind::Bar | ChartKind::HBar => draw_bars(&mut chart, spec, &x_labels, false, &slots)?,
ChartKind::StackedBar => draw_bars(&mut chart, spec, &x_labels, true, &slots)?,
match horizontal {
true => hbar::draw_row_labels(&chart, root, &row_labels, y_min, metrics)?,
false => draw_x_labels(&chart, root, &x_labels, y_min, metrics)?,
Ok(())
/// The title font, on the scale of [`DEFAULT_TEXT_PX`]: one step above the 11 of the labels.
const TITLE_FONT: u32 = 13;
const X_AREA: u32 = 36;
const MARGIN: u32 = 8;
fn note_height(metrics: Metrics, notes: usize) -> i32 {
metrics.px_i32(16) * i32::try_from(notes).unwrap_or(0)
fn title_height(metrics: Metrics, chart_h: i32) -> i32 {
metrics.px_i32(22).min(chart_h / 3)
/// The value axis the bars grow along, and the grid across it. A vertical chart's labels
/// are the x labels drawn by [`draw_x_labels`]; a horizontal one's are drawn by [`hbar`].
fn configure_mesh<DB>(
chart: &mut Chart<'_, DB>,
metrics: Metrics,
decimals: usize,
value_ticks: usize,
let value = |y: &f64| format_y_label(*y, decimals);
let blank = |_: &f64| String::new();
let mut mesh = chart.configure_mesh();
// Cap the ticks so the default "one line per unit" doesn't draw
// hundreds of rules on a chart whose range spans into the thousands.
ChartKind::HBar => mesh
.x_labels(value_ticks)
.x_label_formatter(&value)
.y_labels(1)
.y_label_formatter(&blank)
.set_tick_mark_size(LabelAreaPosition::Left, 0)
.disable_y_mesh()
.x_desc(&spec.y_label),
_ => mesh
.y_labels(6)
.y_label_formatter(&value)
.x_labels(1)
.x_label_formatter(&blank)
.set_tick_mark_size(LabelAreaPosition::Bottom, 0)
.disable_x_mesh()
.x_desc(&spec.x_label)
.y_desc(&spec.y_label),
mesh.light_line_style(TRANSPARENT)
.axis_style(metrics.ink)
.bold_line_style(metrics.ink.mix(0.3))
.axis_desc_style(("sans-serif", metrics.px(12), &metrics.ink))
.label_style(("sans-serif", metrics.px(11), &metrics.ink))
.draw()
/// The union of x labels in the order they first appear.
fn x_labels(spec: &ChartSpec) -> Vec<String> {
let mut labels: Vec<String> = Vec::new();
for point in spec.series.iter().flat_map(|series| &series.points) {
if !labels.contains(&point.x) {
labels.push(point.x.clone());
labels
/// Bars with one point each at their own x: the axis labels already name them.
fn bars_name_themselves(spec: &ChartSpec) -> bool {
let mut seen: Vec<&str> = Vec::new();
for series in &spec.series {
let [point] = series.points.as_slice() else {
return false;
if seen.contains(&point.x.as_str()) {
seen.push(&point.x);
matches!(spec.kind, ChartKind::Bar | ChartKind::HBar)
/// The decimals a y tick needs over an axis `range` long: one more than the digit the tick
/// step (about a fifth of the range, in 1, 2 or 5 units) reaches down to.
fn y_decimals(range: f64) -> usize {
let step = range / 5.0;
if !(step.is_finite() && step > 0.0) {
return 0;
let digits = (0..8i32)
.find(|digits| step * 10f64.powi(digits - 1) >= 1.0)
.unwrap_or(8);
usize::try_from(digits).unwrap_or(0)
/// A y tick with up to `decimals` decimals, no trailing zeros, thousands grouped by a comma.
fn format_y_label(y: f64, decimals: usize) -> String {
let text = format!("{:.*}", decimals, y.abs());
let trimmed = if text.contains('.') {
text.trim_end_matches('0').trim_end_matches('.')
} else {
text.as_str()
let (whole, fraction) = trimmed.split_once('.').unwrap_or((trimmed, ""));
let mut grouped = String::new();
for (i, digit) in whole.chars().enumerate() {
if i > 0 && (whole.len() - i) % 3 == 0 {
grouped.push(',');
grouped.push(digit);
if !fraction.is_empty() {
grouped.push('.');
grouped.push_str(fraction);
match (y < 0.0, grouped.as_str()) {
(_, "0") | (false, _) => grouped,
(true, _) => format!("-{grouped}"),
fn y_range(spec: &ChartSpec) -> (f64, f64) {
let (mut min, mut max) = (0.0_f64, 0.0_f64);
if matches!(spec.kind, ChartKind::StackedBar) {
// Per-x-slot: sum positive and negative stacks separately.
let mut slots: std::collections::BTreeMap<&str, (f64, f64)> =
std::collections::BTreeMap::new();
for point in &series.points {
let y = point.y_f64();
let (neg, pos) = slots.entry(point.x.as_str()).or_insert((0.0, 0.0));
if y >= 0.0 {
*pos += y;
*neg += y;
for (_, (neg, pos)) in slots {
if neg < min {
min = neg;
if pos > max {
max = pos;
if y < min {
min = y;
if y > max {
max = y;
let span = match (max - min).abs() {
0.0 => 1.0,
span => span,
let pad = span * 0.05;
// An axis that has nothing on one side of zero stops at zero; a chart of zeros keeps a
// span so its ticks have somewhere to land.
let low = if min < 0.0 { min - pad } else { 0.0 };
let high = match (max > 0.0, min < 0.0) {
(true, _) => max + pad,
(false, true) => 0.0,
(false, false) => span,
(low, high)
/// The x labels centred under their slots, below the axis.
fn draw_x_labels<DB, CT>(
chart: &ChartContext<'_, DB, CT>,
area: &DrawingArea<DB, Shift>,
x_labels: &[String],
y_min: f64,
CT: plotters::coord::CoordTranslate<From = (f64, f64)>,
let style = ("sans-serif", metrics.px(11), &metrics.ink)
.into_text_style(area)
.pos(Pos::new(HPos::Center, VPos::Top));
for (idx, label) in x_labels.iter().enumerate() {
let (x, y) = chart
.plotting_area()
.map_coordinate(&(Slots::centre(idx), y_min));
area.draw_text(label, &style, (x, y + metrics.gap()))?;
fn draw_line<DB, CT>(
chart: &mut ChartContext<'_, DB, CT>,
let (stroke, dot) = (metrics.px(2), metrics.px_i32(3));
for (i, series) in spec.series.iter().enumerate() {
let color = color_for(i);
let points: Vec<(f64, f64)> = x_labels
.iter()
.enumerate()
.map(|(idx, label)| {
let y = series
.points
.find(|p| &p.x == label)
.map_or(0.0, SeriesPoint::y_f64);
(Slots::centre(idx), y)
})
.collect();
chart.draw_series(LineSeries::new(points.clone(), color.stroke_width(stroke)))?;
chart.draw_series(
points
.into_iter()
.map(|p| Circle::new(p, dot, color.filled())),
fn draw_bars<DB, CT>(
stacked: bool,
slots: &Slots,
// Stacked-bar accumulators per x-slot and sign.
let mut pos_acc: Vec<f64> = vec![0.0; x_labels.len()];
let mut neg_acc: Vec<f64> = vec![0.0; x_labels.len()];
// Bars already placed in each x slot: the next one sits right of them.
let mut placed: Vec<usize> = vec![0; x_labels.len()];
for (s_idx, series) in spec.series.iter().enumerate() {
let color = color_for(s_idx);
for (x_idx, label) in x_labels.iter().enumerate() {
let Some(point) = series.points.iter().find(|p| &p.x == label) else {
continue;
let rank = if stacked { 0 } else { placed[x_idx] };
placed[x_idx] += 1;
if y == 0.0 {
let (base, top) = if stacked {
let acc = if y >= 0.0 {
&mut pos_acc[x_idx]
&mut neg_acc[x_idx]
let start = *acc;
*acc += y;
(start, *acc)
(0.0, y)
let (left, right) = slots.span(x_idx, rank);
let corners = match spec.kind {
ChartKind::HBar => [(base, left), (top, right)],
_ => [(left, base), (right, top)],
chart.draw_series(std::iter::once(Rectangle::new(corners, color.filled())))?;
fn draw_notes<DB>(
if spec.notes.is_empty() || area.dim_in_pixel().1 == 0 {
let style = ("sans-serif", metrics.px(11), &metrics.ink).into_text_style(area);
for (i, note) in spec.notes.iter().enumerate() {
let y = metrics.px_i32(2) + i32::try_from(i).unwrap_or(0) * metrics.px_i32(14);
area.draw_text(note, &style, (metrics.px_i32(8), y))?;
#[cfg(all(test, feature = "svg"))]
mod tests;