Skip to main content

ggplot_rs/aes/
mapping.rs

1use crate::aes::{Aes, MappingStage};
2use crate::data::DataFrame;
3
4/// Evaluate aesthetic mappings: extract columns from source data
5/// and rename them to canonical aesthetic names (x, y, color, etc.).
6/// Only resolves BeforeStat mappings.
7pub fn resolve_mappings(data: &DataFrame, mapping: &Aes) -> DataFrame {
8    let mut result = DataFrame::new();
9    let nrows = data.nrows();
10
11    if nrows == 0 {
12        return result;
13    }
14
15    for m in &mapping.mappings {
16        if m.stage != MappingStage::BeforeStat {
17            continue;
18        }
19        let col_name = m.aesthetic.col_name();
20        if let Some(values) = data.column(&m.column) {
21            result.add_column(col_name.to_string(), values.to_vec());
22        }
23    }
24
25    // Also carry over any columns that already have canonical names and aren't mapped
26    for name in data.column_names() {
27        if !result.has_column(name) {
28            // Keep original columns available for stats that need them
29            if let Some(values) = data.column(name) {
30                if result.nrows() == 0 || values.len() == result.nrows() {
31                    result.add_column(name.to_string(), values.to_vec());
32                }
33            }
34        }
35    }
36
37    result
38}
39
40/// Apply after_stat mappings: rename stat-computed columns to canonical aesthetic names.
41/// Called after the stat step in the build pipeline.
42pub fn apply_after_stat(data: &mut DataFrame, mapping: &Aes) {
43    for m in &mapping.mappings {
44        if m.stage != MappingStage::AfterStat {
45            continue;
46        }
47        let target = m.aesthetic.col_name();
48        let source = &m.column;
49
50        // If the stat produced the source column, rename it to the target aesthetic
51        if let Some(values) = data.column(source) {
52            let values = values.to_vec();
53            // Remove existing target column if any, then add the new mapping
54            if data.has_column(target) {
55                if let Some(col) = data.column_mut(target) {
56                    *col = values;
57                }
58            } else {
59                data.add_column(target.to_string(), values);
60            }
61        }
62    }
63}