Lines
100 %
Functions
63.93 %
Branches
//! Horizontal bars: one row per x label, the labels left of the axis.
use std::borrow::Cow;
use plotters::coord::Shift;
use plotters::prelude::*;
use plotters::style::text_anchor::{HPos, Pos, VPos};
use super::legend::{more_label, pixels, text_width};
use super::{DrawResult, MARGIN, X_AREA, format_y_label, note_height, title_height, x_labels};
use crate::layout::Metrics;
use crate::spec::{ChartKind, ChartSpec};
const ELLIPSIS: char = '…';
/// A label's share of the chart width: wider labels are cut.
const LABEL_SHARE: i32 = 3;
/// The least height of a row: the pitch of a note line.
fn row_height(metrics: Metrics) -> i32 {
metrics.px_i32(14)
}
fn style<'a, DB: DrawingBackend>(
area: &DrawingArea<DB, Shift>,
metrics: &'a Metrics,
) -> TextStyle<'a> {
("sans-serif", metrics.px(11))
.into_text_style(area)
.color(&metrics.ink)
/// `label`, or its start and an ellipsis, so that `width` of the result is at most `cap`.
fn cut(label: &str, cap: i32, width: impl Fn(&str) -> i32) -> String {
if width(label) <= cap {
return label.to_string();
let mut kept: Vec<char> = label.chars().collect();
while kept.pop().is_some() {
let cut: String = kept.iter().chain(&[ELLIPSIS]).collect();
if width(&cut) <= cap {
return cut;
ELLIPSIS.to_string()
/// The labels as drawn, each cut to its share of the chart width.
pub(super) fn row_labels<DB: DrawingBackend>(
root: &DrawingArea<DB, Shift>,
labels: &[String],
metrics: Metrics,
) -> Vec<String> {
let cap = pixels(root.dim_in_pixel().0) / LABEL_SHARE;
let width = |text: &str| text_width(root, text, metrics);
labels.iter().map(|label| cut(label, cap, width)).collect()
/// The width of the left axis area: the widest label and its gap to the axis.
pub(super) fn axis_width<DB: DrawingBackend>(
) -> u32 {
let widest = labels
.iter()
.map(|label| text_width(root, label, metrics))
.max()
.unwrap_or(0);
u32::try_from(widest + 2 * metrics.gap()).unwrap_or(0)
/// How many value ticks fit in `plot_w`: one per widest tick label and a gap, from 2 to 6.
pub(super) fn tick_count<DB: DrawingBackend>(
plot_w: i32,
(low, high): (f64, f64),
decimals: usize,
) -> usize {
let widest = [low, high]
.map(|&tick| text_width(root, &format_y_label(tick, decimals), metrics))
let pitch = (widest + metrics.px_i32(14)).max(1);
usize::try_from(plot_w / pitch).unwrap_or(0).clamp(2, 6)
/// Each label right-aligned against the axis, centred on its row.
pub(super) fn draw_row_labels<DB, CT>(
chart: &ChartContext<'_, DB, CT>,
x_min: f64,
) -> DrawResult<DB>
where
DB: DrawingBackend,
CT: plotters::coord::CoordTranslate<From = (f64, f64)>,
{
let text_style = style(area, &metrics).pos(Pos::new(HPos::Right, VPos::Center));
for (idx, label) in labels.iter().enumerate() {
let (x, y) = chart
.plotting_area()
.map_coordinate(&(x_min, crate::layout::Slots::centre(idx)));
area.draw_text(label, &text_style, (x - metrics.gap(), y))?;
Ok(())
/// How many rows fit in `total_h` beside the title, value axis and `notes`.
fn capacity(metrics: Metrics, total_h: i32, notes: usize) -> usize {
let chart_h = total_h - note_height(metrics, notes);
let plot_h = chart_h
- title_height(metrics, chart_h)
- metrics.px_i32(X_AREA)
- 2 * metrics.px_i32(MARGIN);
usize::try_from(plot_h / row_height(metrics))
.unwrap_or(0)
.max(1)
/// `spec` with the rows that do not fit dropped and a "+N more" note for them.
pub(super) fn capped<'a>(
spec: &'a ChartSpec,
total_h: i32,
) -> Cow<'a, ChartSpec> {
if !matches!(spec.kind, ChartKind::HBar) {
return Cow::Borrowed(spec);
let mut labels = x_labels(spec);
let fits = capacity(metrics, total_h, spec.notes.len());
if labels.len() <= fits {
let fits = capacity(metrics, total_h, spec.notes.len() + 1);
let hidden = labels.len().saturating_sub(fits);
labels.truncate(fits);
let mut kept = spec.clone();
for series in &mut kept.series {
series.points.retain(|p| labels.contains(&p.x));
kept.series.retain(|series| !series.points.is_empty());
kept.notes.push(more_label(hidden));
Cow::Owned(kept)
#[cfg(all(test, feature = "svg"))]
mod tests;