Lines
98.47 %
Functions
72.22 %
Branches
100 %
//! The series legend: rows of swatch and name drawn above the plot, never over it.
use plotters::coord::Shift;
use plotters::prelude::*;
use plotters::style::text_anchor::{HPos, Pos, VPos};
use super::{DrawResult, bars_name_themselves, color_for};
use crate::layout::Metrics;
use crate::spec::{ChartKind, ChartSpec};
/// Series indices on each row of the legend.
type Rows = Vec<Vec<usize>>;
fn font(metrics: Metrics) -> (&'static str, u32) {
("sans-serif", metrics.px(11))
}
fn row_height(metrics: Metrics) -> i32 {
metrics.px_i32(18)
fn gap(metrics: Metrics) -> i32 {
metrics.px_i32(14)
pub(super) fn pixels(length: u32) -> i32 {
i32::try_from(length).unwrap_or(i32::MAX)
pub(super) fn text_width<DB: DrawingBackend>(
area: &DrawingArea<DB, Shift>,
text: &str,
metrics: Metrics,
) -> i32 {
let style = (font(metrics).0, font(metrics).1, &metrics.ink).into_text_style(area);
pixels(area.estimate_text_size(text, &style).map_or(0, |(w, _)| w))
/// The pixel width of every entry: swatch, space and name.
fn entry_widths<DB: DrawingBackend>(
spec: &ChartSpec,
) -> Vec<i32> {
spec.series
.iter()
.map(|series| metrics.px_i32(14) + text_width(area, &series.label, metrics))
.collect()
/// Entries packed left to right, a new row when the next does not fit in `avail`.
fn pack(widths: &[i32], avail: i32, gap: i32) -> Rows {
let mut rows: Rows = Vec::new();
let mut used = 0;
for (index, width) in widths.iter().enumerate() {
match rows.last_mut() {
Some(row) if used + gap + width <= avail => {
row.push(index);
used += gap + width;
_ => {
rows.push(vec![index]);
used = *width;
rows
pub(super) fn more_label(hidden: usize) -> String {
format!("+{hidden} more")
/// The legend rows of a chart, as many as fit in `max_height`. When entries are cut,
/// the last row ends with a "+N more" entry, indexed after the series.
pub(super) struct Legend {
widths: Vec<i32>,
rows: Rows,
more: String,
impl Legend {
/// Empty when the axis labels already name every bar.
pub fn new<DB: DrawingBackend>(
max_height: i32,
) -> Self {
let mut widths = entry_widths(area, spec, metrics);
let avail = pixels(area.dim_in_pixel().0) - 2 * metrics.px_i32(8);
let mut rows = if bars_name_themselves(spec) {
Vec::new()
} else {
pack(&widths, avail, gap(metrics))
};
let capacity = usize::try_from(max_height / row_height(metrics)).unwrap_or(0);
let mut more = String::new();
if rows.len() > capacity {
rows.truncate(capacity);
more = Self::append_more(area, &mut rows, &mut widths, avail, metrics);
Self {
widths,
rows,
more,
metrics,
/// Drops trailing entries of the last row until "+N more" fits after them.
fn append_more<DB: DrawingBackend>(
rows: &mut Rows,
widths: &mut Vec<i32>,
avail: i32,
) -> String {
let total = widths.len();
loop {
let shown: usize = rows.iter().map(Vec::len).sum();
let label = more_label(total - shown);
let width = text_width(area, &label, metrics);
let Some(last) = rows.last_mut() else {
return String::new();
let used: i32 = last.iter().filter_map(|&i| widths.get(i)).sum::<i32>()
+ gap(metrics) * pixels(u32::try_from(last.len()).unwrap_or(0));
if used + width <= avail || last.is_empty() {
last.push(total);
widths.push(width);
return label;
last.pop();
/// The height the legend takes from the chart.
pub fn height(&self) -> i32 {
i32::try_from(self.rows.len()).unwrap_or(0) * row_height(self.metrics)
pub fn draw<DB: DrawingBackend>(
&self,
) -> DrawResult<DB> {
let metrics = self.metrics;
let style = (font(metrics).0, font(metrics).1, &metrics.ink)
.into_text_style(area)
.pos(Pos::new(HPos::Left, VPos::Center));
let (swatch_w, swatch_h) = (metrics.px_i32(10), metrics.px_i32(6));
let canvas = pixels(area.dim_in_pixel().0);
for (row_index, row) in self.rows.iter().enumerate() {
let used = row.iter().filter_map(|&i| self.widths.get(i)).sum::<i32>()
+ gap(metrics) * i32::try_from(row.len().saturating_sub(1)).unwrap_or(0);
let mut x = ((canvas - used) / 2).max(0);
let y = i32::try_from(row_index).unwrap_or(0) * row_height(metrics)
+ row_height(metrics) / 2;
for &index in row {
let Some(width) = self.widths.get(index) else {
continue;
let Some(series) = spec.series.get(index) else {
area.draw_text(&self.more, &style, (x, y))?;
x += width + gap(metrics);
let color = color_for(index);
let top = y - swatch_h / 2;
if matches!(spec.kind, ChartKind::Line) {
area.draw(&PathElement::new(
vec![(x, y), (x + swatch_w, y)],
color.stroke_width(metrics.px(2)),
))?;
let corners = [(x, top), (x + swatch_w, top + swatch_h)];
area.draw(&Rectangle::new(corners, color.filled()))?;
area.draw(&Rectangle::new(corners, metrics.ink.stroke_width(1)))?;
area.draw_text(&series.label, &style, (x + metrics.px_i32(14), y))?;
Ok(())
#[cfg(test)]
mod tests;