Lines
100 %
Functions
Branches
//! Text-relative sizes and bar slot geometry shared by every backend.
use plotters::prelude::RGBColor;
use crate::spec::ChartSpec;
/// The rendered height, in pixels, of label text at the sizes the layout was designed for.
/// plotters draws a font of size `n` about four fifths of `n` tall, so the designed
/// size 11 is 9 px of glyph.
pub const DEFAULT_TEXT_PX: u32 = 9;
/// Converts sizes designed for [`DEFAULT_TEXT_PX`] text to the text height drawn,
/// and holds the colour the axes, grid and text are drawn in.
#[derive(Debug, Clone, Copy)]
pub(crate) struct Metrics {
text: u32,
pub ink: RGBColor,
}
impl Metrics {
pub fn new(text_px: u32, ink: RGBColor) -> Self {
Self {
text: text_px.max(1),
ink,
/// `base` pixels at the default text height, scaled to this one.
pub fn px(self, base: u32) -> u32 {
base.saturating_mul(self.text)
.saturating_add(DEFAULT_TEXT_PX / 2)
/ DEFAULT_TEXT_PX
/// The space between the axis and the top of the label under it: 0.4 of the text height.
pub fn gap(self) -> i32 {
i32::try_from(self.text.saturating_mul(2) / 5).unwrap_or(i32::MAX)
pub fn px_i32(self, base: u32) -> i32 {
i32::try_from(self.px(base)).unwrap_or(i32::MAX)
/// The share of a slot left empty on each side of its bars.
const SLOT_GAP: f64 = 1.0 / 7.0;
fn units(count: usize) -> f64 {
f64::from(u32::try_from(count).unwrap_or(u32::MAX))
/// How many bars each x label holds. A label is one unit wide on the x axis, so a label's
/// bars share the slot between its gaps and a lone bar fills it whatever the other labels hold.
pub(crate) struct Slots {
counts: Vec<usize>,
impl Slots {
/// One bar per label, as a line or a stacked bar has.
pub fn single(labels: usize) -> Self {
counts: vec![1; labels],
/// The bars of each label are the series that have a point at it.
pub fn grouped(spec: &ChartSpec, labels: &[String]) -> Self {
let counts = labels
.iter()
.map(|label| {
spec.series
.filter(|series| series.points.iter().any(|p| &p.x == label))
.count()
.max(1)
})
.collect();
Self { counts }
/// The x axis length: one unit per label.
pub fn len(&self) -> f64 {
units(self.counts.len())
/// The middle of the slot of `label`.
pub fn centre(label: usize) -> f64 {
units(label) + 0.5
/// The x range of bar `rank` of label `label`.
pub fn span(&self, label: usize, rank: usize) -> (f64, f64) {
let bars = self.counts.get(label).copied().unwrap_or(1).max(1);
let each = (1.0 - 2.0 * SLOT_GAP) / units(bars);
let left = units(label) + SLOT_GAP + units(rank) * each;
(left, left + each)