ggplot-rs 0.63.0

A Rust implementation of ggplot2's Grammar of Graphics
Documentation
use crate::aes::Aesthetic;
use crate::coord::Coord;
use crate::data::{DataFrame, Value};
use crate::position::identity::PositionIdentity;
use crate::position::Position;
use crate::render::backend::{DrawBackend, LineStyle, Linetype, PointShape, PointStyle, RectStyle};
use crate::render::RenderError;
use crate::scale::ScaleSet;
use crate::stat::density::StatDensity;
use crate::stat::Stat;
use crate::theme::Theme;

use super::{Geom, GeomParams};

/// Density curve geometry — filled area under a kernel density estimate.
pub struct GeomDensity {
    pub fill: (u8, u8, u8),
    pub color: (u8, u8, u8),
    pub alpha: f64,
    pub line_width: f64,
    /// Fill each side of a threshold in its own colour (a distribution of
    /// outcomes: losses red, gains green), cut at the exact crossing; one
    /// outline. Along x by default use [`SplitAxis::X`](super::support::SplitAxis::X).
    pub split: Option<super::support::SignSplit>,
}

impl Default for GeomDensity {
    fn default() -> Self {
        GeomDensity {
            fill: (97, 156, 255),
            color: (50, 50, 50),
            alpha: 0.3,
            line_width: 1.0,
            split: None,
        }
    }
}

impl Geom for GeomDensity {
    fn key_fill(&self) -> Option<((u8, u8, u8), f64)> {
        Some((self.fill, self.alpha))
    }

    fn draw(
        &self,
        data: &DataFrame,
        coord: &dyn Coord,
        scales: &ScaleSet,
        _theme: &Theme,
        backend: &mut dyn DrawBackend,
    ) -> Result<(), RenderError> {
        let x_col = data
            .column("x")
            .ok_or(RenderError::MissingAesthetic("x".into()))?;
        let y_col = data
            .column("y")
            .ok_or(RenderError::MissingAesthetic("y".into()))?;
        let fill_col = data.column("fill");
        let color_col = data.column("color");

        let plot_area = backend.plot_area();
        let x_scale = scales.get(&Aesthetic::X);
        let y_scale = scales.get(&Aesthetic::Y);

        let base_ny = y_scale.map(|s| s.map(&Value::Float(0.0))).unwrap_or(0.0);

        // Determine groups from color or fill column
        let group_col = color_col.or(fill_col);
        let groups: Vec<(String, Vec<usize>)> = if let Some(gc) = group_col {
            let mut groups: Vec<(String, Vec<usize>)> = Vec::new();
            for (i, v) in gc.iter().enumerate() {
                let key = v.to_group_key();
                if let Some(entry) = groups.iter_mut().find(|(k, _)| k == &key) {
                    entry.1.push(i);
                } else {
                    groups.push((key, vec![i]));
                }
            }
            groups
        } else {
            // Single group with all indices
            vec![("".to_string(), (0..data.nrows()).collect())]
        };

        for (group_label, indices) in &groups {
            if indices.is_empty() {
                continue;
            }
            let first_idx = indices[0];

            // Resolve fill: use fill scale if fill column exists, else use color scale, else default
            let fill_color = fill_col
                .and_then(|fc| scales.map_color(&Aesthetic::Fill, &fc[first_idx]))
                .or_else(|| {
                    color_col.and_then(|cc| scales.map_color(&Aesthetic::Color, &cc[first_idx]))
                })
                .unwrap_or(self.fill);

            // Resolve line: use color scale if color column exists, else use fill scale, else default
            let line_color = color_col
                .and_then(|cc| scales.map_color(&Aesthetic::Color, &cc[first_idx]))
                .or_else(|| {
                    fill_col.and_then(|fc| scales.map_color(&Aesthetic::Fill, &fc[first_idx]))
                })
                .unwrap_or(self.color);

            let mut up_n: Vec<(f64, f64)> = Vec::new();
            let mut low_n: Vec<(f64, f64)> = Vec::new();
            for &i in indices {
                let nx = x_scale.map(|s| s.map(&x_col[i])).unwrap_or(0.0);
                let ny = y_scale.map(|s| s.map(&y_col[i])).unwrap_or(0.0);
                up_n.push((nx, ny));
                low_n.push((nx, base_ny));
            }
            let px = |pts: &[(f64, f64)]| -> Vec<(f64, f64)> {
                pts.iter()
                    .map(|&p| coord.transform(p, &plot_area))
                    .collect()
            };
            let upper = px(&up_n);

            // the filled parts: the whole curve, or one per side of the split
            let parts = match &self.split {
                None => {
                    let mut poly = up_n.clone();
                    poly.extend(low_n.iter().rev());
                    vec![(poly, fill_color)]
                }
                Some(sp) => super::area::split_band(sp, &up_n, &low_n, x_scale, y_scale),
            };
            for (poly, colour) in parts {
                if poly.len() >= 3 {
                    backend.draw_polygon(
                        &px(&poly),
                        &RectStyle {
                            fill: Some(colour),
                            stroke: None,
                            stroke_width: 0.0,
                            alpha: self.alpha,
                            clip: true,
                            corner_radius: 0.0,
                        },
                    )?;
                }
            }

            // Top line
            if upper.len() >= 2 {
                backend.draw_line(
                    &upper,
                    &LineStyle {
                        color: line_color,
                        alpha: 1.0,
                        width: self.line_width,
                        linetype: Linetype::Solid,
                        ..Default::default()
                    },
                )?;
            }

            // Sparse invisible hover points: the curve carries no marks, so emit a
            // handful of transparent points along it (tagged with the x value and
            // density) for the axis-pointer to read on hover.
            let step = (indices.len() / 48).max(1);
            for (k, &i) in indices.iter().enumerate() {
                if k % step != 0 {
                    continue;
                }
                let dens = y_col[i]
                    .as_f64()
                    .map(|f| format!("{f:.4}"))
                    .unwrap_or_default();
                let tip = if group_label.is_empty() {
                    format!("density: {dens}")
                } else {
                    format!("{group_label}: {dens}")
                };
                super::set_mark(
                    backend,
                    Some(tip),
                    Some(super::tip_value(&x_col[i])),
                    super::series_key(data, i),
                    super::measured_value(data, i),
                );
                super::set_mark_formatted(
                    backend,
                    scales,
                    Some(&x_col[i]),
                    &Aesthetic::Y,
                    super::measured_raw(data, i),
                );
                backend.draw_shape(
                    upper[k],
                    0.6,
                    &PointStyle {
                        color: line_color,
                        alpha: 0.0,
                        filled: true,
                        shape: PointShape::Circle,
                    },
                )?;
            }
            super::clear_mark(backend);
        }

        Ok(())
    }

    fn required_aes(&self) -> Vec<Aesthetic> {
        vec![Aesthetic::X]
    }

    fn default_stat(&self) -> Box<dyn Stat> {
        Box::new(StatDensity::default())
    }

    fn default_position(&self) -> Box<dyn Position> {
        Box::new(PositionIdentity)
    }

    fn default_params(&self) -> GeomParams {
        GeomParams::default()
    }

    fn name(&self) -> &str {
        "density"
    }

    fn apply_element_geom(&mut self, el: &crate::theme::elements::ElementGeom) {
        if let (true, Some(ink)) = (self.color == (50, 50, 50), el.ink) {
            self.color = ink;
        }
    }

    fn set_series_color(&mut self, color: (u8, u8, u8)) {
        self.fill = color;
    }
}