Skip to main content

fp_frame/
plot_render.rs

1//! Zero-dependency deterministic SVG renderer for the backend-neutral plot
2//! specs produced by `DataFrame::plot` / `Series::plot` / `hist` / `boxplot`
3//! and the GroupBy plotting hooks.
4//!
5//! Design constraints (br-frankenpandas-rc-plot-renderer-zf9bf):
6//! - **Pure Rust, no new dependencies, no `unsafe`, Tokio-free.** SVG is text;
7//!   an in-house writer beats pulling a font/rasterizer stack into the
8//!   workspace. PNG output needs a rasterizer dependency and is a deliberate
9//!   follow-up, not part of this module.
10//! - **Deterministic**: no clock, no RNG, fixed palette and geometry — the same
11//!   spec renders byte-identical SVG forever (asserted by a test).
12//! - **Fail closed, zero panics**: non-numeric series, all-missing series, and
13//!   negative pie values return `Err(FrameError::...)` instead of plotting
14//!   nonsense or panicking; `NaN`/`Null` values become gaps (line/area/scatter)
15//!   or are skipped (histogram/box/bar).
16//!
17//! Style floor only: axes, ticks, gridlines, series colors, titles, legend,
18//! XML-escaped labels. This is not matplotlib parity by design.
19
20use crate::{
21    BoxPlotSpec, FrameError, HistogramSpec, PlotKind, PlotSeriesSpec, PlotSpec, Scalar,
22    ScatterMatrixSpec, TablePlotSpec,
23};
24
25// ── Geometry / palette ─────────────────────────────────────────────────────
26
27const WIDTH: f64 = 640.0;
28const HEIGHT: f64 = 400.0;
29const MARGIN_LEFT: f64 = 56.0;
30const MARGIN_RIGHT: f64 = 16.0;
31const MARGIN_TOP: f64 = 30.0;
32const MARGIN_BOTTOM: f64 = 42.0;
33const PLOT_W: f64 = WIDTH - MARGIN_LEFT - MARGIN_RIGHT;
34const PLOT_H: f64 = HEIGHT - MARGIN_TOP - MARGIN_BOTTOM;
35const PALETTE: [&str; 7] = [
36    "#4e79a7", "#f28e2b", "#e15759", "#76b7b2", "#59a14f", "#edc948", "#b07aa1",
37];
38const MAX_X_TICKS: usize = 8;
39
40fn palette(i: usize) -> &'static str {
41    PALETTE[i % PALETTE.len()]
42}
43
44/// XML-escape text destined for element content or attribute values.
45fn esc(s: &str) -> String {
46    let mut out = String::with_capacity(s.len());
47    for c in s.chars() {
48        match c {
49            '&' => out.push_str("&"),
50            '<' => out.push_str("&lt;"),
51            '>' => out.push_str("&gt;"),
52            '"' => out.push_str("&quot;"),
53            '\'' => out.push_str("&#39;"),
54            _ => out.push(c),
55        }
56    }
57    out
58}
59
60/// Numeric view of a series: `None` = missing (`NaN` or `Null`), `Err` = the
61/// series is not plottable at all (non-numeric dtype). Matches pandas, where
62/// plotting an object column raises instead of inventing numbers.
63fn numeric_view(series: &PlotSeriesSpec) -> Result<Vec<Option<f64>>, FrameError> {
64    series
65        .values
66        .iter()
67        .map(|value| match value {
68            Scalar::Float64(v) => Ok(if v.is_finite() { Some(*v) } else { None }),
69            Scalar::Int64(v) => Ok(Some(*v as f64)),
70            Scalar::Bool(b) => Ok(Some(if *b { 1.0 } else { 0.0 })),
71            Scalar::Null(_) => Ok(None),
72            other => Err(FrameError::CompatibilityRejected(format!(
73                "plot requires numeric values: series '{}' carries {:?} ({other:?})",
74                series.name, series.dtype
75            ))),
76        })
77        .collect()
78}
79
80/// A finite min/max pair across every series; constant data is padded so the
81/// band keeps height instead of dividing by zero. All-missing data is an error.
82#[derive(Debug, Clone, Copy)]
83struct Scale {
84    min: f64,
85    max: f64,
86}
87
88fn data_scale(series: &[Vec<Option<f64>>]) -> Result<Scale, FrameError> {
89    let mut min = f64::INFINITY;
90    let mut max = f64::NEG_INFINITY;
91    for values in series {
92        for v in values.iter().flatten() {
93            if v.is_finite() {
94                min = min.min(*v);
95                max = max.max(*v);
96            }
97        }
98    }
99    if !min.is_finite() || !max.is_finite() {
100        return Err(FrameError::CompatibilityRejected(
101            "no plottable (non-missing) values in this plot".to_owned(),
102        ));
103    }
104    if (max - min).abs() < f64::EPSILON {
105        min -= 1.0;
106        max += 1.0;
107    }
108    Ok(Scale { min, max })
109}
110
111fn fmt_num(v: f64) -> String {
112    if v == v.trunc() && v.abs() < 1e15 {
113        format!("{}", v as i64)
114    } else {
115        format!("{v:.4}")
116    }
117}
118
119fn svg_open(title: &str) -> String {
120    format!(
121        "<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"{WIDTH}\" height=\"{HEIGHT}\" viewBox=\"0 0 {WIDTH} {HEIGHT}\" font-family=\"monospace\" font-size=\"11\"><rect width=\"{WIDTH}\" height=\"{HEIGHT}\" fill=\"white\"/><text x=\"{MARGIN_LEFT}\" y=\"18\" fill=\"#333\">{}</text>",
122        esc(title)
123    )
124}
125
126fn svg_axes(scale: &Scale, x_labels: &[String]) -> String {
127    let mut out = String::new();
128    let right = MARGIN_LEFT + PLOT_W;
129    let bottom = MARGIN_TOP + PLOT_H;
130    for i in 0..=4 {
131        let frac = i as f64 / 4.0;
132        let value = scale.max - frac * (scale.max - scale.min);
133        let y = MARGIN_TOP + frac * PLOT_H;
134        out.push_str(&format!(
135            "<line x1=\"{MARGIN_LEFT}\" y1=\"{y:.2}\" x2=\"{right}\" y2=\"{y:.2}\" stroke=\"#e5e5e5\"/><text x=\"{}\" y=\"{:.2}\" text-anchor=\"end\" fill=\"#666\">{}</text>",
136            MARGIN_LEFT - 6.0,
137            y + 4.0,
138            esc(&fmt_num(value))
139        ));
140    }
141    out.push_str(&format!(
142        "<line x1=\"{MARGIN_LEFT}\" y1=\"{MARGIN_TOP}\" x2=\"{MARGIN_LEFT}\" y2=\"{bottom}\" stroke=\"#333\"/><line x1=\"{MARGIN_LEFT}\" y1=\"{bottom}\" x2=\"{right}\" y2=\"{bottom}\" stroke=\"#333\"/>"
143    ));
144    let n = x_labels.len();
145    if n > 0 {
146        let step = n.div_ceil(MAX_X_TICKS);
147        for (i, label) in x_labels.iter().enumerate() {
148            if i % step != 0 {
149                continue;
150            }
151            let x = MARGIN_LEFT + (i as f64 + 0.5) * PLOT_W / n as f64;
152            out.push_str(&format!(
153                "<text x=\"{x:.2}\" y=\"{:.2}\" text-anchor=\"middle\" fill=\"#666\">{}</text>",
154                bottom + 14.0,
155                esc(label)
156            ));
157        }
158    }
159    out
160}
161
162fn svg_horizontal_axes(scale: &Scale, y_labels: &[String]) -> String {
163    let mut out = String::new();
164    let right = MARGIN_LEFT + PLOT_W;
165    let bottom = MARGIN_TOP + PLOT_H;
166    for i in 0..=4 {
167        let frac = i as f64 / 4.0;
168        let value = scale.min + frac * (scale.max - scale.min);
169        let x = MARGIN_LEFT + frac * PLOT_W;
170        out.push_str(&format!(
171            "<line x1=\"{x:.2}\" y1=\"{MARGIN_TOP}\" x2=\"{x:.2}\" y2=\"{bottom}\" stroke=\"#e5e5e5\"/><text x=\"{x:.2}\" y=\"{:.2}\" text-anchor=\"middle\" fill=\"#666\">{}</text>",
172            bottom + 14.0,
173            esc(&fmt_num(value))
174        ));
175    }
176    out.push_str(&format!(
177        "<line x1=\"{MARGIN_LEFT}\" y1=\"{MARGIN_TOP}\" x2=\"{MARGIN_LEFT}\" y2=\"{bottom}\" stroke=\"#333\"/><line x1=\"{MARGIN_LEFT}\" y1=\"{bottom}\" x2=\"{right}\" y2=\"{bottom}\" stroke=\"#333\"/>"
178    ));
179    let n = y_labels.len();
180    if n > 0 {
181        let step = n.div_ceil(MAX_X_TICKS);
182        let slot = PLOT_H / n as f64;
183        for (i, label) in y_labels.iter().enumerate() {
184            if i % step != 0 {
185                continue;
186            }
187            let y = MARGIN_TOP + (i as f64 + 0.5) * slot;
188            let truncated = if label.len() > 8 {
189                format!("{}…", &label[..7])
190            } else {
191                label.clone()
192            };
193            out.push_str(&format!(
194                "<text x=\"{}\" y=\"{y:.2}\" text-anchor=\"end\" dominant-baseline=\"middle\" fill=\"#666\">{}</text>",
195                MARGIN_LEFT - 6.0,
196                esc(&truncated)
197            ));
198        }
199    }
200    out
201}
202
203fn svg_numeric_2d_axes(x_scale: &Scale, y_scale: &Scale) -> String {
204    let mut out = String::new();
205    let right = MARGIN_LEFT + PLOT_W;
206    let bottom = MARGIN_TOP + PLOT_H;
207    for i in 0..=4 {
208        let frac = i as f64 / 4.0;
209        let value = y_scale.max - frac * (y_scale.max - y_scale.min);
210        let y = MARGIN_TOP + frac * PLOT_H;
211        out.push_str(&format!(
212            "<line x1=\"{MARGIN_LEFT}\" y1=\"{y:.2}\" x2=\"{right}\" y2=\"{y:.2}\" stroke=\"#e5e5e5\"/><text x=\"{}\" y=\"{:.2}\" text-anchor=\"end\" fill=\"#666\">{}</text>",
213            MARGIN_LEFT - 6.0,
214            y + 4.0,
215            esc(&fmt_num(value))
216        ));
217    }
218    for i in 0..=4 {
219        let frac = i as f64 / 4.0;
220        let value = x_scale.min + frac * (x_scale.max - x_scale.min);
221        let x = MARGIN_LEFT + frac * PLOT_W;
222        out.push_str(&format!(
223            "<line x1=\"{x:.2}\" y1=\"{MARGIN_TOP}\" x2=\"{x:.2}\" y2=\"{bottom}\" stroke=\"#e5e5e5\"/><text x=\"{x:.2}\" y=\"{:.2}\" text-anchor=\"middle\" fill=\"#666\">{}</text>",
224            bottom + 14.0,
225            esc(&fmt_num(value))
226        ));
227    }
228    out.push_str(&format!(
229        "<line x1=\"{MARGIN_LEFT}\" y1=\"{MARGIN_TOP}\" x2=\"{MARGIN_LEFT}\" y2=\"{bottom}\" stroke=\"#333\"/><line x1=\"{MARGIN_LEFT}\" y1=\"{bottom}\" x2=\"{right}\" y2=\"{bottom}\" stroke=\"#333\"/>"
230    ));
231    out
232}
233
234fn legend(entries: &[(String, &str)]) -> String {
235    if entries.is_empty() {
236        return String::new();
237    }
238    let mut out = String::new();
239    let y = HEIGHT - 10.0;
240    let max_display = 6;
241    let (display_entries, overflow) = if entries.len() > max_display {
242        (
243            &entries[..max_display - 1],
244            Some(entries.len() - (max_display - 1)),
245        )
246    } else {
247        (entries, None)
248    };
249    let total_items = display_entries.len() + if overflow.is_some() { 1 } else { 0 };
250    let spacing = (PLOT_W / total_items.max(1) as f64).min(140.0);
251    for (i, (name, color)) in display_entries.iter().enumerate() {
252        let x = MARGIN_LEFT + (i as f64 * spacing);
253        let max_chars = ((spacing - 20.0) / 7.0).floor() as usize;
254        let display_name = if name.chars().count() > max_chars && max_chars >= 4 {
255            let truncated: String = name.chars().take(max_chars - 1).collect();
256            format!("{truncated}…")
257        } else {
258            name.clone()
259        };
260        out.push_str(&format!(
261            "<rect x=\"{x:.2}\" y=\"{:.2}\" width=\"10\" height=\"10\" fill=\"{color}\"/><text x=\"{:.2}\" y=\"{y:.2}\" fill=\"#333\">{}</text>",
262            y - 9.0,
263            x + 14.0,
264            esc(&display_name)
265        ));
266    }
267    if let Some(count) = overflow {
268        let x = MARGIN_LEFT + (display_entries.len() as f64 * spacing);
269        out.push_str(&format!(
270            "<text x=\"{x:.2}\" y=\"{y:.2}\" fill=\"#666\">+{count} more</text>"
271        ));
272    }
273    out
274}
275
276// ── PlotSpec rendering (line / area / scatter / bar / pie) ─────────────────
277
278fn render_plot(spec: &PlotSpec) -> Result<String, FrameError> {
279    if spec.kind == PlotKind::Box {
280        return boxplot_body(&spec.series, &spec.method);
281    }
282    if spec.kind == PlotKind::Histogram {
283        return histogram_body(&spec.series, 10, &spec.method);
284    }
285
286    let views: Result<Vec<Vec<Option<f64>>>, FrameError> =
287        spec.series.iter().map(numeric_view).collect();
288    let views = views?;
289
290    let is_xy_scatter = spec.kind == PlotKind::Scatter
291        && spec.series.len() >= 2
292        && spec.series.len().is_multiple_of(2)
293        && (spec.method.contains("(x=")
294            || spec.method.contains("scatter_columns")
295            || spec.method.contains(".lag(")
296            || spec.method.contains("radviz"));
297    let is_xy_hexbin = spec.kind == PlotKind::Hexbin
298        && spec.series.len() >= 2
299        && spec.series.len().is_multiple_of(2)
300        && (spec.method.contains("(x=") || spec.method.contains("hexbin_columns"));
301
302    let (scale, xy_scales) = if (is_xy_scatter || is_xy_hexbin) && views.len() >= 2 {
303        let x_views: Vec<_> = (0..views.len())
304            .step_by(2)
305            .map(|i| views[i].clone())
306            .collect();
307        let y_views: Vec<_> = (1..views.len())
308            .step_by(2)
309            .map(|i| views[i].clone())
310            .collect();
311        let (x_sc, y_sc) = if spec.method.contains("radviz") {
312            (
313                Scale {
314                    min: -1.15,
315                    max: 1.15,
316                },
317                Scale {
318                    min: -1.15,
319                    max: 1.15,
320                },
321            )
322        } else {
323            (data_scale(&x_views)?, data_scale(&y_views)?)
324        };
325        (y_sc, Some((x_sc, y_sc)))
326    } else {
327        let mut sc = data_scale(&views)?;
328        if spec.kind == PlotKind::Bar || spec.kind == PlotKind::Barh {
329            sc.min = sc.min.min(0.0);
330            sc.max = sc.max.max(0.0);
331            if (sc.max - sc.min).abs() < f64::EPSILON {
332                sc.max += 1.0;
333            }
334        }
335        (sc, None)
336    };
337
338    let n = spec
339        .series
340        .iter()
341        .map(|s| s.values.len())
342        .max()
343        .unwrap_or(0);
344    let mut x_labels: Vec<String> = spec
345        .series
346        .first()
347        .map(|first| {
348            first
349                .index
350                .iter()
351                .map(|label| crate::scalar_plot_label(&crate::index_label_to_scalar(label)))
352                .collect()
353        })
354        .unwrap_or_default();
355    if x_labels.len() < n {
356        x_labels = (0..n).map(|i| i.to_string()).collect();
357    }
358
359    let y = |v: f64| MARGIN_TOP + (scale.max - v) / (scale.max - scale.min) * PLOT_H;
360    let x = |i: usize| MARGIN_LEFT + (i as f64 + 0.5) * PLOT_W / n.max(1) as f64;
361
362    let mut body = String::new();
363    match spec.kind {
364        PlotKind::Line | PlotKind::Area => {
365            let is_class_grouped = spec.kind == PlotKind::Line
366                && (spec.method.contains("parallel_coordinates")
367                    || spec.method.contains("andrews_curves"));
368            let mut unique_classes: Vec<String> = Vec::new();
369            if is_class_grouped {
370                for s in &spec.series {
371                    let class_name = s
372                        .group_key
373                        .as_ref()
374                        .and_then(|gk| gk.first())
375                        .map(crate::scalar_plot_label)
376                        .unwrap_or_else(|| s.name.clone());
377                    if !unique_classes.contains(&class_name) {
378                        unique_classes.push(class_name);
379                    }
380                }
381            }
382
383            if spec.method.contains("parallel_coordinates") {
384                let bottom = MARGIN_TOP + PLOT_H;
385                for i in 0..n {
386                    let xi = x(i);
387                    body.push_str(&format!(
388                        "<line x1=\"{xi:.2}\" y1=\"{MARGIN_TOP}\" x2=\"{xi:.2}\" y2=\"{bottom}\" stroke=\"#ccc\" stroke-width=\"1\" stroke-dasharray=\"3,3\"/>"
389                    ));
390                }
391            }
392
393            // Contiguous finite runs become separate polylines; NaN/Null breaks
394            // the line exactly like a masked gap.
395            for (si, values) in views.iter().enumerate() {
396                let color = if is_class_grouped {
397                    let class_name = spec.series[si]
398                        .group_key
399                        .as_ref()
400                        .and_then(|gk| gk.first())
401                        .map(crate::scalar_plot_label)
402                        .unwrap_or_else(|| spec.series[si].name.clone());
403                    let c_idx = unique_classes
404                        .iter()
405                        .position(|c| c == &class_name)
406                        .unwrap_or(si);
407                    palette(c_idx)
408                } else {
409                    palette(si)
410                };
411                let stroke_attrs = if is_class_grouped {
412                    "stroke-width=\"1.5\" stroke-opacity=\"0.6\""
413                } else {
414                    "stroke-width=\"2\""
415                };
416                let mut runs: Vec<Vec<(f64, f64)>> = vec![Vec::new()];
417                for (i, v) in values.iter().enumerate() {
418                    match v.filter(|v| v.is_finite()) {
419                        Some(v) => runs.last_mut().expect("seeded run").push((x(i), y(v))),
420                        None if !runs.last().expect("seeded run").is_empty() => {
421                            runs.push(Vec::new());
422                        }
423                        None => {}
424                    }
425                }
426                runs.retain(|run| !run.is_empty());
427                for run in &runs {
428                    let points = run
429                        .iter()
430                        .map(|(px, py)| format!("{px:.2},{py:.2}"))
431                        .collect::<Vec<_>>()
432                        .join(" ");
433                    if spec.kind == PlotKind::Area {
434                        let first_x = run[0].0;
435                        let last_x = run[run.len() - 1].0;
436                        let base = y(scale.min);
437                        body.push_str(&format!(
438                            "<polygon points=\"{first_x:.2},{base:.2} {points} {last_x:.2},{base:.2}\" fill=\"{color}\" fill-opacity=\"0.25\" stroke=\"none\"/>"
439                        ));
440                    }
441                    body.push_str(&format!(
442                        "<polyline points=\"{points}\" fill=\"none\" stroke=\"{color}\" {stroke_attrs}/>"
443                    ));
444                }
445            }
446        }
447        PlotKind::Scatter => {
448            if let Some((ref x_sc, ref y_sc)) = xy_scales {
449                let x_map = |v: f64| MARGIN_LEFT + (v - x_sc.min) / (x_sc.max - x_sc.min) * PLOT_W;
450                let y_map = |v: f64| MARGIN_TOP + (y_sc.max - v) / (y_sc.max - y_sc.min) * PLOT_H;
451                if spec.method.contains("radviz") {
452                    let cx = x_map(0.0);
453                    let cy = y_map(0.0);
454                    let rx = (x_map(1.0) - cx).abs();
455                    let ry = (y_map(1.0) - cy).abs();
456                    body.push_str(&format!(
457                        "<ellipse cx=\"{cx:.2}\" cy=\"{cy:.2}\" rx=\"{rx:.2}\" ry=\"{ry:.2}\" fill=\"none\" stroke=\"#bbb\" stroke-width=\"1.5\"/>"
458                    ));
459                }
460                let num_groups = views.len() / 2;
461                for g in 0..num_groups {
462                    let color = palette(g);
463                    let vx_view = &views[2 * g];
464                    let vy_view = &views[2 * g + 1];
465                    let len = vx_view.len().min(vy_view.len());
466                    for i in 0..len {
467                        if let (Some(vx), Some(vy)) = (vx_view[i], vy_view[i])
468                            && vx.is_finite()
469                            && vy.is_finite()
470                        {
471                            body.push_str(&format!(
472                                "<circle cx=\"{:.2}\" cy=\"{:.2}\" r=\"2.5\" fill=\"{color}\"/>",
473                                x_map(vx),
474                                y_map(vy)
475                            ));
476                        }
477                    }
478                }
479            } else {
480                for (si, values) in views.iter().enumerate() {
481                    let color = palette(si);
482                    for (i, v) in values.iter().enumerate() {
483                        if let Some(v) = v.filter(|v| v.is_finite()) {
484                            body.push_str(&format!(
485                                "<circle cx=\"{:.2}\" cy=\"{:.2}\" r=\"2.5\" fill=\"{color}\"/>",
486                                x(i),
487                                y(v)
488                            ));
489                        }
490                    }
491                }
492            }
493        }
494        PlotKind::Bar => {
495            let k = views.len().max(1);
496            let slot = PLOT_W / n.max(1) as f64;
497            let bar_w = (slot * 0.7 / k as f64).max(0.5);
498            let baseline = 0.0f64.clamp(scale.min, scale.max);
499            let base = y(baseline);
500            for (si, values) in views.iter().enumerate() {
501                let color = palette(si);
502                let offset = si as f64 * bar_w + slot * 0.15;
503                for (i, v) in values.iter().enumerate() {
504                    if let Some(v) = v.filter(|v| v.is_finite()) {
505                        let top = y(v);
506                        let rect_y = top.min(base);
507                        let rect_h = (base - top).abs().max(0.5);
508                        body.push_str(&format!(
509                            "<rect x=\"{:.2}\" y=\"{rect_y:.2}\" width=\"{bar_w:.2}\" height=\"{rect_h:.2}\" fill=\"{color}\"/>",
510                            MARGIN_LEFT + i as f64 * slot + offset,
511                        ));
512                    }
513                }
514            }
515        }
516        PlotKind::Pie => {
517            let any_positive = views.iter().any(|v| v.iter().flatten().any(|x| *x > 0.0));
518            if !any_positive {
519                return Err(FrameError::CompatibilityRejected(
520                    "pie plot requires at least one positive value".to_owned(),
521                ));
522            }
523            let mut angle: f64 = -std::f64::consts::FRAC_PI_2;
524            let cx = MARGIN_LEFT + PLOT_W / 2.0;
525            let cy = MARGIN_TOP + PLOT_H / 2.0;
526            let r = 140.0;
527            let mut slice_idx = 0;
528            for (si, values) in views.iter().enumerate() {
529                let finite_values: Vec<f64> = values
530                    .iter()
531                    .flatten()
532                    .copied()
533                    .filter(|v| v.is_finite())
534                    .collect();
535                if finite_values.iter().any(|v| *v < 0.0) {
536                    return Err(FrameError::CompatibilityRejected(format!(
537                        "pie requires non-negative values: series '{}' has a negative slice",
538                        spec.series[si].name
539                    )));
540                }
541                let total: f64 = finite_values.iter().sum();
542                if total <= 0.0 {
543                    continue;
544                }
545                for v in finite_values {
546                    if v <= 0.0 {
547                        continue;
548                    }
549                    let color = palette(slice_idx);
550                    slice_idx += 1;
551                    let frac = v / total;
552                    if frac >= 1.0 - 1e-6 {
553                        body.push_str(&format!(
554                            "<circle cx=\"{cx:.2}\" cy=\"{cy:.2}\" r=\"{r}\" fill=\"{color}\" stroke=\"white\"/>"
555                        ));
556                        angle += std::f64::consts::TAU;
557                    } else {
558                        let next = angle + frac * std::f64::consts::TAU;
559                        let large = (next - angle) > std::f64::consts::PI;
560                        body.push_str(&format!(
561                            "<path d=\"M {cx:.2} {cy:.2} L {:.2} {:.2} A {r} {r} 0 {} 1 {:.2} {:.2} Z\" fill=\"{color}\" stroke=\"white\"/>",
562                            cx + r * angle.cos(),
563                            cy + r * angle.sin(),
564                            i64::from(large),
565                            cx + r * next.cos(),
566                            cy + r * next.sin(),
567                        ));
568                        angle = next;
569                    }
570                }
571            }
572        }
573        PlotKind::Barh => {
574            let k = views.len().max(1);
575            let slot = PLOT_H / n.max(1) as f64;
576            let bar_h = (slot * 0.7 / k as f64).max(0.5);
577            let baseline = 0.0f64.clamp(scale.min, scale.max);
578            let base_x = MARGIN_LEFT + (baseline - scale.min) / (scale.max - scale.min) * PLOT_W;
579            let val_to_x =
580                |v: f64| MARGIN_LEFT + (v - scale.min) / (scale.max - scale.min) * PLOT_W;
581            for (si, values) in views.iter().enumerate() {
582                let color = palette(si);
583                let offset = si as f64 * bar_h + slot * 0.15;
584                for (i, v) in values.iter().enumerate() {
585                    if let Some(v) = v.filter(|v| v.is_finite()) {
586                        let vx = val_to_x(v);
587                        let rect_x = vx.min(base_x);
588                        let rect_w = (vx - base_x).abs().max(0.5);
589                        let rect_y = MARGIN_TOP + i as f64 * slot + offset;
590                        body.push_str(&format!(
591                            "<rect x=\"{rect_x:.2}\" y=\"{rect_y:.2}\" width=\"{rect_w:.2}\" height=\"{bar_h:.2}\" fill=\"{color}\"/>",
592                        ));
593                    }
594                }
595            }
596        }
597        PlotKind::Kde | PlotKind::Density => {
598            let mut all_finite: Vec<f64> = Vec::new();
599            let mut per_series_finite: Vec<Vec<f64>> = Vec::new();
600            for values in &views {
601                let finite: Vec<f64> = values
602                    .iter()
603                    .flatten()
604                    .copied()
605                    .filter(|v| v.is_finite())
606                    .collect();
607                all_finite.extend(&finite);
608                per_series_finite.push(finite);
609            }
610            if all_finite.is_empty() {
611                return Err(FrameError::CompatibilityRejected(
612                    "kde plot requires at least one finite numeric value".to_owned(),
613                ));
614            }
615            let (data_min, data_max) = all_finite
616                .iter()
617                .fold((f64::INFINITY, f64::NEG_INFINITY), |(mn, mx), &v| {
618                    (mn.min(v), mx.max(v))
619                });
620            let span = (data_max - data_min).max(1.0);
621            let eval_min = data_min - 0.2 * span;
622            let eval_max = data_max + 0.2 * span;
623            let grid_size = 100;
624            let step = (eval_max - eval_min) / (grid_size - 1) as f64;
625
626            let mut curves: Vec<Vec<(f64, f64)>> = Vec::new();
627            let mut max_density = 0.0f64;
628            let inv_sqrt_2pi = 1.0 / (2.0 * std::f64::consts::PI).sqrt();
629
630            for finite in &per_series_finite {
631                let m = finite.len();
632                if m == 0 {
633                    curves.push(Vec::new());
634                    continue;
635                }
636                let mean = finite.iter().sum::<f64>() / m as f64;
637                let var = if m > 1 {
638                    finite.iter().map(|x| (x - mean).powi(2)).sum::<f64>() / (m - 1) as f64
639                } else {
640                    1.0
641                };
642                let std_dev = var.sqrt().max(1e-6);
643                let bandwidth = (1.06 * std_dev * (m as f64).powf(-0.2)).max(1e-6);
644                let two_h_sq = 2.0 * bandwidth * bandwidth;
645                let norm = 1.0 / (m as f64 * bandwidth) * inv_sqrt_2pi;
646
647                let mut curve = Vec::with_capacity(grid_size);
648                for g in 0..grid_size {
649                    let t = eval_min + g as f64 * step;
650                    let mut d = 0.0;
651                    for &x_val in finite {
652                        let diff = t - x_val;
653                        d += (-diff * diff / two_h_sq).exp();
654                    }
655                    d *= norm;
656                    max_density = max_density.max(d);
657                    curve.push((t, d));
658                }
659                curves.push(curve);
660            }
661            if max_density <= 0.0 {
662                max_density = 1.0;
663            }
664
665            let y_dens = |d: f64| MARGIN_TOP + (1.0 - d / (max_density * 1.05)) * PLOT_H;
666            let x_dens = |t: f64| MARGIN_LEFT + (t - eval_min) / (eval_max - eval_min) * PLOT_W;
667
668            for (si, curve) in curves.iter().enumerate() {
669                if curve.is_empty() {
670                    continue;
671                }
672                let color = palette(si);
673                let points = curve
674                    .iter()
675                    .map(|(t, d)| format!("{:.2},{:.2}", x_dens(*t), y_dens(*d)))
676                    .collect::<Vec<_>>()
677                    .join(" ");
678                let first_x = x_dens(curve[0].0);
679                let last_x = x_dens(curve[curve.len() - 1].0);
680                let base_y = y_dens(0.0);
681                body.push_str(&format!(
682                    "<polygon points=\"{first_x:.2},{base_y:.2} {points} {last_x:.2},{base_y:.2}\" fill=\"{color}\" fill-opacity=\"0.15\" stroke=\"none\"/>"
683                ));
684                body.push_str(&format!(
685                    "<polyline points=\"{points}\" fill=\"none\" stroke=\"{color}\" stroke-width=\"2\"/>"
686                ));
687            }
688        }
689        PlotKind::Hexbin => {
690            let pairs: Vec<(f64, f64)> = if is_xy_hexbin && views.len() >= 2 {
691                let mut p = Vec::new();
692                for g in 0..views.len() / 2 {
693                    let v0 = &views[2 * g];
694                    let v1 = &views[2 * g + 1];
695                    let len = v0.len().min(v1.len());
696                    for i in 0..len {
697                        if let (Some(x), Some(y)) = (v0[i], v1[i])
698                            && x.is_finite()
699                            && y.is_finite()
700                        {
701                            p.push((x, y));
702                        }
703                    }
704                }
705                p
706            } else if views.len() >= 2 {
707                let v0 = &views[0];
708                let v1 = &views[1];
709                let len = v0.len().min(v1.len());
710                (0..len)
711                    .filter_map(|i| match (v0[i], v1[i]) {
712                        (Some(x), Some(y)) if x.is_finite() && y.is_finite() => Some((x, y)),
713                        _ => None,
714                    })
715                    .collect()
716            } else if let Some(v0) = views.first() {
717                v0.iter()
718                    .enumerate()
719                    .filter_map(|(i, v)| v.filter(|v| v.is_finite()).map(|v| (i as f64, v)))
720                    .collect()
721            } else {
722                Vec::new()
723            };
724
725            if pairs.is_empty() {
726                return Err(FrameError::CompatibilityRejected(
727                    "hexbin plot requires numeric coordinate pairs".to_owned(),
728                ));
729            }
730
731            let (min_x, max_x) = if let Some((ref x_sc, _)) = xy_scales {
732                (x_sc.min, x_sc.max)
733            } else {
734                pairs
735                    .iter()
736                    .fold((f64::INFINITY, f64::NEG_INFINITY), |(mn, mx), p| {
737                        (mn.min(p.0), mx.max(p.0))
738                    })
739            };
740            let (min_y, max_y) = if let Some((_, ref y_sc)) = xy_scales {
741                (y_sc.min, y_sc.max)
742            } else {
743                pairs
744                    .iter()
745                    .fold((f64::INFINITY, f64::NEG_INFINITY), |(mn, mx), p| {
746                        (mn.min(p.1), mx.max(p.1))
747                    })
748            };
749            let span_x = (max_x - min_x).max(1.0);
750            let span_y = (max_y - min_y).max(1.0);
751            let grid_nx = 16;
752            let grid_ny = 12;
753            let mut bins: std::collections::HashMap<(usize, usize), usize> =
754                std::collections::HashMap::new();
755            for &(px, py) in &pairs {
756                let bx = (((px - min_x) / span_x * (grid_nx as f64 - 1.0)).round() as usize)
757                    .min(grid_nx - 1);
758                let by = (((py - min_y) / span_y * (grid_ny as f64 - 1.0)).round() as usize)
759                    .min(grid_ny - 1);
760                *bins.entry((bx, by)).or_insert(0) += 1;
761            }
762            let max_count = bins.values().copied().max().unwrap_or(1) as f64;
763            let cell_w = PLOT_W / grid_nx as f64;
764            let cell_h = PLOT_H / grid_ny as f64;
765
766            for ((bx, by), count) in &bins {
767                let cx = MARGIN_LEFT + (*bx as f64 + 0.5) * cell_w;
768                let cy = MARGIN_TOP + (grid_ny - 1 - *by) as f64 * cell_h + cell_h * 0.5;
769                let intensity = (*count as f64 / max_count).clamp(0.15, 1.0);
770                let r = (cell_w.min(cell_h) * 0.45 * (0.4 + 0.6 * intensity)).max(2.0);
771                body.push_str(&format!(
772                    "<circle cx=\"{cx:.2}\" cy=\"{cy:.2}\" r=\"{r:.2}\" fill=\"#4e79a7\" fill-opacity=\"{intensity:.2}\" stroke=\"#333\" stroke-width=\"0.5\"/>"
773                ));
774            }
775        }
776        PlotKind::Histogram | PlotKind::Box => unreachable!(),
777    }
778
779    let legend_entries: Vec<(String, &str)> = if spec.kind == PlotKind::Pie {
780        if spec.series.len() == 1 {
781            let s = &spec.series[0];
782            let mut entries = Vec::new();
783            let mut s_idx = 0;
784            for (i, v) in views[0].iter().enumerate() {
785                if let Some(val) = v
786                    && val.is_finite()
787                    && *val > 0.0
788                {
789                    let label = s
790                        .index
791                        .get(i)
792                        .map(|lbl| crate::scalar_plot_label(&crate::index_label_to_scalar(lbl)))
793                        .unwrap_or_else(|| i.to_string());
794                    entries.push((label, palette(s_idx)));
795                    s_idx += 1;
796                }
797            }
798            entries
799        } else if spec.series.iter().all(|s| s.values.len() == 1) {
800            spec.series
801                .iter()
802                .enumerate()
803                .map(|(i, s)| (s.name.clone(), palette(i)))
804                .collect()
805        } else {
806            let mut entries = Vec::new();
807            let mut s_idx = 0;
808            for (si, s) in spec.series.iter().enumerate() {
809                for (i, v) in views[si].iter().enumerate() {
810                    if let Some(val) = v
811                        && val.is_finite()
812                        && *val > 0.0
813                    {
814                        let label = s
815                            .index
816                            .get(i)
817                            .map(|lbl| {
818                                format!(
819                                    "{}[{}]",
820                                    s.name,
821                                    crate::scalar_plot_label(&crate::index_label_to_scalar(lbl))
822                                )
823                            })
824                            .unwrap_or_else(|| format!("{}[{i}]", s.name));
825                        entries.push((label, palette(s_idx)));
826                        s_idx += 1;
827                    }
828                }
829            }
830            entries
831        }
832    } else if xy_scales.is_some() {
833        let num_groups = spec.series.len() / 2;
834        if num_groups <= 1 && !spec.method.contains("radviz") {
835            vec![(
836                format!("{} vs {}", spec.series[1].name, spec.series[0].name),
837                palette(0),
838            )]
839        } else {
840            (0..num_groups)
841                .map(|g| {
842                    let label = if let Some(ref gk) = spec.series[2 * g].group_key {
843                        crate::group_key_label(gk)
844                    } else if let Some(b_start) = spec.series[2 * g].name.find('[') {
845                        let s = &spec.series[2 * g].name;
846                        if let Some(b_end) = s.rfind(']') {
847                            s[b_start + 1..b_end].to_owned()
848                        } else {
849                            s.clone()
850                        }
851                    } else {
852                        format!("group {g}")
853                    };
854                    (label, palette(g))
855                })
856                .collect()
857        }
858    } else if spec.kind == PlotKind::Line
859        && (spec.method.contains("parallel_coordinates") || spec.method.contains("andrews_curves"))
860    {
861        let mut unique_classes: Vec<String> = Vec::new();
862        for s in &spec.series {
863            let class_name = s
864                .group_key
865                .as_ref()
866                .and_then(|gk| gk.first())
867                .map(crate::scalar_plot_label)
868                .unwrap_or_else(|| s.name.clone());
869            if !unique_classes.contains(&class_name) {
870                unique_classes.push(class_name);
871            }
872        }
873        unique_classes
874            .into_iter()
875            .enumerate()
876            .map(|(i, c)| (c, palette(i)))
877            .collect()
878    } else {
879        spec.series
880            .iter()
881            .enumerate()
882            .map(|(i, s)| (s.name.clone(), palette(i)))
883            .collect()
884    };
885    let axes = if spec.kind == PlotKind::Pie {
886        String::new()
887    } else if let Some((ref x_sc, ref y_sc)) = xy_scales {
888        svg_numeric_2d_axes(x_sc, y_sc)
889    } else if spec.kind == PlotKind::Barh {
890        svg_horizontal_axes(&scale, &x_labels)
891    } else {
892        svg_axes(&scale, &x_labels)
893    };
894    Ok(format!(
895        "{}{body}{axes}{}</svg>",
896        svg_open(&spec.method),
897        legend(&legend_entries),
898    ))
899}
900
901// ── Histogram primitives ───────────────────────────────────────────────────
902
903fn histogram_body(
904    series: &[PlotSeriesSpec],
905    bins: usize,
906    title: &str,
907) -> Result<String, FrameError> {
908    if bins == 0 {
909        return Err(FrameError::CompatibilityRejected(
910            "histogram requires at least one bin".to_owned(),
911        ));
912    }
913    let views: Result<Vec<Vec<Option<f64>>>, FrameError> =
914        series.iter().map(numeric_view).collect();
915    let views = views?;
916    let finite_series: Vec<Vec<f64>> = views
917        .iter()
918        .map(|v| v.iter().flatten().copied().collect())
919        .collect();
920    if finite_series.iter().all(|v| v.is_empty()) {
921        return Err(FrameError::CompatibilityRejected(
922            "no plottable (non-missing) values in this histogram".to_owned(),
923        ));
924    }
925
926    let flat: Vec<Option<f64>> = finite_series
927        .iter()
928        .flat_map(|v| v.iter().copied())
929        .map(Some)
930        .collect();
931    let scale = data_scale(&[flat])?;
932    let step = (scale.max - scale.min) / bins as f64;
933
934    let mut global_max = 0usize;
935    let mut all_counts: Vec<Vec<usize>> = Vec::with_capacity(finite_series.len());
936    for values in &finite_series {
937        let mut counts = vec![0usize; bins];
938        for v in values {
939            let raw_idx = ((v - scale.min) / step).floor();
940            let idx = if *v >= scale.max {
941                bins - 1
942            } else if raw_idx <= 0.0 {
943                0
944            } else {
945                (raw_idx as usize).min(bins - 1)
946            };
947            counts[idx] += 1;
948        }
949        global_max = global_max.max(*counts.iter().max().unwrap_or(&0));
950        all_counts.push(counts);
951    }
952    let global_max = global_max.max(1);
953
954    let mut body = String::new();
955    let width = PLOT_W / finite_series.len().max(1) as f64;
956    for (si, counts) in all_counts.iter().enumerate() {
957        let color = palette(si);
958        let x0 = MARGIN_LEFT + si as f64 * width;
959        let inner = width * 0.85;
960        let bar_w = (inner / bins as f64 - 1.0).max(0.5);
961        for (bi, count) in counts.iter().enumerate() {
962            if *count == 0 {
963                continue;
964            }
965            let h = *count as f64 / global_max as f64 * PLOT_H;
966            let bx = x0 + bi as f64 * (inner / bins as f64);
967            body.push_str(&format!(
968                "<rect x=\"{bx:.2}\" y=\"{:.2}\" width=\"{bar_w:.2}\" height=\"{h:.2}\" fill=\"{color}\" stroke=\"white\"/>",
969                MARGIN_TOP + PLOT_H - h
970            ));
971        }
972    }
973
974    let count_scale = Scale {
975        min: 0.0,
976        max: global_max as f64,
977    };
978    let mut x_labels = Vec::with_capacity(bins);
979    for i in 0..bins {
980        let bin_mid = scale.min + (i as f64 + 0.5) * step;
981        x_labels.push(fmt_num(bin_mid));
982    }
983    let axes = svg_axes(&count_scale, &x_labels);
984    let legend_entries: Vec<(String, &str)> = series
985        .iter()
986        .enumerate()
987        .map(|(i, s)| (s.name.clone(), palette(i)))
988        .collect();
989
990    Ok(format!(
991        "{}{body}{axes}{}</svg>",
992        svg_open(title),
993        legend(&legend_entries)
994    ))
995}
996
997fn boxplot_body(series: &[PlotSeriesSpec], title: &str) -> Result<String, FrameError> {
998    let views: Result<Vec<Vec<Option<f64>>>, FrameError> =
999        series.iter().map(numeric_view).collect();
1000    let views = views?;
1001    let mut sorted: Vec<(usize, Vec<f64>)> = views
1002        .iter()
1003        .enumerate()
1004        .map(|(si, v)| {
1005            let mut vals: Vec<f64> = v.iter().flatten().copied().collect();
1006            vals.sort_by(f64::total_cmp);
1007            (si, vals)
1008        })
1009        .collect();
1010    sorted.retain(|(_, vals)| !vals.is_empty());
1011    if sorted.is_empty() {
1012        return Err(FrameError::CompatibilityRejected(
1013            "no plottable (non-missing) values in this boxplot".to_owned(),
1014        ));
1015    }
1016    let scale = data_scale(&views)?;
1017    let y = |v: f64| MARGIN_TOP + (scale.max - v) / (scale.max - scale.min) * PLOT_H;
1018    let slot = PLOT_W / sorted.len() as f64;
1019    let mut body = String::new();
1020    let mut x_labels = Vec::with_capacity(sorted.len());
1021    let mut legend_entries = Vec::with_capacity(sorted.len());
1022    for (box_idx, (orig_si, vals)) in sorted.iter().enumerate() {
1023        let color = palette(*orig_si);
1024        let name = &series[*orig_si].name;
1025        x_labels.push(name.clone());
1026        legend_entries.push((name.clone(), color));
1027        let (q1, med, q3) = (
1028            quantile(vals, 0.25),
1029            quantile(vals, 0.5),
1030            quantile(vals, 0.75),
1031        );
1032        let (lo, hi) = (vals[0], vals[vals.len() - 1]);
1033        let cx = MARGIN_LEFT + slot * (box_idx as f64 + 0.5);
1034        let bw = (slot * 0.5).max(1.0);
1035        let top = y(q3);
1036        let bottom = y(q1);
1037        body.push_str(&format!(
1038            "<line x1=\"{cx:.2}\" y1=\"{:.2}\" x2=\"{cx:.2}\" y2=\"{:.2}\" stroke=\"{color}\"/><line x1=\"{:.2}\" y1=\"{:.2}\" x2=\"{:.2}\" y2=\"{:.2}\" stroke=\"{color}\"/>",
1039            y(lo),
1040            y(q1),
1041            cx - bw / 2.0,
1042            y(lo),
1043            cx + bw / 2.0,
1044            y(lo),
1045        ));
1046        body.push_str(&format!(
1047            "<line x1=\"{cx:.2}\" y1=\"{:.2}\" x2=\"{cx:.2}\" y2=\"{:.2}\" stroke=\"{color}\"/><line x1=\"{:.2}\" y1=\"{:.2}\" x2=\"{:.2}\" y2=\"{:.2}\" stroke=\"{color}\"/>",
1048            y(q3),
1049            y(hi),
1050            cx - bw / 2.0,
1051            y(hi),
1052            cx + bw / 2.0,
1053            y(hi),
1054        ));
1055        body.push_str(&format!(
1056            "<rect x=\"{:.2}\" y=\"{top:.2}\" width=\"{bw:.2}\" height=\"{:.2}\" fill=\"{color}\" fill-opacity=\"0.35\" stroke=\"{color}\"/><line x1=\"{:.2}\" y1=\"{:.2}\" x2=\"{:.2}\" y2=\"{:.2}\" stroke=\"{color}\" stroke-width=\"2\"/>",
1057            cx - bw / 2.0,
1058            (bottom - top).abs().max(0.5),
1059            cx - bw / 2.0,
1060            y(med),
1061            cx + bw / 2.0,
1062            y(med),
1063        ));
1064    }
1065    let axes = svg_axes(&scale, &x_labels);
1066    Ok(format!(
1067        "{}{body}{axes}{}</svg>",
1068        svg_open(title),
1069        legend(&legend_entries)
1070    ))
1071}
1072
1073fn quantile(sorted: &[f64], q: f64) -> f64 {
1074    let h = (sorted.len() - 1) as f64 * q;
1075    let lo = h.floor() as usize;
1076    let hi = h.ceil() as usize;
1077    sorted[lo] + (sorted[hi] - sorted[lo]) * (h - lo as f64)
1078}
1079
1080// ── Public API ─────────────────────────────────────────────────────────────
1081
1082impl PlotSpec {
1083    /// Render this spec to a deterministic SVG document (style floor: axes,
1084    /// ticks, gridlines, legend; see module docs). Fails closed on non-numeric
1085    /// series or all-missing data; never panics.
1086    pub fn to_svg(&self) -> Result<String, FrameError> {
1087        render_plot(self)
1088    }
1089
1090    /// [`PlotSpec::to_svg`] as UTF-8 bytes (convenience for `write`/HTTP paths).
1091    pub fn to_svg_bytes(&self) -> Result<Vec<u8>, FrameError> {
1092        self.to_svg().map(String::into_bytes)
1093    }
1094
1095    /// Wrap the deterministic SVG in an HTML figure container suitable for
1096    /// embedding into notebooks, dashboards, or web pages.
1097    pub fn to_html(&self) -> Result<String, FrameError> {
1098        self.to_svg().map(|s| wrap_svg_html(&s))
1099    }
1100
1101    /// Render this spec to a complete, self-contained HTML5 page document.
1102    pub fn to_html_page(&self, title: Option<&str>) -> Result<String, FrameError> {
1103        let title_str = title.unwrap_or(&self.method);
1104        self.to_svg().map(|s| wrap_svg_html_page(&s, title_str))
1105    }
1106
1107    /// Render this spec to Markdown-compatible HTML embedding.
1108    pub fn to_markdown(&self) -> Result<String, FrameError> {
1109        self.to_svg().map(|s| wrap_svg_markdown(&s))
1110    }
1111
1112    /// Save the rendered plot to a file on disk. The file extension determines
1113    /// the target format: `.svg` (raw SVG XML), `.html` / `.htm` (standalone HTML
1114    /// document), or `.md` (markdown snippet).
1115    pub fn save<P: AsRef<std::path::Path>>(&self, path: P) -> Result<(), FrameError> {
1116        let svg = self.to_svg()?;
1117        save_rendered_svg(&svg, path, &self.method)
1118    }
1119}
1120
1121impl HistogramSpec {
1122    /// Render a grouped histogram: one inset of `bins` bars per series, NaN
1123    /// values skipped. Fails closed on non-numeric input or all-missing data.
1124    pub fn to_svg(&self) -> Result<String, FrameError> {
1125        let title = format!(
1126            "histogram ({})",
1127            self.series
1128                .first()
1129                .map(|s| s.name.as_str())
1130                .unwrap_or("values")
1131        );
1132        histogram_body(&self.series, self.bins, &title)
1133    }
1134
1135    /// [`HistogramSpec::to_svg`] as UTF-8 bytes.
1136    pub fn to_svg_bytes(&self) -> Result<Vec<u8>, FrameError> {
1137        self.to_svg().map(String::into_bytes)
1138    }
1139
1140    /// Wrap the deterministic SVG in an HTML figure container.
1141    pub fn to_html(&self) -> Result<String, FrameError> {
1142        self.to_svg().map(|s| wrap_svg_html(&s))
1143    }
1144
1145    /// Render this histogram spec to a complete HTML5 page document.
1146    pub fn to_html_page(&self, title: Option<&str>) -> Result<String, FrameError> {
1147        let title_str = title.unwrap_or(&self.method);
1148        self.to_svg().map(|s| wrap_svg_html_page(&s, title_str))
1149    }
1150
1151    /// Render this histogram spec to Markdown-compatible HTML embedding.
1152    pub fn to_markdown(&self) -> Result<String, FrameError> {
1153        self.to_svg().map(|s| wrap_svg_markdown(&s))
1154    }
1155
1156    /// Save the rendered histogram to disk (`.svg`, `.html`/`.htm`, or `.md`).
1157    pub fn save<P: AsRef<std::path::Path>>(&self, path: P) -> Result<(), FrameError> {
1158        let svg = self.to_svg()?;
1159        save_rendered_svg(&svg, path, &self.method)
1160    }
1161}
1162
1163impl BoxPlotSpec {
1164    /// Render a side-by-side box-and-whisker plot (min, q1, median, q3, max —
1165    /// linear-interpolated quantiles, NaN skipped). Fails closed when every
1166    /// series is empty, or on non-numeric input.
1167    pub fn to_svg(&self) -> Result<String, FrameError> {
1168        let title = format!(
1169            "boxplot ({})",
1170            self.series
1171                .first()
1172                .map(|s| s.name.as_str())
1173                .unwrap_or("values")
1174        );
1175        boxplot_body(&self.series, &title)
1176    }
1177
1178    /// [`BoxPlotSpec::to_svg`] as UTF-8 bytes.
1179    pub fn to_svg_bytes(&self) -> Result<Vec<u8>, FrameError> {
1180        self.to_svg().map(String::into_bytes)
1181    }
1182
1183    /// Wrap the deterministic SVG in an HTML figure container.
1184    pub fn to_html(&self) -> Result<String, FrameError> {
1185        self.to_svg().map(|s| wrap_svg_html(&s))
1186    }
1187
1188    /// Render this boxplot spec to a complete HTML5 page document.
1189    pub fn to_html_page(&self, title: Option<&str>) -> Result<String, FrameError> {
1190        let title_str = title.unwrap_or(&self.method);
1191        self.to_svg().map(|s| wrap_svg_html_page(&s, title_str))
1192    }
1193
1194    /// Render this boxplot spec to Markdown-compatible HTML embedding.
1195    pub fn to_markdown(&self) -> Result<String, FrameError> {
1196        self.to_svg().map(|s| wrap_svg_markdown(&s))
1197    }
1198
1199    /// Save the rendered boxplot to disk (`.svg`, `.html`/`.htm`, or `.md`).
1200    pub fn save<P: AsRef<std::path::Path>>(&self, path: P) -> Result<(), FrameError> {
1201        let svg = self.to_svg()?;
1202        save_rendered_svg(&svg, path, &self.method)
1203    }
1204}
1205
1206impl ScatterMatrixSpec {
1207    /// Render this scatter matrix specification to deterministic SVG XML.
1208    pub fn to_svg(&self) -> Result<String, FrameError> {
1209        scatter_matrix_body(self)
1210    }
1211
1212    /// [`ScatterMatrixSpec::to_svg`] as UTF-8 bytes.
1213    pub fn to_svg_bytes(&self) -> Result<Vec<u8>, FrameError> {
1214        self.to_svg().map(String::into_bytes)
1215    }
1216
1217    /// Wrap the deterministic SVG in an HTML figure container.
1218    pub fn to_html(&self) -> Result<String, FrameError> {
1219        self.to_svg().map(|s| wrap_svg_html(&s))
1220    }
1221
1222    /// Render this scatter matrix spec to a complete HTML5 page document.
1223    pub fn to_html_page(&self, title: Option<&str>) -> Result<String, FrameError> {
1224        let title_str = title.unwrap_or(&self.method);
1225        self.to_svg().map(|s| wrap_svg_html_page(&s, title_str))
1226    }
1227
1228    /// Render this scatter matrix spec to Markdown-compatible HTML embedding.
1229    pub fn to_markdown(&self) -> Result<String, FrameError> {
1230        self.to_svg().map(|s| wrap_svg_markdown(&s))
1231    }
1232
1233    /// Save the rendered scatter matrix to disk (`.svg`, `.html`/`.htm`, or `.md`).
1234    pub fn save<P: AsRef<std::path::Path>>(&self, path: P) -> Result<(), FrameError> {
1235        let svg = self.to_svg()?;
1236        save_rendered_svg(&svg, path, &self.method)
1237    }
1238}
1239
1240impl TablePlotSpec {
1241    /// Render this table plot specification to deterministic SVG XML.
1242    pub fn to_svg(&self) -> Result<String, FrameError> {
1243        table_body(self)
1244    }
1245
1246    /// [`TablePlotSpec::to_svg`] as UTF-8 bytes.
1247    pub fn to_svg_bytes(&self) -> Result<Vec<u8>, FrameError> {
1248        self.to_svg().map(String::into_bytes)
1249    }
1250
1251    /// Wrap the deterministic SVG in an HTML figure container.
1252    pub fn to_html(&self) -> Result<String, FrameError> {
1253        self.to_svg().map(|s| wrap_svg_html(&s))
1254    }
1255
1256    /// Render this table plot spec to a complete HTML5 page document.
1257    pub fn to_html_page(&self, title: Option<&str>) -> Result<String, FrameError> {
1258        let title_str = title.unwrap_or(&self.method);
1259        self.to_svg().map(|s| wrap_svg_html_page(&s, title_str))
1260    }
1261
1262    /// Render this table plot spec to Markdown-compatible HTML embedding.
1263    pub fn to_markdown(&self) -> Result<String, FrameError> {
1264        self.to_svg().map(|s| wrap_svg_markdown(&s))
1265    }
1266
1267    /// Save the rendered table to disk (`.svg`, `.html`/`.htm`, or `.md`).
1268    pub fn save<P: AsRef<std::path::Path>>(&self, path: P) -> Result<(), FrameError> {
1269        let svg = self.to_svg()?;
1270        save_rendered_svg(&svg, path, &self.method)
1271    }
1272}
1273
1274fn scatter_matrix_body(spec: &ScatterMatrixSpec) -> Result<String, FrameError> {
1275    let n = spec.columns.len();
1276    if n == 0 {
1277        return Err(FrameError::CompatibilityRejected(
1278            "scatter_matrix requires at least one numeric column".to_owned(),
1279        ));
1280    }
1281    if spec.series.len() != n {
1282        return Err(FrameError::CompatibilityRejected(format!(
1283            "scatter_matrix: series count ({}) does not match columns count ({n})",
1284            spec.series.len()
1285        )));
1286    }
1287
1288    if !spec.alpha.is_finite() || !(0.0..=1.0).contains(&spec.alpha) {
1289        return Err(FrameError::CompatibilityRejected(format!(
1290            "scatter_matrix: alpha must be in [0, 1], found {}",
1291            spec.alpha
1292        )));
1293    }
1294
1295    if !spec.range_padding.is_finite() || spec.range_padding < 0.0 {
1296        return Err(FrameError::CompatibilityRejected(format!(
1297            "scatter_matrix: range_padding must be finite and >= 0, found {}",
1298            spec.range_padding
1299        )));
1300    }
1301
1302    let diag = spec.diagonal.to_ascii_lowercase();
1303    if diag != "hist" && diag != "kde" && diag != "density" {
1304        return Err(FrameError::CompatibilityRejected(format!(
1305            "scatter_matrix: diagonal must be 'hist', 'kde', or 'density', found '{}'",
1306            spec.diagonal
1307        )));
1308    }
1309
1310    let views: Result<Vec<Vec<Option<f64>>>, FrameError> =
1311        spec.series.iter().map(numeric_view).collect();
1312    let views = views?;
1313
1314    let mut finite_series: Vec<Vec<f64>> = Vec::with_capacity(n);
1315    let mut scales: Vec<Scale> = Vec::with_capacity(n);
1316
1317    for (k, view) in views.iter().enumerate() {
1318        let finite_vals: Vec<f64> = view
1319            .iter()
1320            .flatten()
1321            .copied()
1322            .filter(|v| v.is_finite())
1323            .collect();
1324        if finite_vals.is_empty() {
1325            return Err(FrameError::CompatibilityRejected(format!(
1326                "no plottable (non-missing) values in column '{}'",
1327                spec.columns[k]
1328            )));
1329        }
1330        let mut c_min = finite_vals.iter().copied().fold(f64::INFINITY, f64::min);
1331        let mut c_max = finite_vals
1332            .iter()
1333            .copied()
1334            .fold(f64::NEG_INFINITY, f64::max);
1335        if (c_max - c_min).abs() < f64::EPSILON {
1336            c_min -= 1.0;
1337            c_max += 1.0;
1338        }
1339        let span = c_max - c_min;
1340        let pad = span * spec.range_padding;
1341        scales.push(Scale {
1342            min: c_min - pad,
1343            max: c_max + pad,
1344        });
1345        finite_series.push(finite_vals);
1346    }
1347
1348    let panel_size: f64 = if n == 1 {
1349        240.0
1350    } else if n == 2 {
1351        180.0
1352    } else {
1353        150.0
1354    };
1355    let margin_left: f64 = 65.0;
1356    let margin_right: f64 = 25.0;
1357    let margin_top: f64 = 35.0;
1358    let margin_bottom: f64 = 45.0;
1359    let grid_w = n as f64 * panel_size;
1360    let grid_h = n as f64 * panel_size;
1361    let total_w = margin_left + grid_w + margin_right;
1362    let total_h = margin_top + grid_h + margin_bottom;
1363    let cell_pad = 6.0;
1364
1365    let mut svg = format!(
1366        "<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"{total_w:.2}\" height=\"{total_h:.2}\" viewBox=\"0 0 {total_w:.2} {total_h:.2}\" font-family=\"monospace\" font-size=\"11\">\
1367        <rect width=\"{total_w:.2}\" height=\"{total_h:.2}\" fill=\"white\"/>\
1368        <text x=\"{:.2}\" y=\"22\" text-anchor=\"middle\" fill=\"#333\" font-size=\"13\" font-weight=\"bold\">{}</text>",
1369        total_w / 2.0,
1370        esc(&spec.method)
1371    );
1372
1373    for i in 0..n {
1374        for j in 0..n {
1375            let cell_x0 = margin_left + (j as f64) * panel_size;
1376            let cell_y0 = margin_top + (i as f64) * panel_size;
1377            let plot_x = cell_x0 + cell_pad;
1378            let plot_y = cell_y0 + cell_pad;
1379            let plot_w = panel_size - 2.0 * cell_pad;
1380            let plot_h = panel_size - 2.0 * cell_pad;
1381
1382            svg.push_str(&format!(
1383                "<rect x=\"{plot_x:.2}\" y=\"{plot_y:.2}\" width=\"{plot_w:.2}\" height=\"{plot_h:.2}\" fill=\"#fafafa\" stroke=\"#d0d0d0\" stroke-width=\"1\"/>"
1384            ));
1385
1386            for frac in [0.25, 0.5, 0.75] {
1387                let gx = plot_x + frac * plot_w;
1388                let gy = plot_y + frac * plot_h;
1389                svg.push_str(&format!(
1390                    "<line x1=\"{gx:.2}\" y1=\"{plot_y:.2}\" x2=\"{gx:.2}\" y2=\"{:.2}\" stroke=\"#ececec\" stroke-dasharray=\"2,2\"/>\
1391                    <line x1=\"{plot_x:.2}\" y1=\"{gy:.2}\" x2=\"{:.2}\" y2=\"{gy:.2}\" stroke=\"#ececec\" stroke-dasharray=\"2,2\"/>",
1392                    plot_y + plot_h,
1393                    plot_x + plot_w
1394                ));
1395            }
1396
1397            if i == j {
1398                if diag == "hist" {
1399                    let values = &finite_series[i];
1400                    let x_scale = &scales[i];
1401                    let bins = 10usize;
1402                    let mut counts = vec![0usize; bins];
1403                    let step = (x_scale.max - x_scale.min) / bins as f64;
1404                    for v in values {
1405                        let raw_idx = ((v - x_scale.min) / step).floor();
1406                        let idx = if *v >= x_scale.max {
1407                            bins - 1
1408                        } else if raw_idx <= 0.0 {
1409                            0
1410                        } else {
1411                            (raw_idx as usize).min(bins - 1)
1412                        };
1413                        counts[idx] += 1;
1414                    }
1415                    let max_count = counts.iter().copied().max().unwrap_or(1).max(1);
1416                    let bar_w = (plot_w / bins as f64 - 1.0).max(0.5);
1417                    for (bi, &cnt) in counts.iter().enumerate() {
1418                        if cnt == 0 {
1419                            continue;
1420                        }
1421                        let h = (cnt as f64 / max_count as f64) * (plot_h - 2.0);
1422                        let bx = plot_x + (bi as f64 * plot_w / bins as f64);
1423                        let by = plot_y + plot_h - h;
1424                        svg.push_str(&format!(
1425                            "<rect x=\"{bx:.2}\" y=\"{by:.2}\" width=\"{bar_w:.2}\" height=\"{h:.2}\" fill=\"#4e79a7\" fill-opacity=\"0.7\" stroke=\"white\" stroke-width=\"0.5\"/>"
1426                        ));
1427                    }
1428                } else {
1429                    let values = &finite_series[i];
1430                    let x_scale = &scales[i];
1431                    let n_pts = values.len();
1432                    let mean = values.iter().sum::<f64>() / n_pts as f64;
1433                    let var = if n_pts > 1 {
1434                        values.iter().map(|v| (v - mean).powi(2)).sum::<f64>() / (n_pts - 1) as f64
1435                    } else {
1436                        1.0
1437                    };
1438                    let std = var.sqrt();
1439                    let h = if std > 1e-9 {
1440                        1.06 * std * (n_pts as f64).powf(-0.2)
1441                    } else {
1442                        (x_scale.max - x_scale.min) / 10.0
1443                    };
1444                    let h = if h > 1e-9 { h } else { 1.0 };
1445                    let m_steps = 50usize;
1446                    let x_span = x_scale.max - x_scale.min;
1447                    let mut densities = Vec::with_capacity(m_steps);
1448                    let inv_sqrt_2pi = 1.0 / (2.0 * std::f64::consts::PI).sqrt();
1449                    for s in 0..m_steps {
1450                        let x_val = x_scale.min + (s as f64 / (m_steps - 1) as f64) * x_span;
1451                        let mut sum = 0.0;
1452                        for v in values {
1453                            let u = (x_val - v) / h;
1454                            sum += (-0.5 * u * u).exp();
1455                        }
1456                        let dens = sum / (n_pts as f64 * h) * inv_sqrt_2pi;
1457                        densities.push(dens);
1458                    }
1459                    let max_dens = densities.iter().copied().fold(0.0, f64::max).max(1e-9);
1460                    let mut poly_pts = Vec::with_capacity(m_steps);
1461                    for (s, &dens) in densities.iter().enumerate() {
1462                        let px = plot_x + (s as f64 / (m_steps - 1) as f64) * plot_w;
1463                        let frac = (dens / max_dens).clamp(0.0, 1.0);
1464                        let py = plot_y + (1.0 - frac) * (plot_h - 2.0);
1465                        poly_pts.push((px, py));
1466                    }
1467                    let mut poly_str = format!("{plot_x:.2},{:.2} ", plot_y + plot_h);
1468                    for (px, py) in &poly_pts {
1469                        poly_str.push_str(&format!("{px:.2},{py:.2} "));
1470                    }
1471                    poly_str.push_str(&format!("{:.2},{:.2}", plot_x + plot_w, plot_y + plot_h));
1472                    svg.push_str(&format!(
1473                        "<polygon points=\"{poly_str}\" fill=\"#4e79a7\" fill-opacity=\"0.2\"/>"
1474                    ));
1475                    let mut line_str = String::new();
1476                    for (k, (px, py)) in poly_pts.iter().enumerate() {
1477                        if k > 0 {
1478                            line_str.push(' ');
1479                        }
1480                        line_str.push_str(&format!("{px:.2},{py:.2}"));
1481                    }
1482                    svg.push_str(&format!(
1483                        "<polyline points=\"{line_str}\" fill=\"none\" stroke=\"#4e79a7\" stroke-width=\"1.5\"/>"
1484                    ));
1485                }
1486            } else {
1487                let x_scale = &scales[j];
1488                let y_scale = &scales[i];
1489                let x_col = &views[j];
1490                let y_col = &views[i];
1491                let num_rows = x_col.len().min(y_col.len());
1492                let x_span = (x_scale.max - x_scale.min).max(f64::EPSILON);
1493                let y_span = (y_scale.max - y_scale.min).max(f64::EPSILON);
1494                for r in 0..num_rows {
1495                    if let (Some(x_val), Some(y_val)) = (x_col[r], y_col[r])
1496                        && x_val.is_finite()
1497                        && y_val.is_finite()
1498                    {
1499                        let x_frac = ((x_val - x_scale.min) / x_span).clamp(0.0, 1.0);
1500                        let y_frac = ((y_val - y_scale.min) / y_span).clamp(0.0, 1.0);
1501                        let px = plot_x + x_frac * plot_w;
1502                        let py = plot_y + (1.0 - y_frac) * plot_h;
1503                        svg.push_str(&format!(
1504                            "<circle cx=\"{px:.2}\" cy=\"{py:.2}\" r=\"2.5\" fill=\"#4e79a7\" fill-opacity=\"{:.2}\"/>",
1505                            spec.alpha
1506                        ));
1507                    }
1508                }
1509            }
1510
1511            if j == 0 {
1512                let y_scale = &scales[i];
1513                let col_name = &spec.columns[i];
1514                let cy = plot_y + plot_h / 2.0;
1515                svg.push_str(&format!(
1516                    "<text x=\"{:.2}\" y=\"{cy:.2}\" text-anchor=\"middle\" dominant-baseline=\"central\" transform=\"rotate(-90 {:.2} {cy:.2})\" fill=\"#333\" font-size=\"11\" font-weight=\"bold\">{}</text>",
1517                    margin_left - 38.0,
1518                    margin_left - 38.0,
1519                    esc(col_name)
1520                ));
1521                for &frac in &[0.0, 0.5, 1.0] {
1522                    let val = y_scale.min + frac * (y_scale.max - y_scale.min);
1523                    let ty = plot_y + (1.0 - frac) * plot_h;
1524                    svg.push_str(&format!(
1525                        "<line x1=\"{:.2}\" y1=\"{ty:.2}\" x2=\"{plot_x:.2}\" y2=\"{ty:.2}\" stroke=\"#999\" stroke-width=\"1\"/>\
1526                        <text x=\"{:.2}\" y=\"{ty:.2}\" text-anchor=\"end\" dominant-baseline=\"middle\" fill=\"#666\" font-size=\"9\">{}</text>",
1527                        plot_x - 3.0,
1528                        plot_x - 5.0,
1529                        esc(&fmt_num(val))
1530                    ));
1531                }
1532            }
1533
1534            if i == n - 1 {
1535                let x_scale = &scales[j];
1536                let col_name = &spec.columns[j];
1537                let cx = plot_x + plot_w / 2.0;
1538                svg.push_str(&format!(
1539                    "<text x=\"{cx:.2}\" y=\"{:.2}\" text-anchor=\"middle\" fill=\"#333\" font-size=\"11\" font-weight=\"bold\">{}</text>",
1540                    total_h - 8.0,
1541                    esc(col_name)
1542                ));
1543                for &frac in &[0.0, 0.5, 1.0] {
1544                    let val = x_scale.min + frac * (x_scale.max - x_scale.min);
1545                    let tx = plot_x + frac * plot_w;
1546                    let ty = plot_y + plot_h;
1547                    svg.push_str(&format!(
1548                        "<line x1=\"{tx:.2}\" y1=\"{ty:.2}\" x2=\"{tx:.2}\" y2=\"{:.2}\" stroke=\"#999\" stroke-width=\"1\"/>\
1549                        <text x=\"{tx:.2}\" y=\"{:.2}\" text-anchor=\"middle\" dominant-baseline=\"hanging\" fill=\"#666\" font-size=\"9\">{}</text>",
1550                        ty + 3.0,
1551                        ty + 5.0,
1552                        esc(&fmt_num(val))
1553                    ));
1554                }
1555            }
1556        }
1557    }
1558
1559    svg.push_str("</svg>");
1560    Ok(svg)
1561}
1562
1563fn table_body(spec: &TablePlotSpec) -> Result<String, FrameError> {
1564    let n_rows = spec.cells.len();
1565    if n_rows == 0 {
1566        return Err(FrameError::CompatibilityRejected(
1567            "table requires at least one row".to_owned(),
1568        ));
1569    }
1570    let n_cols = spec.cells[0].len();
1571    if n_cols == 0 {
1572        return Err(FrameError::CompatibilityRejected(
1573            "table requires at least one column".to_owned(),
1574        ));
1575    }
1576
1577    for (idx, row) in spec.cells.iter().enumerate() {
1578        if row.len() != n_cols {
1579            return Err(FrameError::CompatibilityRejected(format!(
1580                "table: row {idx} length ({}) does not match column count ({n_cols})",
1581                row.len()
1582            )));
1583        }
1584    }
1585
1586    let has_row_labels = !spec.row_labels.is_empty();
1587    if has_row_labels && spec.row_labels.len() != n_rows {
1588        return Err(FrameError::CompatibilityRejected(format!(
1589            "table: row_labels length ({}) does not match row count ({n_rows})",
1590            spec.row_labels.len()
1591        )));
1592    }
1593
1594    let has_col_labels = !spec.col_labels.is_empty();
1595    if has_col_labels && spec.col_labels.len() != n_cols {
1596        return Err(FrameError::CompatibilityRejected(format!(
1597            "table: col_labels length ({}) does not match column count ({n_cols})",
1598            spec.col_labels.len()
1599        )));
1600    }
1601
1602    const ROW_H: f64 = 28.0;
1603    const HEADER_H: f64 = 32.0;
1604    const PAD_X: f64 = 20.0;
1605    const PAD_Y: f64 = 20.0;
1606    const TITLE_H: f64 = 26.0;
1607
1608    let row_label_w = if has_row_labels {
1609        let max_len = spec
1610            .row_labels
1611            .iter()
1612            .map(|s| s.chars().count())
1613            .max()
1614            .unwrap_or(4);
1615        (max_len as f64 * 8.5 + 24.0).clamp(70.0, 200.0)
1616    } else {
1617        0.0
1618    };
1619
1620    let mut col_widths = Vec::with_capacity(n_cols);
1621    for col_idx in 0..n_cols {
1622        let header_len = if has_col_labels {
1623            spec.col_labels[col_idx].chars().count()
1624        } else {
1625            0
1626        };
1627        let cell_max_len = spec
1628            .cells
1629            .iter()
1630            .map(|row| row[col_idx].chars().count())
1631            .max()
1632            .unwrap_or(0);
1633        let max_len = header_len.max(cell_max_len);
1634        let w = (max_len as f64 * 8.5 + 24.0).clamp(65.0, 220.0);
1635        col_widths.push(w);
1636    }
1637
1638    let total_table_w: f64 = row_label_w + col_widths.iter().sum::<f64>();
1639    let total_table_h: f64 =
1640        (if has_col_labels { HEADER_H } else { 0.0 }) + (n_rows as f64 * ROW_H);
1641
1642    let canvas_w = (total_table_w + PAD_X * 2.0).max(320.0);
1643    let canvas_h = total_table_h + PAD_Y * 2.0 + TITLE_H;
1644
1645    let mut svg = String::with_capacity(4096);
1646    svg.push_str(&format!(
1647        "<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 {canvas_w:.1} {canvas_h:.1}\" width=\"{canvas_w:.1}\" height=\"{canvas_h:.1}\">\n"
1648    ));
1649    svg.push_str("  <rect width=\"100%\" height=\"100%\" fill=\"#ffffff\"/>\n");
1650
1651    let title_text = if !spec.method.is_empty() {
1652        &spec.method
1653    } else {
1654        "pandas.plotting.table"
1655    };
1656    svg.push_str(&format!(
1657        "  <text x=\"{PAD_X:.1}\" y=\"{:.1}\" font-family=\"system-ui, -apple-system, sans-serif\" font-size=\"13\" font-weight=\"bold\" fill=\"#1e293b\">{}</text>\n",
1658        PAD_Y + 14.0,
1659        esc(title_text)
1660    ));
1661
1662    let start_x = PAD_X;
1663    let start_y = PAD_Y + TITLE_H;
1664
1665    // Header row (column labels)
1666    if has_col_labels {
1667        let mut curr_x = start_x;
1668        if has_row_labels {
1669            svg.push_str(&format!(
1670                "  <rect x=\"{curr_x:.1}\" y=\"{start_y:.1}\" width=\"{row_label_w:.1}\" height=\"{HEADER_H:.1}\" fill=\"#f1f5f9\" stroke=\"#cbd5e1\" stroke-width=\"1\"/>\n"
1671            ));
1672            curr_x += row_label_w;
1673        }
1674        for (col_idx, w) in col_widths.iter().enumerate() {
1675            let label = &spec.col_labels[col_idx];
1676            svg.push_str(&format!(
1677                "  <rect x=\"{curr_x:.1}\" y=\"{start_y:.1}\" width=\"{w:.1}\" height=\"{HEADER_H:.1}\" fill=\"#f1f5f9\" stroke=\"#cbd5e1\" stroke-width=\"1\"/>\n"
1678            ));
1679            let text_x = curr_x + w / 2.0;
1680            let text_y = start_y + HEADER_H / 2.0 + 4.0;
1681            svg.push_str(&format!(
1682                "  <text x=\"{text_x:.1}\" y=\"{text_y:.1}\" text-anchor=\"middle\" font-family=\"system-ui, -apple-system, sans-serif\" font-size=\"12\" font-weight=\"bold\" fill=\"#334155\">{}</text>\n",
1683                esc(label)
1684            ));
1685            curr_x += w;
1686        }
1687    }
1688
1689    let rows_start_y = if has_col_labels {
1690        start_y + HEADER_H
1691    } else {
1692        start_y
1693    };
1694
1695    for row_idx in 0..n_rows {
1696        let row_y = rows_start_y + (row_idx as f64 * ROW_H);
1697        let row_bg = if row_idx % 2 == 0 {
1698            "#ffffff"
1699        } else {
1700            "#f8fafc"
1701        };
1702        let mut curr_x = start_x;
1703
1704        if has_row_labels {
1705            let r_label = &spec.row_labels[row_idx];
1706            svg.push_str(&format!(
1707                "  <rect x=\"{curr_x:.1}\" y=\"{row_y:.1}\" width=\"{row_label_w:.1}\" height=\"{ROW_H:.1}\" fill=\"#f8fafc\" stroke=\"#cbd5e1\" stroke-width=\"1\"/>\n"
1708            ));
1709            let text_x = curr_x + 10.0;
1710            let text_y = row_y + ROW_H / 2.0 + 4.0;
1711            svg.push_str(&format!(
1712                "  <text x=\"{text_x:.1}\" y=\"{text_y:.1}\" text-anchor=\"start\" font-family=\"system-ui, -apple-system, sans-serif\" font-size=\"12\" font-weight=\"600\" fill=\"#475569\">{}</text>\n",
1713                esc(r_label)
1714            ));
1715            curr_x += row_label_w;
1716        }
1717
1718        for (col_idx, w) in col_widths.iter().enumerate() {
1719            let cell_val = &spec.cells[row_idx][col_idx];
1720            svg.push_str(&format!(
1721                "  <rect x=\"{curr_x:.1}\" y=\"{row_y:.1}\" width=\"{w:.1}\" height=\"{ROW_H:.1}\" fill=\"{row_bg}\" stroke=\"#cbd5e1\" stroke-width=\"1\"/>\n"
1722            ));
1723            let text_x = curr_x + w / 2.0;
1724            let text_y = row_y + ROW_H / 2.0 + 4.0;
1725            svg.push_str(&format!(
1726                "  <text x=\"{text_x:.1}\" y=\"{text_y:.1}\" text-anchor=\"middle\" font-family=\"system-ui, -apple-system, sans-serif\" font-size=\"12\" fill=\"#1e293b\">{}</text>\n",
1727                esc(cell_val)
1728            ));
1729            curr_x += w;
1730        }
1731    }
1732
1733    svg.push_str("</svg>");
1734    Ok(svg)
1735}
1736
1737fn wrap_svg_html(svg: &str) -> String {
1738    format!(
1739        "<div class=\"frankenpandas-plot\" style=\"display:inline-block;max-width:100%;height:auto;\">\n{svg}\n</div>"
1740    )
1741}
1742
1743fn wrap_svg_html_page(svg: &str, title: &str) -> String {
1744    let esc_title = esc(title);
1745    format!(
1746        "<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n  <meta charset=\"utf-8\">\n  <title>{esc_title}</title>\n  <style>\n    body {{\n      margin: 0;\n      padding: 24px;\n      font-family: -apple-system, BlinkMacSystemFont, \"Segoe UI\", Roboto, Helvetica, Arial, sans-serif;\n      background-color: #f8f9fa;\n      color: #212529;\n      display: flex;\n      justify-content: center;\n      align-items: center;\n      min-height: 100vh;\n    }}\n    .frankenpandas-plot-container {{\n      background: #ffffff;\n      padding: 20px;\n      border-radius: 8px;\n      box-shadow: 0 4px 12px rgba(0,0,0,0.08);\n      max-width: 100%;\n    }}\n    .frankenpandas-plot-container svg {{\n      display: block;\n      max-width: 100%;\n      height: auto;\n    }}\n  </style>\n</head>\n<body>\n  <div class=\"frankenpandas-plot-container\">\n    {svg}\n  </div>\n</body>\n</html>\n"
1747    )
1748}
1749
1750fn wrap_svg_markdown(svg: &str) -> String {
1751    format!("<div class=\"frankenpandas-plot\">\n{svg}\n</div>\n")
1752}
1753
1754fn save_rendered_svg<P: AsRef<std::path::Path>>(
1755    svg: &str,
1756    path: P,
1757    default_title: &str,
1758) -> Result<(), FrameError> {
1759    let path_ref = path.as_ref();
1760    let ext = path_ref
1761        .extension()
1762        .and_then(|e| e.to_str())
1763        .unwrap_or("")
1764        .to_ascii_lowercase();
1765
1766    let content = match ext.as_str() {
1767        "svg" => svg.as_bytes().to_vec(),
1768        "html" | "htm" => wrap_svg_html_page(svg, default_title).into_bytes(),
1769        "md" | "markdown" => wrap_svg_markdown(svg).into_bytes(),
1770        "png" | "pdf" | "jpg" | "jpeg" => {
1771            return Err(FrameError::CompatibilityRejected(format!(
1772                "saving plot directly to '.{ext}' requires an external rasterizer; supported vector formats are: .svg, .html, .htm, .md"
1773            )));
1774        }
1775        _ => svg.as_bytes().to_vec(),
1776    };
1777
1778    if let Some(parent) = path_ref.parent().filter(|p| !p.as_os_str().is_empty()) {
1779        let _ = std::fs::create_dir_all(parent);
1780    }
1781
1782    std::fs::write(path_ref, content).map_err(|err| {
1783        FrameError::CompatibilityRejected(format!(
1784            "failed to save plot to '{}': {err}",
1785            path_ref.display()
1786        ))
1787    })
1788}
1789
1790#[cfg(test)]
1791mod tests {
1792    use super::{
1793        BoxPlotSpec, FrameError, HistogramSpec, PlotKind, PlotSeriesSpec, PlotSpec, Scalar,
1794        numeric_view, quantile,
1795    };
1796    use crate::{DType, DataFrame, IndexLabel, Series};
1797
1798    fn series(name: &str, values: Vec<Scalar>) -> PlotSeriesSpec {
1799        PlotSeriesSpec {
1800            name: name.to_owned(),
1801            dtype: DType::Float64,
1802            index: (0..values.len() as i64)
1803                .map(crate::IndexLabel::Int64)
1804                .collect(),
1805            values,
1806            group_key: None,
1807        }
1808    }
1809
1810    fn floats(values: &[f64]) -> Vec<Scalar> {
1811        values.iter().map(|v| Scalar::Float64(*v)).collect()
1812    }
1813
1814    #[test]
1815    fn line_plot_renders_deterministic_svg_with_axis_and_legend() {
1816        let spec = PlotSpec {
1817            method: "plot".to_owned(),
1818            kind: PlotKind::Line,
1819            series: vec![series("s", floats(&[1.0, 2.0, 3.0]))],
1820        };
1821        let a = spec.to_svg().expect("render");
1822        let b = spec.to_svg().expect("render again");
1823        assert_eq!(a, b, "rendering must be deterministic");
1824        assert!(a.starts_with("<svg") && a.ends_with("</svg>"));
1825        assert!(a.contains("<polyline"), "line kind must draw polylines");
1826        assert!(a.contains(">s</text>"), "legend must carry the series name");
1827        assert!(a.contains(">plot</text>"), "title must carry the method");
1828    }
1829
1830    #[test]
1831    fn nan_and_null_values_become_gaps_not_coordinates() {
1832        let spec = PlotSpec {
1833            method: "plot".to_owned(),
1834            kind: PlotKind::Line,
1835            series: vec![series(
1836                "gappy",
1837                vec![
1838                    Scalar::Float64(1.0),
1839                    Scalar::Float64(f64::NAN),
1840                    Scalar::Float64(3.0),
1841                    Scalar::Null(crate::NullKind::NaN),
1842                    Scalar::Float64(5.0),
1843                ],
1844            )],
1845        };
1846        let svg = spec.to_svg().expect("render");
1847        assert!(svg.contains("<polyline"), "gaps still draw segments");
1848        // Two gaps split 5 values into 3 finite runs.
1849        assert_eq!(svg.matches("<polyline").count(), 3);
1850        assert!(
1851            !svg.contains("NaN"),
1852            "missing values must not leak as text coords"
1853        );
1854    }
1855
1856    #[test]
1857    fn all_missing_and_non_numeric_series_fail_closed() {
1858        let all_nan = PlotSpec {
1859            method: "plot".to_owned(),
1860            kind: PlotKind::Line,
1861            series: vec![series("nan", vec![Scalar::Float64(f64::NAN); 3])],
1862        };
1863        assert!(matches!(
1864            all_nan.to_svg(),
1865            Err(FrameError::CompatibilityRejected(_))
1866        ));
1867
1868        let utf8 = PlotSeriesSpec {
1869            name: "text".to_owned(),
1870            dtype: DType::Utf8,
1871            index: vec![crate::IndexLabel::Int64(0)],
1872            values: vec![Scalar::Utf8("nope".to_owned())],
1873            group_key: None,
1874        };
1875        let err = numeric_view(&utf8).expect_err("utf8 must fail closed");
1876        assert!(matches!(err, FrameError::CompatibilityRejected(_)));
1877    }
1878
1879    #[test]
1880    fn histogram_bins_cover_every_finite_value_exactly_once() {
1881        let spec = HistogramSpec {
1882            method: "hist".to_owned(),
1883            bins: 4,
1884            series: vec![series("h", floats(&[0.0, 1.0, 2.0, 3.0, f64::NAN]))],
1885        };
1886        let svg = spec.to_svg().expect("render");
1887        // 4 non-missing values across 4 bins -> 4 bars (bars are the rects
1888        // with a white stroke; the legend + background rects are not).
1889        assert_eq!(
1890            svg.matches("stroke=\"white\"").count(),
1891            4,
1892            "one bar per populated bin"
1893        );
1894    }
1895
1896    #[test]
1897    fn boxplot_quantiles_match_linear_interpolation() {
1898        let vals: Vec<f64> = (1..=5).map(f64::from).collect();
1899        assert_eq!(quantile(&vals, 0.5), 3.0);
1900        assert!((quantile(&vals, 0.25) - 2.0).abs() < 1e-9);
1901        assert!((quantile(&vals, 0.75) - 4.0).abs() < 1e-9);
1902        let even: Vec<f64> = vec![1.0, 2.0, 3.0, 4.0];
1903        assert!((quantile(&even, 0.5) - 2.5).abs() < 1e-9);
1904
1905        let spec = BoxPlotSpec {
1906            method: "boxplot".to_owned(),
1907            series: vec![series("b", floats(&[1.0, 2.0, 3.0, 4.0, 5.0]))],
1908        };
1909        let svg = spec.to_svg().expect("render");
1910        assert!(svg.contains("<rect"), "box body must be drawn");
1911    }
1912
1913    #[test]
1914    fn xml_sensitive_names_are_escaped() {
1915        let spec = PlotSpec {
1916            method: "plot".to_owned(),
1917            kind: PlotKind::Line,
1918            series: vec![series("<b>&\"x'", floats(&[1.0, 2.0]))],
1919        };
1920        let svg = spec.to_svg().expect("render");
1921        assert!(
1922            !svg.contains("<b>&"),
1923            "raw XML-sensitive text must not leak"
1924        );
1925        assert!(svg.contains("&lt;b&gt;&amp;"), "name must be escaped");
1926    }
1927
1928    #[test]
1929    fn svg_bytes_and_bar_and_pie_paths_render() {
1930        let bar = PlotSpec {
1931            method: "bar".to_owned(),
1932            kind: PlotKind::Bar,
1933            series: vec![series("b", floats(&[1.0, 5.0]))],
1934        };
1935        assert!(bar.to_svg().expect("bar").contains("<rect"));
1936        let bytes = bar.to_svg_bytes().expect("bytes");
1937        assert!(bytes.starts_with(b"<svg"));
1938
1939        let pie = PlotSpec {
1940            method: "pie".to_owned(),
1941            kind: PlotKind::Pie,
1942            series: vec![series("p", floats(&[1.0, 1.0, 2.0]))],
1943        };
1944        assert!(pie.to_svg().expect("pie").contains("<path"));
1945
1946        let negative_pie = PlotSpec {
1947            method: "pie".to_owned(),
1948            kind: PlotKind::Pie,
1949            series: vec![series("p", floats(&[-1.0, 2.0]))],
1950        };
1951        assert!(matches!(
1952            negative_pie.to_svg(),
1953            Err(FrameError::CompatibilityRejected(_))
1954        ));
1955    }
1956
1957    #[test]
1958    fn pie_chart_handles_nan_distinct_colors_and_full_circle() {
1959        // 1. Nan in pie values must be skipped, not produce NaN in path coordinates.
1960        let pie_nan = PlotSpec {
1961            method: "pie".to_owned(),
1962            kind: PlotKind::Pie,
1963            series: vec![series(
1964                "p",
1965                vec![
1966                    Scalar::Float64(10.0),
1967                    Scalar::Float64(f64::NAN),
1968                    Scalar::Float64(20.0),
1969                ],
1970            )],
1971        };
1972        let svg_nan = pie_nan.to_svg().expect("pie with nan renders");
1973        assert!(
1974            !svg_nan.contains("NaN"),
1975            "pie svg must never contain NaN coordinates"
1976        );
1977        assert!(svg_nan.contains("<path"), "pie wedges must be drawn");
1978
1979        // 2. Multi-slice pie must use distinct palette colors for slices, not monochrome.
1980        let pie_multi = PlotSpec {
1981            method: "pie".to_owned(),
1982            kind: PlotKind::Pie,
1983            series: vec![series("p", floats(&[10.0, 20.0]))],
1984        };
1985        let svg_multi = pie_multi.to_svg().expect("multi-slice pie renders");
1986        assert!(svg_multi.contains(super::palette(0)));
1987        assert!(svg_multi.contains(super::palette(1)));
1988        // Pie charts must not render Cartesian axes or gridlines
1989        assert!(
1990            !svg_multi.contains("<line x1=\"56\" y1=\"30\""),
1991            "pie charts must not render cartesian axes"
1992        );
1993
1994        // 3. Single-slice (100%) pie must render a full circle rather than degenerate 0-length arc.
1995        let pie_single = PlotSpec {
1996            method: "pie".to_owned(),
1997            kind: PlotKind::Pie,
1998            series: vec![series("p", floats(&[100.0]))],
1999        };
2000        let svg_single = pie_single.to_svg().expect("single-slice pie renders");
2001        assert!(
2002            svg_single.contains("<circle"),
2003            "100% single slice must render circle"
2004        );
2005    }
2006
2007    #[test]
2008    fn export_formats_html_page_markdown_and_file_save() {
2009        let spec = PlotSpec {
2010            method: "test_export".to_owned(),
2011            kind: PlotKind::Line,
2012            series: vec![series("y", floats(&[1.0, 2.0, 3.0]))],
2013        };
2014
2015        // 1. to_html wraps in container
2016        let html = spec.to_html().expect("to_html");
2017        assert!(html.contains("<div class=\"frankenpandas-plot\""));
2018        assert!(html.contains("<svg"));
2019
2020        // 2. to_html_page produces valid HTML5 document
2021        let page = spec.to_html_page(Some("My Title")).expect("to_html_page");
2022        assert!(page.starts_with("<!DOCTYPE html>"));
2023        assert!(page.contains("<title>My Title</title>"));
2024        assert!(page.contains("<svg"));
2025
2026        // 3. to_markdown embeds in div container
2027        let md = spec.to_markdown().expect("to_markdown");
2028        assert!(md.contains("<div class=\"frankenpandas-plot\">"));
2029        assert!(md.contains("<svg"));
2030
2031        // 4. save to tempdir
2032        let temp_dir = std::env::temp_dir().join(format!("fp_test_plot_{}", std::process::id()));
2033        let _ = std::fs::create_dir_all(&temp_dir);
2034
2035        let svg_path = temp_dir.join("plot.svg");
2036        spec.save(&svg_path).expect("save svg");
2037        let read_svg = std::fs::read_to_string(&svg_path).expect("read saved svg");
2038        assert!(read_svg.starts_with("<svg"));
2039
2040        let html_path = temp_dir.join("plot.html");
2041        spec.save(&html_path).expect("save html");
2042        let read_html = std::fs::read_to_string(&html_path).expect("read saved html");
2043        assert!(read_html.starts_with("<!DOCTYPE html>"));
2044
2045        let md_path = temp_dir.join("plot.md");
2046        spec.save(&md_path).expect("save md");
2047        let read_md = std::fs::read_to_string(&md_path).expect("read saved md");
2048        assert!(read_md.contains("<div class=\"frankenpandas-plot\">"));
2049
2050        // 5. save to unsupported raster format fails closed
2051        let png_path = temp_dir.join("plot.png");
2052        let err = spec.save(&png_path).expect_err("png must fail closed");
2053        assert!(matches!(err, FrameError::CompatibilityRejected(_)));
2054
2055        // Clean up temp test files
2056        let _ = std::fs::remove_file(&svg_path);
2057        let _ = std::fs::remove_file(&html_path);
2058        let _ = std::fs::remove_file(&md_path);
2059        let _ = std::fs::remove_dir(&temp_dir);
2060
2061        // 6. Histogram and BoxPlot export methods
2062        let hist = HistogramSpec {
2063            method: "hist".to_owned(),
2064            bins: 3,
2065            series: vec![series("h", floats(&[1.0, 2.0, 3.0]))],
2066        };
2067        assert!(
2068            hist.to_html()
2069                .expect("hist html")
2070                .contains("<div class=\"frankenpandas-plot\"")
2071        );
2072        assert!(
2073            hist.to_html_page(None)
2074                .expect("hist page")
2075                .contains("<!DOCTYPE html>")
2076        );
2077        assert!(
2078            hist.to_markdown()
2079                .expect("hist md")
2080                .contains("<div class=\"frankenpandas-plot\">")
2081        );
2082
2083        let bplot = BoxPlotSpec {
2084            method: "bplot".to_owned(),
2085            series: vec![series("b", floats(&[1.0, 2.0, 3.0]))],
2086        };
2087        assert!(
2088            bplot
2089                .to_html()
2090                .expect("bplot html")
2091                .contains("<div class=\"frankenpandas-plot\"")
2092        );
2093        assert!(
2094            bplot
2095                .to_html_page(None)
2096                .expect("bplot page")
2097                .contains("<!DOCTYPE html>")
2098        );
2099        assert!(
2100            bplot
2101                .to_markdown()
2102                .expect("bplot md")
2103                .contains("<div class=\"frankenpandas-plot\">")
2104        );
2105    }
2106
2107    #[test]
2108    fn infinite_and_neg_infinite_values_become_gaps_not_coordinates() {
2109        let spec = PlotSpec {
2110            method: "plot_gap_test".to_owned(),
2111            kind: PlotKind::Line,
2112            series: vec![series(
2113                "s_test",
2114                vec![
2115                    Scalar::Float64(1.0),
2116                    Scalar::Float64(f64::INFINITY),
2117                    Scalar::Float64(3.0),
2118                    Scalar::Float64(f64::NEG_INFINITY),
2119                    Scalar::Float64(5.0),
2120                ],
2121            )],
2122        };
2123        let svg = spec.to_svg().expect("inf values must render as gaps");
2124        assert!(
2125            !svg.contains("inf"),
2126            "SVG must not contain 'inf' coordinates: {svg}"
2127        );
2128        assert!(
2129            !svg.contains("-inf"),
2130            "SVG must not contain '-inf' coordinates: {svg}"
2131        );
2132        assert_eq!(
2133            svg.matches("<polyline").count(),
2134            3,
2135            "2 infs split 5 items into 3 runs"
2136        );
2137    }
2138
2139    #[test]
2140    fn bar_plot_supports_negative_values_and_zero_baseline() {
2141        let spec = PlotSpec {
2142            method: "bar_neg".to_owned(),
2143            kind: PlotKind::Bar,
2144            series: vec![series(
2145                "b",
2146                vec![
2147                    Scalar::Float64(-10.0),
2148                    Scalar::Float64(0.0),
2149                    Scalar::Float64(20.0),
2150                ],
2151            )],
2152        };
2153        let svg = spec.to_svg().expect("bar plot with negatives renders");
2154        assert!(svg.contains("<rect"), "bars must render as rects");
2155        assert!(
2156            !svg.contains("height=\"-"),
2157            "rect height must never be negative"
2158        );
2159    }
2160
2161    #[test]
2162    fn plot_kind_box_and_histogram_render_correct_primitives() {
2163        // PlotKind::Box on PlotSpec must render boxplot primitives (rect + line whiskers)
2164        let box_spec = PlotSpec {
2165            method: "box_kind".to_owned(),
2166            kind: PlotKind::Box,
2167            series: vec![series("box_s", floats(&[1.0, 2.0, 3.0, 4.0, 5.0]))],
2168        };
2169        let svg_box = box_spec.to_svg().expect("box kind renders");
2170        assert!(svg_box.contains("<rect"), "boxplot must have box rect");
2171        assert!(svg_box.contains("<line"), "boxplot must have whisker lines");
2172        assert!(svg_box.contains("box_s"), "boxplot must carry series name");
2173
2174        // PlotKind::Histogram on PlotSpec must render histogram primitives
2175        let hist_spec = PlotSpec {
2176            method: "hist_kind".to_owned(),
2177            kind: PlotKind::Histogram,
2178            series: vec![series("hist_s", floats(&[1.0, 2.0, 2.5, 3.0]))],
2179        };
2180        let svg_hist = hist_spec.to_svg().expect("hist kind renders");
2181        assert!(svg_hist.contains("<rect"), "hist must have bars");
2182        assert!(svg_hist.contains("hist_s"), "hist must carry series name");
2183    }
2184
2185    #[test]
2186    fn legend_overflow_handles_more_than_six_series() {
2187        let mut s_vec = Vec::new();
2188        for i in 0..8 {
2189            s_vec.push(series(&format!("col_{i}"), floats(&[1.0, 2.0])));
2190        }
2191        let spec = PlotSpec {
2192            method: "multi".to_owned(),
2193            kind: PlotKind::Line,
2194            series: s_vec,
2195        };
2196        let svg = spec.to_svg().expect("multi series renders");
2197        assert!(
2198            svg.contains("+3 more"),
2199            "overflow legend must display +3 more"
2200        );
2201    }
2202
2203    #[test]
2204    fn barh_kde_density_hexbin_render_expected_svg_elements() {
2205        // 1. Barh
2206        let barh_spec = PlotSpec {
2207            method: "test_barh".to_owned(),
2208            kind: PlotKind::Barh,
2209            series: vec![series("bh", floats(&[10.0, 20.0, 15.0]))],
2210        };
2211        let barh_svg = barh_spec.to_svg().expect("barh renders");
2212        assert!(barh_svg.contains("<rect"), "barh must contain rects");
2213        assert!(
2214            barh_svg.contains("bh"),
2215            "barh must contain legend series name"
2216        );
2217
2218        // 2. KDE & Density
2219        let kde_spec = PlotSpec {
2220            method: "test_kde".to_owned(),
2221            kind: PlotKind::Kde,
2222            series: vec![series("kd", floats(&[1.0, 2.0, 2.5, 3.0, 4.0, 5.0]))],
2223        };
2224        let kde_svg = kde_spec.to_svg().expect("kde renders");
2225        assert!(
2226            kde_svg.contains("<polyline"),
2227            "kde must contain polyline curve"
2228        );
2229        assert!(kde_svg.contains("<polygon"), "kde must contain filled area");
2230
2231        let density_spec = PlotSpec {
2232            method: "test_density".to_owned(),
2233            kind: PlotKind::Density,
2234            series: vec![series("dens", floats(&[1.0, 2.0, 2.5, 3.0, 4.0, 5.0]))],
2235        };
2236        let dens_svg = density_spec.to_svg().expect("density renders");
2237        assert!(
2238            dens_svg.contains("<polyline"),
2239            "density must contain polyline curve"
2240        );
2241
2242        // 3. Hexbin
2243        let hexbin_spec = PlotSpec {
2244            method: "test_hexbin".to_owned(),
2245            kind: PlotKind::Hexbin,
2246            series: vec![
2247                series("x", floats(&[1.0, 2.0, 3.0, 4.0, 5.0])),
2248                series("y", floats(&[2.0, 4.0, 6.0, 8.0, 10.0])),
2249            ],
2250        };
2251        let hex_svg = hexbin_spec.to_svg().expect("hexbin renders");
2252        assert!(
2253            hex_svg.contains("<circle"),
2254            "hexbin must contain binned circles"
2255        );
2256    }
2257
2258    #[test]
2259    fn scatter_xy_renders_numeric_2d_axes_and_mapped_coordinates() {
2260        let spec = PlotSpec {
2261            method: "DataFrame.plot.scatter(x='wt', y='mpg')".to_owned(),
2262            kind: PlotKind::Scatter,
2263            series: vec![
2264                series("wt", floats(&[10.0, 20.0, 30.0])),
2265                series("mpg", floats(&[100.0, 200.0, 300.0])),
2266            ],
2267        };
2268        let svg = spec.to_svg().expect("xy scatter renders");
2269        // Must contain circles for data points
2270        assert!(svg.contains("<circle"));
2271        assert_eq!(svg.matches("<circle").count(), 3);
2272        // Point (10.0, 100.0) -> left (56.00), bottom (358.00)
2273        assert!(
2274            svg.contains("cx=\"56.00\" cy=\"358.00\""),
2275            "lower-left point must map to (56.00, 358.00): {svg}"
2276        );
2277        // Point (30.0, 300.0) -> right (624.00), top (30.00)
2278        assert!(
2279            svg.contains("cx=\"624.00\" cy=\"30.00\""),
2280            "upper-right point must map to (624.00, 30.00): {svg}"
2281        );
2282        // Point (20.0, 200.0) -> center (340.00, 194.00)
2283        assert!(
2284            svg.contains("cx=\"340.00\" cy=\"194.00\""),
2285            "center point must map to (340.00, 194.00): {svg}"
2286        );
2287        // Must contain numeric 2D tick labels for both axes
2288        assert!(svg.contains(">10</text>"));
2289        assert!(svg.contains(">30</text>"));
2290        assert!(svg.contains(">100</text>"));
2291        assert!(svg.contains(">300</text>"));
2292        // Legend must display "mpg vs wt"
2293        assert!(svg.contains("mpg vs wt"));
2294    }
2295
2296    #[test]
2297    fn hexbin_xy_renders_numeric_2d_axes_and_legend() {
2298        let spec = PlotSpec {
2299            method: "DataFrame.plot.hexbin(x='a', y='b')".to_owned(),
2300            kind: PlotKind::Hexbin,
2301            series: vec![
2302                series("a", floats(&[1.0, 2.0, 3.0, 4.0, 5.0])),
2303                series("b", floats(&[10.0, 20.0, 30.0, 40.0, 50.0])),
2304            ],
2305        };
2306        let svg = spec.to_svg().expect("xy hexbin renders");
2307        assert!(svg.contains("<circle"));
2308        assert!(svg.contains("b vs a"));
2309        assert!(svg.contains(">1</text>"));
2310        assert!(svg.contains(">5</text>"));
2311        assert!(svg.contains(">10</text>"));
2312        assert!(svg.contains(">50</text>"));
2313    }
2314
2315    #[test]
2316    fn dataframe_scatter_and_hexbin_xy_methods() {
2317        use crate::{DataFrame, IndexLabel, Series};
2318        let labels = vec![
2319            IndexLabel::Int64(0),
2320            IndexLabel::Int64(1),
2321            IndexLabel::Int64(2),
2322        ];
2323        let sx = Series::from_values("x", labels.clone(), floats(&[10.0, 20.0, 30.0])).unwrap();
2324        let sy = Series::from_values("y", labels, floats(&[100.0, 200.0, 300.0])).unwrap();
2325        let df = DataFrame::from_series(vec![sx, sy]).unwrap();
2326
2327        // 1. scatter_xy
2328        let sc_spec = df.scatter_xy("x", "y").expect("scatter_xy");
2329        assert_eq!(sc_spec.kind, PlotKind::Scatter);
2330        assert_eq!(sc_spec.method, "DataFrame.plot.scatter(x='x', y='y')");
2331        let svg = df.scatter_xy_to_svg("x", "y").expect("scatter_xy_to_svg");
2332        assert!(svg.contains("<circle"));
2333        let html = df.scatter_xy_to_html("x", "y").expect("scatter_xy_to_html");
2334        assert!(html.contains("<svg"));
2335
2336        // 2. hexbin_xy & hexbin_columns
2337        let hb_spec = df.hexbin_xy("x", "y").expect("hexbin_xy");
2338        assert_eq!(hb_spec.kind, PlotKind::Hexbin);
2339        let hb_svg = df.hexbin_xy_to_svg("x", "y").expect("hexbin_xy_to_svg");
2340        assert!(hb_svg.contains("<circle"));
2341        let hb_html = df.hexbin_xy_to_html("x", "y").expect("hexbin_xy_to_html");
2342        assert!(hb_html.contains("<svg"));
2343
2344        // 3. plot_xy
2345        let p_sc = df
2346            .plot_xy(PlotKind::Scatter, "x", "y")
2347            .expect("plot_xy scatter");
2348        assert_eq!(p_sc.kind, PlotKind::Scatter);
2349        let p_hb = df
2350            .plot_xy(PlotKind::Hexbin, "x", "y")
2351            .expect("plot_xy hexbin");
2352        assert_eq!(p_hb.kind, PlotKind::Hexbin);
2353        let p_line = df.plot_xy(PlotKind::Line, "x", "y").expect("plot_xy line");
2354        assert_eq!(p_line.kind, PlotKind::Line);
2355        assert_eq!(p_line.series.len(), 2);
2356    }
2357
2358    #[test]
2359    fn dataframe_hist_and_boxplot_columns_and_by() {
2360        use crate::{DataFrame, IndexLabel, Series};
2361        let labels = vec![
2362            IndexLabel::Int64(0),
2363            IndexLabel::Int64(1),
2364            IndexLabel::Int64(2),
2365            IndexLabel::Int64(3),
2366        ];
2367        let sa = Series::from_values("a", labels.clone(), floats(&[1.0, 2.0, 3.0, 4.0])).unwrap();
2368        let sb =
2369            Series::from_values("b", labels.clone(), floats(&[10.0, 20.0, 30.0, 40.0])).unwrap();
2370        let sc = Series::from_values(
2371            "category",
2372            labels.clone(),
2373            vec![
2374                Scalar::Utf8("cat1".to_string()),
2375                Scalar::Utf8("cat2".to_string()),
2376                Scalar::Utf8("cat1".to_string()),
2377                Scalar::Utf8("cat2".to_string()),
2378            ],
2379        )
2380        .unwrap();
2381        let df = DataFrame::from_series(vec![sa, sb, sc]).unwrap();
2382
2383        // 1. hist_columns
2384        let h_cols = df.hist_columns(&["a", "b"], 5).expect("hist_columns");
2385        assert_eq!(h_cols.method, "DataFrame.hist(column=[\"a\", \"b\"])");
2386        assert_eq!(h_cols.bins, 5);
2387        assert_eq!(h_cols.series.len(), 2);
2388        let h_svg = df
2389            .hist_columns_to_svg(&["a", "b"], 5)
2390            .expect("hist_columns_to_svg");
2391        assert!(h_svg.contains("<svg"));
2392        let h_html = df
2393            .hist_columns_to_html(&["a", "b"], 5)
2394            .expect("hist_columns_to_html");
2395        assert!(h_html.contains("<div class=\"frankenpandas-plot\""));
2396        assert!(h_html.contains("<svg"));
2397
2398        // 2. hist_by
2399        let h_by = df.hist_by("a", "category", 4).expect("hist_by");
2400        assert_eq!(h_by.method, "DataFrame.hist(column='a', by='category')");
2401        assert_eq!(h_by.bins, 4);
2402        assert_eq!(h_by.series.len(), 2); // cat1 and cat2
2403        let h_by_svg = df
2404            .hist_by_to_svg("a", "category", 4)
2405            .expect("hist_by_to_svg");
2406        assert!(h_by_svg.contains("<svg"));
2407        let h_by_html = df
2408            .hist_by_to_html("a", "category", 4)
2409            .expect("hist_by_to_html");
2410        assert!(h_by_html.contains("<div class=\"frankenpandas-plot\""));
2411        assert!(h_by_html.contains("<svg"));
2412
2413        // 3. boxplot_columns
2414        let b_cols = df.boxplot_columns(&["a", "b"]).expect("boxplot_columns");
2415        assert_eq!(b_cols.method, "DataFrame.boxplot(column=[\"a\", \"b\"])");
2416        assert_eq!(b_cols.series.len(), 2);
2417        let b_svg = df
2418            .boxplot_columns_to_svg(&["a", "b"])
2419            .expect("boxplot_columns_to_svg");
2420        assert!(b_svg.contains("<svg"));
2421        let b_html = df
2422            .boxplot_columns_to_html(&["a", "b"])
2423            .expect("boxplot_columns_to_html");
2424        assert!(b_html.contains("<div class=\"frankenpandas-plot\""));
2425        assert!(b_html.contains("<svg"));
2426
2427        // 4. boxplot_by
2428        let b_by = df.boxplot_by("b", "category").expect("boxplot_by");
2429        assert_eq!(b_by.method, "DataFrame.boxplot(column='b', by='category')");
2430        assert_eq!(b_by.series.len(), 2); // cat1 and cat2
2431        let b_by_svg = df
2432            .boxplot_by_to_svg("b", "category")
2433            .expect("boxplot_by_to_svg");
2434        assert!(b_by_svg.contains("<svg"));
2435        let b_by_html = df
2436            .boxplot_by_to_html("b", "category")
2437            .expect("boxplot_by_to_html");
2438        assert!(b_by_html.contains("<div class=\"frankenpandas-plot\""));
2439        assert!(b_by_html.contains("<svg"));
2440    }
2441
2442    #[test]
2443    fn dataframe_groupby_scatter_and_hexbin() {
2444        use crate::{DataFrame, IndexLabel, Series};
2445        let labels = vec![
2446            IndexLabel::Int64(0),
2447            IndexLabel::Int64(1),
2448            IndexLabel::Int64(2),
2449            IndexLabel::Int64(3),
2450        ];
2451        let sx = Series::from_values("x", labels.clone(), floats(&[1.0, 2.0, 3.0, 4.0])).unwrap();
2452        let sy =
2453            Series::from_values("y", labels.clone(), floats(&[10.0, 20.0, 30.0, 40.0])).unwrap();
2454        let sg = Series::from_values(
2455            "group",
2456            labels.clone(),
2457            vec![
2458                Scalar::Utf8("alpha".to_string()),
2459                Scalar::Utf8("beta".to_string()),
2460                Scalar::Utf8("alpha".to_string()),
2461                Scalar::Utf8("beta".to_string()),
2462            ],
2463        )
2464        .unwrap();
2465        let df = DataFrame::from_series(vec![sx, sy, sg]).unwrap();
2466        let gb = df.groupby(&["group"]).unwrap();
2467
2468        // 1. scatter_columns and scatter_xy
2469        let sc_spec = gb.scatter_columns("x", "y").expect("gb scatter_columns");
2470        assert_eq!(sc_spec.kind, PlotKind::Scatter);
2471        assert_eq!(
2472            sc_spec.method,
2473            "DataFrameGroupBy.plot.scatter(x='x', y='y')"
2474        );
2475        assert_eq!(sc_spec.series.len(), 4); // 2 groups * 2 cols (x, y)
2476        let sc_svg = gb
2477            .scatter_columns_to_svg("x", "y")
2478            .expect("gb scatter_columns_to_svg");
2479        assert!(sc_svg.contains("<svg"));
2480        assert!(sc_svg.contains("<circle"));
2481        let sc_html = gb
2482            .scatter_xy_to_html("x", "y")
2483            .expect("gb scatter_xy_to_html");
2484        assert!(sc_html.contains("<div class=\"frankenpandas-plot\""));
2485        assert!(sc_html.contains("<svg"));
2486
2487        // 2. hexbin_columns and hexbin_xy
2488        let hb_spec = gb.hexbin_columns("x", "y").expect("gb hexbin_columns");
2489        assert_eq!(hb_spec.kind, PlotKind::Hexbin);
2490        assert_eq!(hb_spec.method, "DataFrameGroupBy.plot.hexbin(x='x', y='y')");
2491        assert_eq!(hb_spec.series.len(), 4);
2492        let hb_svg = gb
2493            .hexbin_columns_to_svg("x", "y")
2494            .expect("gb hexbin_columns_to_svg");
2495        assert!(hb_svg.contains("<svg"));
2496        assert!(hb_svg.contains("<circle"));
2497        let hb_html = gb
2498            .hexbin_xy_to_html("x", "y")
2499            .expect("gb hexbin_xy_to_html");
2500        assert!(hb_html.contains("<div class=\"frankenpandas-plot\""));
2501        assert!(hb_html.contains("<svg"));
2502
2503        // 3. plot_xy
2504        let p_sc = gb
2505            .plot_xy(PlotKind::Scatter, "x", "y")
2506            .expect("gb plot_xy scatter");
2507        assert_eq!(p_sc.kind, PlotKind::Scatter);
2508        assert_eq!(p_sc.series.len(), 4);
2509
2510        let p_hb = gb
2511            .plot_xy(PlotKind::Hexbin, "x", "y")
2512            .expect("gb plot_xy hexbin");
2513        assert_eq!(p_hb.kind, PlotKind::Hexbin);
2514        assert_eq!(p_hb.series.len(), 4);
2515
2516        // Invalid plot_xy kind error check
2517        let err = gb.plot_xy(PlotKind::Line, "x", "y");
2518        assert!(err.is_err());
2519    }
2520
2521    #[test]
2522    fn dataframe_and_groupby_hist_and_boxplot_ergonomics() {
2523        use crate::{DataFrame, IndexLabel, Series};
2524        let labels = vec![
2525            IndexLabel::Int64(0),
2526            IndexLabel::Int64(1),
2527            IndexLabel::Int64(2),
2528            IndexLabel::Int64(3),
2529        ];
2530        let sx = Series::from_values("x", labels.clone(), floats(&[1.0, 2.0, 3.0, 4.0])).unwrap();
2531        let sy =
2532            Series::from_values("y", labels.clone(), floats(&[10.0, 20.0, 30.0, 40.0])).unwrap();
2533        let sg = Series::from_values(
2534            "group",
2535            labels.clone(),
2536            vec![
2537                Scalar::Utf8("alpha".to_string()),
2538                Scalar::Utf8("beta".to_string()),
2539                Scalar::Utf8("alpha".to_string()),
2540                Scalar::Utf8("beta".to_string()),
2541            ],
2542        )
2543        .unwrap();
2544        let df = DataFrame::from_series(vec![sx.clone(), sy.clone(), sg.clone()]).unwrap();
2545        let df_num = DataFrame::from_series(vec![sx.clone(), sy.clone()]).unwrap();
2546        let gb = df.groupby(&["group"]).unwrap();
2547        let by_s = sg.clone();
2548        let ser_gb = sx.groupby(&by_s).unwrap();
2549
2550        let temp_dir =
2551            std::env::temp_dir().join(format!("fp_test_hist_box_{}", std::process::id()));
2552        let _ = std::fs::create_dir_all(&temp_dir);
2553
2554        // 1. DataFrame hist_with_bins (svg, html, file)
2555        let df_h_svg = df_num
2556            .hist_with_bins_to_svg(6)
2557            .expect("df hist_with_bins_to_svg");
2558        assert!(df_h_svg.contains("<svg"));
2559        assert!(df_h_svg.contains("<rect"));
2560        let df_h_html = df_num
2561            .hist_with_bins_to_html(6)
2562            .expect("df hist_with_bins_to_html");
2563        assert!(df_h_html.contains("<div class=\"frankenpandas-plot\""));
2564        assert!(df_h_html.contains("<svg"));
2565        let df_h_file = temp_dir.join("df_hist.svg");
2566        df_num
2567            .hist_with_bins_to_file(6, &df_h_file)
2568            .expect("df hist_with_bins_to_file");
2569        assert!(
2570            std::fs::read_to_string(&df_h_file)
2571                .expect("read df_hist")
2572                .contains("<svg")
2573        );
2574
2575        // 2. DataFrame hist_columns & boxplot_columns (svg, html, file)
2576        let df_hc_svg = df
2577            .hist_columns_to_svg(&["x", "y"], 5)
2578            .expect("df hist_columns_to_svg");
2579        assert!(df_hc_svg.contains("<svg"));
2580        let df_hc_html = df
2581            .hist_columns_to_html(&["x", "y"], 5)
2582            .expect("df hist_columns_to_html");
2583        assert!(df_hc_html.contains("<div class=\"frankenpandas-plot\""));
2584        let df_hc_file = temp_dir.join("df_hist_cols.svg");
2585        df.hist_columns_to_file(&["x", "y"], 5, &df_hc_file)
2586            .expect("df hist_columns_to_file");
2587        assert!(
2588            std::fs::read_to_string(&df_hc_file)
2589                .expect("read df_hist_cols")
2590                .contains("<svg")
2591        );
2592
2593        let df_bc_svg = df
2594            .boxplot_columns_to_svg(&["x"])
2595            .expect("df boxplot_columns_to_svg");
2596        assert!(df_bc_svg.contains("<svg"));
2597        assert!(df_bc_svg.contains("<line"));
2598        let df_bc_html = df
2599            .boxplot_columns_to_html(&["x"])
2600            .expect("df boxplot_columns_to_html");
2601        assert!(df_bc_html.contains("<div class=\"frankenpandas-plot\""));
2602        let df_bc_file = temp_dir.join("df_box_cols.svg");
2603        df.boxplot_columns_to_file(&["x"], &df_bc_file)
2604            .expect("df boxplot_columns_to_file");
2605        assert!(
2606            std::fs::read_to_string(&df_bc_file)
2607                .expect("read df_box_cols")
2608                .contains("<svg")
2609        );
2610
2611        // 3. Series hist_with_bins (svg, html, file)
2612        let s_h_svg = sx
2613            .hist_with_bins_to_svg(4)
2614            .expect("s hist_with_bins_to_svg");
2615        assert!(s_h_svg.contains("<svg"));
2616        let s_h_html = sx
2617            .hist_with_bins_to_html(4)
2618            .expect("s hist_with_bins_to_html");
2619        assert!(s_h_html.contains("<div class=\"frankenpandas-plot\""));
2620        let s_h_file = temp_dir.join("s_hist.svg");
2621        sx.hist_with_bins_to_file(4, &s_h_file)
2622            .expect("s hist_with_bins_to_file");
2623        assert!(
2624            std::fs::read_to_string(&s_h_file)
2625                .expect("read s_hist")
2626                .contains("<svg")
2627        );
2628
2629        // 4. DataFrameGroupBy hist_with_bins (svg, html, file)
2630        let gb_h_svg = gb
2631            .hist_with_bins_to_svg(5)
2632            .expect("gb hist_with_bins_to_svg");
2633        assert!(gb_h_svg.contains("<svg"));
2634        let gb_h_html = gb
2635            .hist_with_bins_to_html(5)
2636            .expect("gb hist_with_bins_to_html");
2637        assert!(gb_h_html.contains("<div class=\"frankenpandas-plot\""));
2638        let gb_h_file = temp_dir.join("gb_hist.svg");
2639        gb.hist_with_bins_to_file(5, &gb_h_file)
2640            .expect("gb hist_with_bins_to_file");
2641        assert!(
2642            std::fs::read_to_string(&gb_h_file)
2643                .expect("read gb_hist")
2644                .contains("<svg")
2645        );
2646
2647        // 5. DataFrameGroupBy hist_columns & boxplot_columns (svg, html, file)
2648        let gb_hc_svg = gb
2649            .hist_columns_to_svg(&["x", "y"], 5)
2650            .expect("gb hist_columns_to_svg");
2651        assert!(gb_hc_svg.contains("<svg"));
2652        let gb_hc_html = gb
2653            .hist_columns_to_html(&["x", "y"], 5)
2654            .expect("gb hist_columns_to_html");
2655        assert!(gb_hc_html.contains("<div class=\"frankenpandas-plot\""));
2656        let gb_hc_file = temp_dir.join("gb_hist_cols.svg");
2657        gb.hist_columns_to_file(&["x", "y"], 5, &gb_hc_file)
2658            .expect("gb hist_columns_to_file");
2659        assert!(
2660            std::fs::read_to_string(&gb_hc_file)
2661                .expect("read gb_hist_cols")
2662                .contains("<svg")
2663        );
2664
2665        let gb_bc_svg = gb
2666            .boxplot_columns_to_svg(&["x"])
2667            .expect("gb boxplot_columns_to_svg");
2668        assert!(gb_bc_svg.contains("<svg"));
2669        assert!(gb_bc_svg.contains("<line"));
2670        let gb_bc_html = gb
2671            .boxplot_columns_to_html(&["x"])
2672            .expect("gb boxplot_columns_to_html");
2673        assert!(gb_bc_html.contains("<div class=\"frankenpandas-plot\""));
2674        let gb_bc_file = temp_dir.join("gb_box_cols.svg");
2675        gb.boxplot_columns_to_file(&["x"], &gb_bc_file)
2676            .expect("gb boxplot_columns_to_file");
2677        assert!(
2678            std::fs::read_to_string(&gb_bc_file)
2679                .expect("read gb_box_cols")
2680                .contains("<svg")
2681        );
2682
2683        // 6. SeriesGroupBy hist_with_bins (svg, html, file)
2684        let sgb_h_svg = ser_gb
2685            .hist_with_bins_to_svg(4)
2686            .expect("sgb hist_with_bins_to_svg");
2687        assert!(sgb_h_svg.contains("<svg"));
2688        let sgb_h_html = ser_gb
2689            .hist_with_bins_to_html(4)
2690            .expect("sgb hist_with_bins_to_html");
2691        assert!(sgb_h_html.contains("<div class=\"frankenpandas-plot\""));
2692        let sgb_h_file = temp_dir.join("sgb_hist.svg");
2693        ser_gb
2694            .hist_with_bins_to_file(4, &sgb_h_file)
2695            .expect("sgb hist_with_bins_to_file");
2696        assert!(
2697            std::fs::read_to_string(&sgb_h_file)
2698                .expect("read sgb_hist")
2699                .contains("<svg")
2700        );
2701
2702        // 7. Error handling for missing columns
2703        assert!(gb.hist_columns(&["nonexistent"], 5).is_err());
2704        assert!(gb.boxplot_columns(&["nonexistent"]).is_err());
2705        assert!(df.hist_columns(&["nonexistent"], 5).is_err());
2706        assert!(df.boxplot_columns(&["nonexistent"]).is_err());
2707
2708        // Cleanup temp files
2709        let _ = std::fs::remove_file(&df_h_file);
2710        let _ = std::fs::remove_file(&df_hc_file);
2711        let _ = std::fs::remove_file(&df_bc_file);
2712        let _ = std::fs::remove_file(&s_h_file);
2713        let _ = std::fs::remove_file(&gb_h_file);
2714        let _ = std::fs::remove_file(&gb_hc_file);
2715        let _ = std::fs::remove_file(&gb_bc_file);
2716        let _ = std::fs::remove_file(&sgb_h_file);
2717        let _ = std::fs::remove_dir(&temp_dir);
2718    }
2719
2720    #[test]
2721    fn lag_plot_and_autocorrelation_plot_and_grouped_plots() {
2722        use crate::{DataFrame, IndexLabel, Series};
2723        let labels = vec![
2724            IndexLabel::Int64(0),
2725            IndexLabel::Int64(1),
2726            IndexLabel::Int64(2),
2727            IndexLabel::Int64(3),
2728            IndexLabel::Int64(4),
2729            IndexLabel::Int64(5),
2730        ];
2731        let sx = Series::from_values(
2732            "val",
2733            labels.clone(),
2734            floats(&[1.0, 2.0, 3.0, 2.0, 1.0, 2.0]),
2735        )
2736        .unwrap();
2737        let sy = Series::from_values(
2738            "val2",
2739            labels.clone(),
2740            floats(&[10.0, 20.0, 15.0, 25.0, 30.0, 20.0]),
2741        )
2742        .unwrap();
2743        let sg = Series::from_values(
2744            "group",
2745            labels.clone(),
2746            vec![
2747                Scalar::Utf8("A".to_string()),
2748                Scalar::Utf8("B".to_string()),
2749                Scalar::Utf8("A".to_string()),
2750                Scalar::Utf8("B".to_string()),
2751                Scalar::Utf8("A".to_string()),
2752                Scalar::Utf8("B".to_string()),
2753            ],
2754        )
2755        .unwrap();
2756
2757        let df = DataFrame::from_series(vec![sx.clone(), sy.clone(), sg.clone()]).unwrap();
2758
2759        let temp_dir =
2760            std::env::temp_dir().join(format!("fp_test_lag_ac_grouped_{}", std::process::id()));
2761        let _ = std::fs::create_dir_all(&temp_dir);
2762
2763        // 1. Series lag_plot
2764        let lag_spec = sx.lag_plot(1).expect("lag_plot(1)");
2765        assert_eq!(lag_spec.kind, PlotKind::Scatter);
2766        assert_eq!(lag_spec.series.len(), 2);
2767        assert_eq!(lag_spec.series[0].name, "y(t)");
2768        assert_eq!(lag_spec.series[1].name, "y(t+1)");
2769        let lag_svg = sx.lag_plot_to_svg(1).expect("lag_plot_to_svg");
2770        assert!(lag_svg.contains("<svg"));
2771        assert!(lag_svg.contains("<circle"));
2772        let lag_html = sx.lag_plot_to_html(1).expect("lag_plot_to_html");
2773        assert!(lag_html.contains("<div class=\"frankenpandas-plot\""));
2774        let lag_file = temp_dir.join("lag.svg");
2775        sx.lag_plot_to_file(1, &lag_file).expect("lag_plot_to_file");
2776        assert!(
2777            std::fs::read_to_string(&lag_file)
2778                .expect("read lag")
2779                .contains("<svg")
2780        );
2781
2782        // 2. Series autocorrelation_plot
2783        let ac_spec = sx.autocorrelation_plot().expect("autocorrelation_plot");
2784        assert_eq!(ac_spec.kind, PlotKind::Line);
2785        assert_eq!(ac_spec.series.len(), 1);
2786        let ac_svg = sx
2787            .autocorrelation_plot_to_svg()
2788            .expect("autocorrelation_plot_to_svg");
2789        assert!(ac_svg.contains("<svg"));
2790        assert!(ac_svg.contains("<polyline"));
2791        let ac_html = sx
2792            .autocorrelation_plot_to_html()
2793            .expect("autocorrelation_plot_to_html");
2794        assert!(ac_html.contains("<div class=\"frankenpandas-plot\""));
2795        let ac_file = temp_dir.join("autocorr.svg");
2796        sx.autocorrelation_plot_to_file(&ac_file)
2797            .expect("autocorrelation_plot_to_file");
2798        assert!(
2799            std::fs::read_to_string(&ac_file)
2800                .expect("read autocorr")
2801                .contains("<svg")
2802        );
2803
2804        // 3. Error cases for lag_plot and autocorrelation_plot
2805        assert!(sg.lag_plot(1).is_err());
2806        assert!(sg.autocorrelation_plot().is_err());
2807        assert!(sx.lag_plot(10).is_err());
2808        let s_short =
2809            Series::from_values("short", vec![labels[0].clone()], floats(&[1.0])).unwrap();
2810        assert!(s_short.autocorrelation_plot().is_err());
2811
2812        // 4. DataFrame hist_columns_by and hist_by_all
2813        let hc_by_svg = df
2814            .hist_columns_by_to_svg(&["val", "val2"], "group", 5)
2815            .expect("hist_columns_by_to_svg");
2816        assert!(hc_by_svg.contains("<svg"));
2817        let hc_by_html = df
2818            .hist_columns_by_to_html(&["val", "val2"], "group", 5)
2819            .expect("hist_columns_by_to_html");
2820        assert!(hc_by_html.contains("<div class=\"frankenpandas-plot\""));
2821        let hc_by_file = temp_dir.join("hist_cols_by.svg");
2822        df.hist_columns_by_to_file(&["val", "val2"], "group", 5, &hc_by_file)
2823            .expect("hist_columns_by_to_file");
2824        assert!(
2825            std::fs::read_to_string(&hc_by_file)
2826                .expect("read hist_cols_by")
2827                .contains("<svg")
2828        );
2829
2830        let h_all_svg = df
2831            .hist_by_all_to_svg("group", 4)
2832            .expect("hist_by_all_to_svg");
2833        assert!(h_all_svg.contains("<svg"));
2834        let h_all_html = df
2835            .hist_by_all_to_html("group", 4)
2836            .expect("hist_by_all_to_html");
2837        assert!(h_all_html.contains("<div class=\"frankenpandas-plot\""));
2838        let h_all_file = temp_dir.join("hist_by_all.svg");
2839        df.hist_by_all_to_file("group", 4, &h_all_file)
2840            .expect("hist_by_all_to_file");
2841        assert!(
2842            std::fs::read_to_string(&h_all_file)
2843                .expect("read hist_by_all")
2844                .contains("<svg")
2845        );
2846
2847        // 5. DataFrame boxplot_columns_by and boxplot_by_all
2848        let bc_by_svg = df
2849            .boxplot_columns_by_to_svg(&["val", "val2"], "group")
2850            .expect("boxplot_columns_by_to_svg");
2851        assert!(bc_by_svg.contains("<svg"));
2852        assert!(bc_by_svg.contains("<line"));
2853        let bc_by_html = df
2854            .boxplot_columns_by_to_html(&["val", "val2"], "group")
2855            .expect("boxplot_columns_by_to_html");
2856        assert!(bc_by_html.contains("<div class=\"frankenpandas-plot\""));
2857        let bc_by_file = temp_dir.join("box_cols_by.svg");
2858        df.boxplot_columns_by_to_file(&["val", "val2"], "group", &bc_by_file)
2859            .expect("boxplot_columns_by_to_file");
2860        assert!(
2861            std::fs::read_to_string(&bc_by_file)
2862                .expect("read box_cols_by")
2863                .contains("<svg")
2864        );
2865
2866        let b_all_svg = df
2867            .boxplot_by_all_to_svg("group")
2868            .expect("boxplot_by_all_to_svg");
2869        assert!(b_all_svg.contains("<svg"));
2870        let b_all_html = df
2871            .boxplot_by_all_to_html("group")
2872            .expect("boxplot_by_all_to_html");
2873        assert!(b_all_html.contains("<div class=\"frankenpandas-plot\""));
2874        let b_all_file = temp_dir.join("box_by_all.svg");
2875        df.boxplot_by_all_to_file("group", &b_all_file)
2876            .expect("boxplot_by_all_to_file");
2877        assert!(
2878            std::fs::read_to_string(&b_all_file)
2879                .expect("read box_by_all")
2880                .contains("<svg")
2881        );
2882
2883        // 6. Error handling
2884        assert!(df.hist_columns_by(&["nonexistent"], "group", 5).is_err());
2885        assert!(df.hist_columns_by(&["val"], "nonexistent", 5).is_err());
2886        assert!(df.boxplot_columns_by(&["nonexistent"], "group").is_err());
2887        assert!(df.boxplot_columns_by(&["val"], "nonexistent").is_err());
2888        let df_str_only = DataFrame::from_series(vec![sg.clone()]).unwrap();
2889        assert!(df_str_only.hist_by_all("group", 5).is_err());
2890        assert!(df_str_only.boxplot_by_all("group").is_err());
2891
2892        // Cleanup
2893        let _ = std::fs::remove_file(&lag_file);
2894        let _ = std::fs::remove_file(&ac_file);
2895        let _ = std::fs::remove_file(&hc_by_file);
2896        let _ = std::fs::remove_file(&h_all_file);
2897        let _ = std::fs::remove_file(&bc_by_file);
2898        let _ = std::fs::remove_file(&b_all_file);
2899        let _ = std::fs::remove_dir(&temp_dir);
2900    }
2901
2902    #[test]
2903    fn bootstrap_plot_and_multivariate_plots() {
2904        let labels: Vec<IndexLabel> = (0..6).map(IndexLabel::Int64).collect();
2905        let sx = Series::from_values(
2906            "sepal_len",
2907            labels.clone(),
2908            floats(&[5.1, 4.9, 4.7, 7.0, 6.4, 6.9]),
2909        )
2910        .unwrap();
2911        let sy = Series::from_values(
2912            "sepal_wid",
2913            labels.clone(),
2914            floats(&[3.5, 3.0, 3.2, 3.2, 3.2, 3.1]),
2915        )
2916        .unwrap();
2917        let sz = Series::from_values(
2918            "petal_len",
2919            labels.clone(),
2920            floats(&[1.4, 1.4, 1.3, 4.7, 4.5, 4.9]),
2921        )
2922        .unwrap();
2923        let sc = Series::from_values(
2924            "species",
2925            labels.clone(),
2926            vec![
2927                Scalar::Utf8("setosa".into()),
2928                Scalar::Utf8("setosa".into()),
2929                Scalar::Utf8("setosa".into()),
2930                Scalar::Utf8("versicolor".into()),
2931                Scalar::Utf8("versicolor".into()),
2932                Scalar::Utf8("versicolor".into()),
2933            ],
2934        )
2935        .unwrap();
2936
2937        let df =
2938            DataFrame::from_series(vec![sx.clone(), sy.clone(), sz.clone(), sc.clone()]).unwrap();
2939        let temp_dir =
2940            std::env::temp_dir().join(format!("fp_test_multivariate_plots_{}", std::process::id()));
2941        let _ = std::fs::create_dir_all(&temp_dir);
2942
2943        // 1. Series bootstrap_plot
2944        let boot_spec = sx.bootstrap_plot(4, 50).expect("bootstrap_plot");
2945        assert_eq!(boot_spec.series.len(), 1);
2946        assert_eq!(boot_spec.series[0].values.len(), 50);
2947        let boot_svg = sx
2948            .bootstrap_plot_to_svg(4, 50)
2949            .expect("bootstrap_plot_to_svg");
2950        assert!(boot_svg.contains("<svg"));
2951        assert!(boot_svg.contains("<rect"));
2952        let boot_html = sx
2953            .bootstrap_plot_to_html(4, 50)
2954            .expect("bootstrap_plot_to_html");
2955        assert!(boot_html.contains("<div class=\"frankenpandas-plot\""));
2956        let boot_file = temp_dir.join("boot.svg");
2957        sx.bootstrap_plot_to_file(4, 50, &boot_file)
2958            .expect("bootstrap_plot_to_file");
2959        assert!(
2960            std::fs::read_to_string(&boot_file)
2961                .expect("read boot")
2962                .contains("<svg")
2963        );
2964
2965        // 2. DataFrame parallel_coordinates
2966        let pc_spec = df
2967            .parallel_coordinates("species", None)
2968            .expect("parallel_coordinates");
2969        assert_eq!(pc_spec.kind, PlotKind::Line);
2970        assert_eq!(pc_spec.series.len(), 6);
2971        let pc_svg = df
2972            .parallel_coordinates_to_svg("species", None)
2973            .expect("parallel_coordinates_to_svg");
2974        assert!(pc_svg.contains("<svg"));
2975        assert!(pc_svg.contains("stroke-dasharray=\"3,3\""));
2976        assert!(pc_svg.contains("stroke-opacity=\"0.6\""));
2977        assert!(pc_svg.contains("setosa"));
2978        assert!(pc_svg.contains("versicolor"));
2979        let pc_html = df
2980            .parallel_coordinates_to_html("species", None)
2981            .expect("parallel_coordinates_to_html");
2982        assert!(pc_html.contains("<div class=\"frankenpandas-plot\""));
2983        let pc_file = temp_dir.join("parallel.svg");
2984        df.parallel_coordinates_to_file("species", None, &pc_file)
2985            .expect("parallel_coordinates_to_file");
2986        assert!(
2987            std::fs::read_to_string(&pc_file)
2988                .expect("read parallel")
2989                .contains("<svg")
2990        );
2991
2992        // parallel_coordinates with explicit cols
2993        let pc_sub_svg = df
2994            .parallel_coordinates_to_svg("species", Some(&["sepal_len", "sepal_wid"]))
2995            .expect("pc_sub");
2996        assert!(pc_sub_svg.contains("<svg"));
2997
2998        // 3. DataFrame andrews_curves
2999        let ac_spec = df.andrews_curves("species", 30).expect("andrews_curves");
3000        assert_eq!(ac_spec.kind, PlotKind::Line);
3001        assert_eq!(ac_spec.series.len(), 6);
3002        assert_eq!(ac_spec.series[0].values.len(), 30);
3003        let ac_svg = df
3004            .andrews_curves_to_svg("species", 30)
3005            .expect("andrews_curves_to_svg");
3006        assert!(ac_svg.contains("<svg"));
3007        assert!(ac_svg.contains("stroke-opacity=\"0.6\""));
3008        assert!(ac_svg.contains("setosa"));
3009        assert!(ac_svg.contains("versicolor"));
3010        let ac_html = df
3011            .andrews_curves_to_html("species", 30)
3012            .expect("andrews_curves_to_html");
3013        assert!(ac_html.contains("<div class=\"frankenpandas-plot\""));
3014        let ac_file = temp_dir.join("andrews.svg");
3015        df.andrews_curves_to_file("species", 30, &ac_file)
3016            .expect("andrews_curves_to_file");
3017        assert!(
3018            std::fs::read_to_string(&ac_file)
3019                .expect("read andrews")
3020                .contains("<svg")
3021        );
3022
3023        // 4. DataFrame radviz
3024        let rv_spec = df.radviz("species", None).expect("radviz");
3025        assert_eq!(rv_spec.kind, PlotKind::Scatter);
3026        assert_eq!(rv_spec.series.len(), 4); // 2 classes * 2 (x, y)
3027        let rv_svg = df.radviz_to_svg("species", None).expect("radviz_to_svg");
3028        assert!(rv_svg.contains("<svg"));
3029        assert!(rv_svg.contains("<ellipse")); // circular boundary
3030        assert!(rv_svg.contains("<circle")); // scatter points
3031        assert!(rv_svg.contains("setosa"));
3032        assert!(rv_svg.contains("versicolor"));
3033        let rv_html = df.radviz_to_html("species", None).expect("radviz_to_html");
3034        assert!(rv_html.contains("<div class=\"frankenpandas-plot\""));
3035        let rv_file = temp_dir.join("radviz.svg");
3036        df.radviz_to_file("species", None, &rv_file)
3037            .expect("radviz_to_file");
3038        assert!(
3039            std::fs::read_to_string(&rv_file)
3040                .expect("read radviz")
3041                .contains("<svg")
3042        );
3043
3044        // 5. Error conditions
3045        assert!(sc.bootstrap_plot(5, 10).is_err());
3046        assert!(df.parallel_coordinates("nonexistent", None).is_err());
3047        assert!(
3048            df.parallel_coordinates("species", Some(&["nonexistent"]))
3049                .is_err()
3050        );
3051        assert!(df.andrews_curves("nonexistent", 50).is_err());
3052        assert!(df.radviz("nonexistent", None).is_err());
3053        assert!(df.radviz("species", Some(&["species"])).is_err()); // no numeric cols
3054        let df_str = DataFrame::from_series(vec![sc.clone()]).unwrap();
3055        assert!(df_str.parallel_coordinates("species", None).is_err());
3056        assert!(df_str.andrews_curves("species", 50).is_err());
3057        assert!(df_str.radviz("species", None).is_err());
3058
3059        // Cleanup
3060        let _ = std::fs::remove_file(&boot_file);
3061        let _ = std::fs::remove_file(&pc_file);
3062        let _ = std::fs::remove_file(&ac_file);
3063        let _ = std::fs::remove_file(&rv_file);
3064        let _ = std::fs::remove_dir(&temp_dir);
3065    }
3066
3067    #[test]
3068    fn scatter_matrix_full_pipeline_and_error_modes() {
3069        let labels: Vec<IndexLabel> = (0..5).map(IndexLabel::Int64).collect();
3070        let s_a =
3071            Series::from_values("a", labels.clone(), floats(&[1.0, 2.0, 3.0, 4.0, 5.0])).unwrap();
3072        let s_b = Series::from_values("b", labels.clone(), floats(&[10.0, 25.0, 15.0, 30.0, 20.0]))
3073            .unwrap();
3074        let s_c =
3075            Series::from_values("c", labels.clone(), floats(&[0.5, 1.5, 2.5, 3.5, 4.5])).unwrap();
3076        let s_cat = Series::from_values(
3077            "category",
3078            labels.clone(),
3079            vec![
3080                Scalar::Utf8("x".to_string()),
3081                Scalar::Utf8("y".to_string()),
3082                Scalar::Utf8("x".to_string()),
3083                Scalar::Utf8("y".to_string()),
3084                Scalar::Utf8("z".to_string()),
3085            ],
3086        )
3087        .unwrap();
3088        let df = DataFrame::from_series(vec![s_a, s_b.clone(), s_c, s_cat.clone()]).unwrap();
3089
3090        // 1. Default scatter matrix: automatically picks all numeric columns, diagonal='hist'
3091        let spec = df
3092            .scatter_matrix(None, None, None)
3093            .expect("default scatter_matrix");
3094        assert_eq!(spec.columns, vec!["a", "b", "c"]);
3095        assert_eq!(spec.diagonal, "hist");
3096        assert!((spec.alpha - 0.5).abs() < 1e-9);
3097        assert!((spec.range_padding - 0.05).abs() < 1e-9);
3098
3099        let svg1 = spec.to_svg().expect("to_svg");
3100        let svg2 = spec.to_svg().expect("to_svg repeat");
3101        assert_eq!(svg1, svg2, "rendering must be deterministic");
3102        assert!(svg1.starts_with("<svg") && svg1.ends_with("</svg>"));
3103        assert!(
3104            svg1.contains("<rect"),
3105            "diagonal histograms and cell boxes must have rects"
3106        );
3107        assert!(
3108            svg1.contains("<circle"),
3109            "off-diagonal scatter plots must have circles"
3110        );
3111        assert!(svg1.contains(">a</text>"), "column a must be labeled");
3112        assert!(svg1.contains(">b</text>"), "column b must be labeled");
3113        assert!(svg1.contains(">c</text>"), "column c must be labeled");
3114
3115        let bytes = spec.to_svg_bytes().expect("to_svg_bytes");
3116        assert!(bytes.starts_with(b"<svg"));
3117        let html = spec.to_html().expect("to_html");
3118        assert!(html.contains("<div class=\"frankenpandas-plot\""));
3119        let page = spec
3120            .to_html_page(Some("Custom Title"))
3121            .expect("to_html_page");
3122        assert!(page.contains("<title>Custom Title</title>"));
3123        let md = spec.to_markdown().expect("to_markdown");
3124        assert!(md.contains("<div class=\"frankenpandas-plot\">"));
3125
3126        // 2. Diagonal 'kde' and 'density'
3127        let spec_kde = df
3128            .scatter_matrix(Some(0.8), Some("kde"), Some(0.1))
3129            .expect("kde scatter_matrix");
3130        assert_eq!(spec_kde.diagonal, "kde");
3131        assert!((spec_kde.alpha - 0.8).abs() < 1e-9);
3132        assert!((spec_kde.range_padding - 0.1).abs() < 1e-9);
3133        let svg_kde = spec_kde.to_svg().expect("kde to_svg");
3134        assert!(
3135            svg_kde.contains("<polyline"),
3136            "kde diagonal must render polyline curve"
3137        );
3138        assert!(
3139            svg_kde.contains("<polygon"),
3140            "kde diagonal must render polygon area"
3141        );
3142
3143        let spec_density = df
3144            .scatter_matrix(Some(0.3), Some("density"), None)
3145            .expect("density scatter_matrix");
3146        assert_eq!(spec_density.diagonal, "density");
3147        let svg_density = spec_density.to_svg().expect("density to_svg");
3148        assert!(svg_density.contains("<polyline"));
3149
3150        // 3. Column subset selection
3151        let spec_cols = df
3152            .scatter_matrix_with_cols(Some(&["b", "c"]), Some(0.6), Some("hist"), None)
3153            .expect("scatter_matrix_with_cols");
3154        assert_eq!(spec_cols.columns, vec!["b", "c"]);
3155        assert_eq!(spec_cols.series.len(), 2);
3156
3157        // 4. Convenience DataFrame helpers
3158        let df_svg = df
3159            .scatter_matrix_to_svg(None, None, None)
3160            .expect("scatter_matrix_to_svg");
3161        assert!(df_svg.contains("<svg"));
3162        let df_html = df
3163            .scatter_matrix_to_html(None, None, None)
3164            .expect("scatter_matrix_to_html");
3165        assert!(df_html.contains("<div class=\"frankenpandas-plot\""));
3166
3167        let temp_dir = std::env::temp_dir().join(format!("fp_test_sm_{}", std::process::id()));
3168        let _ = std::fs::create_dir_all(&temp_dir);
3169        let sm_svg_file = temp_dir.join("sm.svg");
3170        df.scatter_matrix_to_file(&sm_svg_file, None, None, None)
3171            .expect("scatter_matrix_to_file");
3172        assert!(
3173            std::fs::read_to_string(&sm_svg_file)
3174                .expect("read sm.svg")
3175                .contains("<svg")
3176        );
3177
3178        let sm_html_file = temp_dir.join("sm.html");
3179        df.scatter_matrix_with_cols_to_file(Some(&["a", "b"]), &sm_html_file, None, None, None)
3180            .expect("scatter_matrix_with_cols_to_file");
3181        assert!(
3182            std::fs::read_to_string(&sm_html_file)
3183                .expect("read sm.html")
3184                .contains("<!DOCTYPE html>")
3185        );
3186
3187        let sm_cols_svg = df
3188            .scatter_matrix_with_cols_to_svg(Some(&["a", "c"]), None, None, None)
3189            .expect("scatter_matrix_with_cols_to_svg");
3190        assert!(sm_cols_svg.contains("<svg"));
3191        let sm_cols_html = df
3192            .scatter_matrix_with_cols_to_html(Some(&["a", "c"]), None, None, None)
3193            .expect("scatter_matrix_with_cols_to_html");
3194        assert!(sm_cols_html.contains("<div class=\"frankenpandas-plot\""));
3195
3196        // 5. Missing / NaN values handling
3197        let s_nan = Series::from_values(
3198            "a_nan",
3199            labels.clone(),
3200            floats(&[1.0, f64::NAN, 3.0, 4.0, f64::NAN]),
3201        )
3202        .unwrap();
3203        let df_nan = DataFrame::from_series(vec![s_nan, s_b]).unwrap();
3204        let svg_nan = df_nan
3205            .scatter_matrix_to_svg(None, None, None)
3206            .expect("svg with nan");
3207        assert!(svg_nan.contains("<svg"));
3208        assert!(
3209            !svg_nan.contains("NaN"),
3210            "SVG must not contain literal NaN coordinates"
3211        );
3212
3213        // 6. Error conditions
3214        // Empty dataframe
3215        let empty_df = DataFrame::from_series(vec![]).unwrap();
3216        assert!(empty_df.scatter_matrix(None, None, None).is_err());
3217
3218        // DataFrame with no numeric columns
3219        let str_df = DataFrame::from_series(vec![s_cat]).unwrap();
3220        assert!(str_df.scatter_matrix(None, None, None).is_err());
3221
3222        // Non-existent column requested
3223        assert!(
3224            df.scatter_matrix_with_cols(Some(&["nonexistent"]), None, None, None)
3225                .is_err()
3226        );
3227
3228        // Non-numeric column requested
3229        assert!(
3230            df.scatter_matrix_with_cols(Some(&["category"]), None, None, None)
3231                .is_err()
3232        );
3233
3234        // Invalid alpha (< 0, > 1, NaN)
3235        assert!(df.scatter_matrix(Some(-0.5), None, None).is_err());
3236        assert!(df.scatter_matrix(Some(1.5), None, None).is_err());
3237        assert!(df.scatter_matrix(Some(f64::NAN), None, None).is_err());
3238
3239        // Invalid range_padding (< 0, NaN)
3240        assert!(df.scatter_matrix(None, None, Some(-0.1)).is_err());
3241        assert!(df.scatter_matrix(None, None, Some(f64::NAN)).is_err());
3242
3243        // Invalid diagonal
3244        assert!(df.scatter_matrix(None, Some("invalid"), None).is_err());
3245
3246        // Column with all NaN values fails closed on render
3247        let s_all_nan = Series::from_values(
3248            "all_nan",
3249            labels,
3250            floats(&[f64::NAN, f64::NAN, f64::NAN, f64::NAN, f64::NAN]),
3251        )
3252        .unwrap();
3253        let df_all_nan = DataFrame::from_series(vec![s_all_nan]).unwrap();
3254        assert!(df_all_nan.scatter_matrix_to_svg(None, None, None).is_err());
3255
3256        // Cleanup
3257        let _ = std::fs::remove_file(&sm_svg_file);
3258        let _ = std::fs::remove_file(&sm_html_file);
3259        let _ = std::fs::remove_dir(&temp_dir);
3260    }
3261
3262    #[test]
3263    fn table_full_pipeline_and_error_modes() {
3264        use crate::{DataFrame, IndexLabel, Series, plotting};
3265
3266        let labels = vec![
3267            IndexLabel::Int64(0),
3268            IndexLabel::Int64(1),
3269            IndexLabel::Int64(2),
3270        ];
3271
3272        let s1 = Series::from_values("a", labels.clone(), floats(&[1.0, 2.5, 3.0])).unwrap();
3273        let s2 = Series::from_values(
3274            "b",
3275            labels.clone(),
3276            vec![Scalar::Int64(10), Scalar::Int64(20), Scalar::Int64(30)],
3277        )
3278        .unwrap();
3279        let s3 = Series::from_values(
3280            "c",
3281            labels.clone(),
3282            vec![
3283                Scalar::Utf8("x".to_string()),
3284                Scalar::Utf8("y".to_string()),
3285                Scalar::Null(fp_types::NullKind::Null),
3286            ],
3287        )
3288        .unwrap();
3289
3290        let df = DataFrame::from_series(vec![s1.clone(), s2.clone(), s3.clone()]).unwrap();
3291
3292        // 1. DataFrame::table() default
3293        let spec = df.table().expect("default df.table()");
3294        assert_eq!(spec.method, "pandas.plotting.table");
3295        assert_eq!(spec.row_labels, vec!["0", "1", "2"]);
3296        assert_eq!(spec.col_labels, vec!["a", "b", "c"]);
3297        assert_eq!(spec.cells.len(), 3);
3298        assert_eq!(spec.cells[0], vec!["1.0", "10", "x"]);
3299        assert_eq!(spec.cells[1], vec!["2.5", "20", "y"]);
3300        assert_eq!(spec.cells[2], vec!["3.0", "30", "NaN"]);
3301
3302        // SVG rendering
3303        let svg = df.table_to_svg(None, None).expect("df.table_to_svg()");
3304        assert!(svg.contains("<svg"));
3305        assert!(svg.contains("pandas.plotting.table"));
3306        assert!(svg.contains("1.0"));
3307        assert!(svg.contains("10"));
3308        assert!(svg.contains("NaN"));
3309
3310        // HTML rendering
3311        let html = df.table_to_html(None, None).expect("df.table_to_html()");
3312        assert!(html.contains("<div class=\"frankenpandas-plot\""));
3313        assert!(html.contains("<svg"));
3314
3315        // HTML page & markdown
3316        let page = spec
3317            .to_html_page(Some("Custom Title"))
3318            .expect("to_html_page");
3319        assert!(page.contains("<title>Custom Title</title>"));
3320        assert!(page.contains("<svg"));
3321        let md = spec.to_markdown().expect("to_markdown");
3322        assert!(md.contains("<div class=\"frankenpandas-plot\">"));
3323
3324        // Save to file
3325        let temp_dir = std::env::temp_dir().join(format!("fp_table_test_{}", std::process::id()));
3326        let _ = std::fs::create_dir_all(&temp_dir);
3327        let table_svg_file = temp_dir.join("table.svg");
3328        let table_html_file = temp_dir.join("table.html");
3329        df.table_to_file(&table_svg_file, None, None)
3330            .expect("table_to_file svg");
3331        assert!(table_svg_file.exists());
3332        df.table_to_file(&table_html_file, None, None)
3333            .expect("table_to_file html");
3334        assert!(table_html_file.exists());
3335
3336        // Custom labels
3337        let spec_custom = df
3338            .table_with_labels(
3339                Some(&["rowA", "rowB", "rowC"]),
3340                Some(&["col1", "col2", "col3"]),
3341            )
3342            .expect("table_with_labels");
3343        assert_eq!(spec_custom.row_labels, vec!["rowA", "rowB", "rowC"]);
3344        assert_eq!(spec_custom.col_labels, vec!["col1", "col2", "col3"]);
3345
3346        // 2. Series::table()
3347        let s_spec = s1.table().expect("s.table()");
3348        assert_eq!(s_spec.method, "pandas.plotting.table");
3349        assert_eq!(s_spec.row_labels, vec!["0", "1", "2"]);
3350        assert_eq!(s_spec.col_labels, vec!["a"]);
3351        assert_eq!(s_spec.cells.len(), 3);
3352        assert_eq!(s_spec.cells[0], vec!["1.0"]);
3353        assert_eq!(s_spec.cells[1], vec!["2.5"]);
3354        assert_eq!(s_spec.cells[2], vec!["3.0"]);
3355
3356        let s_svg = s1.table_to_svg(None, None).expect("s.table_to_svg");
3357        assert!(s_svg.contains("<svg"));
3358        let s_html = s1.table_to_html(None, None).expect("s.table_to_html");
3359        assert!(s_html.contains("<svg"));
3360
3361        let table_s_svg_file = temp_dir.join("table_s.svg");
3362        s1.table_to_file(&table_s_svg_file, None, None)
3363            .expect("s.table_to_file");
3364        assert!(table_s_svg_file.exists());
3365
3366        // 3. plotting::table free functions
3367        let plot_df_spec = plotting::table(&df).expect("plotting::table(&df)");
3368        assert_eq!(plot_df_spec.row_labels.len(), 3);
3369        let plot_df_custom = plotting::table_frame(&df, Some(&["r1", "r2", "r3"]), None)
3370            .expect("plotting::table_frame");
3371        assert_eq!(plot_df_custom.row_labels, vec!["r1", "r2", "r3"]);
3372        let plot_s_spec =
3373            plotting::table_series(&s1, None, Some(&["val"])).expect("plotting::table_series");
3374        assert_eq!(plot_s_spec.col_labels, vec!["val"]);
3375
3376        // 4. Error modes
3377        // Empty frame
3378        let empty_df = DataFrame::from_series(vec![]).unwrap();
3379        assert!(empty_df.table().is_err());
3380        assert!(empty_df.table_to_svg(None, None).is_err());
3381
3382        // Empty series
3383        let empty_s = Series::from_values("empty", vec![], vec![]).unwrap();
3384        assert!(empty_s.table().is_err());
3385        assert!(empty_s.table_to_svg(None, None).is_err());
3386
3387        // Label length mismatch
3388        assert!(df.table_with_labels(Some(&["too", "few"]), None).is_err());
3389        assert!(df.table_with_labels(None, Some(&["too", "few"])).is_err());
3390        assert!(s1.table_with_labels(Some(&["too", "few"]), None).is_err());
3391        assert!(s1.table_with_labels(None, Some(&["c1", "c2"])).is_err());
3392
3393        // Unsupported extension
3394        let invalid_ext = temp_dir.join("table.png");
3395        assert!(df.table_to_file(&invalid_ext, None, None).is_err());
3396
3397        // Cleanup
3398        let _ = std::fs::remove_file(&table_svg_file);
3399        let _ = std::fs::remove_file(&table_html_file);
3400        let _ = std::fs::remove_file(&table_s_svg_file);
3401        let _ = std::fs::remove_dir(&temp_dir);
3402    }
3403}