1use crate::{BoxPlotSpec, FrameError, HistogramSpec, PlotKind, PlotSeriesSpec, PlotSpec, Scalar};
21
22const WIDTH: f64 = 640.0;
25const HEIGHT: f64 = 400.0;
26const MARGIN_LEFT: f64 = 56.0;
27const MARGIN_RIGHT: f64 = 16.0;
28const MARGIN_TOP: f64 = 30.0;
29const MARGIN_BOTTOM: f64 = 42.0;
30const PLOT_W: f64 = WIDTH - MARGIN_LEFT - MARGIN_RIGHT;
31const PLOT_H: f64 = HEIGHT - MARGIN_TOP - MARGIN_BOTTOM;
32const PALETTE: [&str; 7] = [
33 "#4e79a7", "#f28e2b", "#e15759", "#76b7b2", "#59a14f", "#edc948", "#b07aa1",
34];
35const MAX_X_TICKS: usize = 8;
36
37fn palette(i: usize) -> &'static str {
38 PALETTE[i % PALETTE.len()]
39}
40
41fn esc(s: &str) -> String {
43 let mut out = String::with_capacity(s.len());
44 for c in s.chars() {
45 match c {
46 '&' => out.push_str("&"),
47 '<' => out.push_str("<"),
48 '>' => out.push_str(">"),
49 '"' => out.push_str("""),
50 '\'' => out.push_str("'"),
51 _ => out.push(c),
52 }
53 }
54 out
55}
56
57fn numeric_view(series: &PlotSeriesSpec) -> Result<Vec<Option<f64>>, FrameError> {
61 series
62 .values
63 .iter()
64 .map(|value| match value {
65 Scalar::Float64(v) => Ok(Some(*v)),
66 Scalar::Int64(v) => Ok(Some(*v as f64)),
67 Scalar::Bool(b) => Ok(Some(if *b { 1.0 } else { 0.0 })),
68 Scalar::Null(_) => Ok(None),
69 other => Err(FrameError::CompatibilityRejected(format!(
70 "plot requires numeric values: series '{}' carries {:?} ({other:?})",
71 series.name, series.dtype
72 ))),
73 })
74 .collect()
75}
76
77struct Scale {
80 min: f64,
81 max: f64,
82}
83
84fn data_scale(series: &[Vec<Option<f64>>]) -> Result<Scale, FrameError> {
85 let mut min = f64::INFINITY;
86 let mut max = f64::NEG_INFINITY;
87 for values in series {
88 for v in values.iter().flatten() {
89 if v.is_finite() {
90 min = min.min(*v);
91 max = max.max(*v);
92 }
93 }
94 }
95 if !min.is_finite() || !max.is_finite() {
96 return Err(FrameError::CompatibilityRejected(
97 "no plottable (non-missing) values in this plot".to_owned(),
98 ));
99 }
100 if (max - min).abs() < f64::EPSILON {
101 min -= 1.0;
102 max += 1.0;
103 }
104 Ok(Scale { min, max })
105}
106
107fn fmt_num(v: f64) -> String {
108 if v == v.trunc() && v.abs() < 1e15 {
109 format!("{}", v as i64)
110 } else {
111 format!("{v:.4}")
112 }
113}
114
115fn svg_open(title: &str) -> String {
116 format!(
117 "<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>",
118 esc(title)
119 )
120}
121
122fn svg_axes(scale: &Scale, x_labels: &[String]) -> String {
123 let mut out = String::new();
124 let right = MARGIN_LEFT + PLOT_W;
125 let bottom = MARGIN_TOP + PLOT_H;
126 for i in 0..=4 {
127 let frac = i as f64 / 4.0;
128 let value = scale.max - frac * (scale.max - scale.min);
129 let y = MARGIN_TOP + frac * PLOT_H;
130 out.push_str(&format!(
131 "<line x1=\"{MARGIN_LEFT}\" y1=\"{y:.2}\" x2=\"{right}\" y2=\"{y:.2}\" stroke=\"#e5e5e5\"/><text x=\"{}\" y=\"{:.2}\" text-anchor=\"end\" fill=\"#666\">{}</text>",
132 MARGIN_LEFT - 6.0,
133 y + 4.0,
134 esc(&fmt_num(value))
135 ));
136 }
137 out.push_str(&format!(
138 "<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\"/>"
139 ));
140 let n = x_labels.len();
141 if n > 0 {
142 let step = n.div_ceil(MAX_X_TICKS);
143 for (i, label) in x_labels.iter().enumerate() {
144 if i % step != 0 {
145 continue;
146 }
147 let x = MARGIN_LEFT + (i as f64 + 0.5) * PLOT_W / n as f64;
148 out.push_str(&format!(
149 "<text x=\"{x:.2}\" y=\"{:.2}\" text-anchor=\"middle\" fill=\"#666\">{}</text>",
150 bottom + 14.0,
151 esc(label)
152 ));
153 }
154 }
155 out
156}
157
158fn legend(entries: &[(String, &str)]) -> String {
159 let mut out = String::new();
160 let y = HEIGHT - 10.0;
161 for (i, (name, color)) in entries.iter().enumerate() {
162 let x = MARGIN_LEFT + 8.0 + (i as f64 * 150.0);
163 out.push_str(&format!(
164 "<rect x=\"{x}\" y=\"{:.2}\" width=\"10\" height=\"10\" fill=\"{color}\"/><text x=\"{}\" y=\"{y}\" fill=\"#333\">{}</text>",
165 y - 9.0,
166 x + 14.0,
167 esc(name)
168 ));
169 }
170 out
171}
172
173fn render_plot(spec: &PlotSpec) -> Result<String, FrameError> {
176 let views: Result<Vec<Vec<Option<f64>>>, FrameError> =
177 spec.series.iter().map(numeric_view).collect();
178 let views = views?;
179 let scale = data_scale(&views)?;
180 let n = spec
181 .series
182 .iter()
183 .map(|s| s.values.len())
184 .max()
185 .unwrap_or(0);
186 let x_labels: Vec<String> = spec
187 .series
188 .first()
189 .map(|first| {
190 first
191 .index
192 .iter()
193 .map(|label| crate::scalar_plot_label(&crate::index_label_to_scalar(label)))
194 .collect()
195 })
196 .unwrap_or_default();
197
198 let y = |v: f64| MARGIN_TOP + (scale.max - v) / (scale.max - scale.min) * PLOT_H;
199 let x = |i: usize| MARGIN_LEFT + (i as f64 + 0.5) * PLOT_W / n.max(1) as f64;
200
201 let mut body = String::new();
202 match spec.kind {
203 PlotKind::Line | PlotKind::Area => {
204 for (si, values) in views.iter().enumerate() {
207 let color = palette(si);
208 let mut runs: Vec<Vec<(f64, f64)>> = vec![Vec::new()];
209 for (i, v) in values.iter().enumerate() {
210 match v.filter(|v| v.is_finite()) {
211 Some(v) => runs.last_mut().expect("seeded run").push((x(i), y(v))),
212 None if !runs.last().expect("seeded run").is_empty() => {
213 runs.push(Vec::new());
214 }
215 None => {}
216 }
217 }
218 runs.retain(|run| !run.is_empty());
219 for run in &runs {
220 let points = run
221 .iter()
222 .map(|(px, py)| format!("{px:.2},{py:.2}"))
223 .collect::<Vec<_>>()
224 .join(" ");
225 if spec.kind == PlotKind::Area {
226 let first_x = run[0].0;
227 let last_x = run[run.len() - 1].0;
228 let base = y(scale.min);
229 body.push_str(&format!(
230 "<polygon points=\"{first_x:.2},{base:.2} {points} {last_x:.2},{base:.2}\" fill=\"{color}\" fill-opacity=\"0.25\" stroke=\"none\"/>"
231 ));
232 }
233 body.push_str(&format!(
234 "<polyline points=\"{points}\" fill=\"none\" stroke=\"{color}\" stroke-width=\"2\"/>"
235 ));
236 }
237 }
238 }
239 PlotKind::Scatter => {
240 for (si, values) in views.iter().enumerate() {
241 let color = palette(si);
242 for (i, v) in values.iter().enumerate() {
243 if let Some(v) = v.filter(|v| v.is_finite()) {
244 body.push_str(&format!(
245 "<circle cx=\"{:.2}\" cy=\"{:.2}\" r=\"2.5\" fill=\"{color}\"/>",
246 x(i),
247 y(v)
248 ));
249 }
250 }
251 }
252 }
253 PlotKind::Bar => {
254 let k = views.len().max(1);
255 let slot = PLOT_W / n.max(1) as f64;
256 let bar_w = slot * 0.7 / k as f64;
257 let base = y(scale.min);
258 for (si, values) in views.iter().enumerate() {
259 let color = palette(si);
260 let offset = si as f64 * bar_w + slot * 0.15;
261 for (i, v) in values.iter().enumerate() {
262 if let Some(v) = v.filter(|v| v.is_finite()) {
263 let top = y(v);
264 body.push_str(&format!(
265 "<rect x=\"{:.2}\" y=\"{top:.2}\" width=\"{bar_w:.2}\" height=\"{:.2}\" fill=\"{color}\"/>",
266 MARGIN_LEFT + i as f64 * slot + offset,
267 (base - top).abs().max(0.5)
268 ));
269 }
270 }
271 }
272 }
273 PlotKind::Pie => {
274 let mut angle: f64 = -std::f64::consts::FRAC_PI_2;
277 let cx = MARGIN_LEFT + PLOT_W / 2.0;
278 let cy = MARGIN_TOP + PLOT_H / 2.0;
279 let r = 140.0;
280 for (si, values) in views.iter().enumerate() {
281 let total: f64 = values.iter().flatten().copied().sum();
282 if values.iter().flatten().any(|v| *v < 0.0) {
283 return Err(FrameError::CompatibilityRejected(format!(
284 "pie requires non-negative values: series '{}' has a negative slice",
285 spec.series[si].name
286 )));
287 }
288 if total == 0.0 {
289 continue;
290 }
291 let color = palette(si);
292 for v in values.iter().flatten().copied() {
293 let next = angle + (v / total) * std::f64::consts::TAU;
294 let large = (next - angle) > std::f64::consts::PI;
295 body.push_str(&format!(
296 "<path d=\"M {cx:.2} {cy:.2} L {:.2} {:.2} A {r} {r} 0 {} 1 {:.2} {:.2} Z\" fill=\"{color}\" stroke=\"white\"/>",
297 cx + r * angle.cos(),
298 cy + r * angle.sin(),
299 i64::from(large),
300 cx + r * next.cos(),
301 cy + r * next.sin(),
302 ));
303 angle = next;
304 }
305 }
306 }
307 PlotKind::Histogram | PlotKind::Box => {
310 let finite: Vec<Vec<f64>> = views
311 .iter()
312 .map(|v| v.iter().flatten().copied().collect())
313 .collect();
314 let names: Vec<String> = spec.series.iter().map(|s| s.name.clone()).collect();
315 body = histogram_body(&finite, &names, 10, &format!("{} (as bars)", spec.method))?;
316 }
317 }
318
319 let legend_entries: Vec<(String, &str)> = spec
320 .series
321 .iter()
322 .enumerate()
323 .map(|(i, s)| (s.name.clone(), palette(i)))
324 .collect();
325 Ok(format!(
326 "{}{body}{}{}</svg>",
327 svg_open(&spec.method),
328 svg_axes(&scale, &x_labels),
329 legend(&legend_entries),
330 ))
331}
332
333fn histogram_body(
338 series: &[Vec<f64>],
339 _names: &[String],
340 bins: usize,
341 title: &str,
342) -> Result<String, FrameError> {
343 if bins == 0 {
344 return Err(FrameError::CompatibilityRejected(
345 "histogram requires at least one bin".to_owned(),
346 ));
347 }
348 let flat: Vec<Option<f64>> = series
349 .iter()
350 .flat_map(|v| v.iter().copied())
351 .map(Some)
352 .collect();
353 let scale = data_scale(&[flat])?;
354 let step = (scale.max - scale.min) / bins as f64;
355
356 let mut global_max = 0usize;
357 let mut all_counts: Vec<Vec<usize>> = Vec::with_capacity(series.len());
358 for values in series {
359 let mut counts = vec![0usize; bins];
360 for v in values {
361 let idx = if *v == scale.max {
363 bins - 1
364 } else {
365 (((v - scale.min) / step).floor() as usize).min(bins - 1)
366 };
367 counts[idx] += 1;
368 }
369 global_max = global_max.max(*counts.iter().max().unwrap_or(&0));
370 all_counts.push(counts);
371 }
372 let global_max = global_max.max(1);
373
374 let mut body = String::new();
375 let width = PLOT_W / series.len().max(1) as f64;
376 for (si, counts) in all_counts.iter().enumerate() {
377 let color = palette(si);
378 let x0 = MARGIN_LEFT + si as f64 * width;
379 let inner = width * 0.85;
380 let bar_w = inner / bins as f64 - 1.0;
381 for (bi, count) in counts.iter().enumerate() {
382 if *count == 0 {
383 continue;
384 }
385 let h = *count as f64 / global_max as f64 * PLOT_H;
386 let bx = x0 + bi as f64 * (inner / bins as f64);
387 body.push_str(&format!(
388 "<rect x=\"{bx:.2}\" y=\"{:.2}\" width=\"{bar_w:.2}\" height=\"{h:.2}\" fill=\"{color}\" stroke=\"white\"/>",
389 MARGIN_TOP + PLOT_H - h
390 ));
391 }
392 }
393 Ok(format!("{}{body}</svg>", svg_open(title)))
394}
395
396fn quantile(sorted: &[f64], q: f64) -> f64 {
397 let h = (sorted.len() - 1) as f64 * q;
398 let lo = h.floor() as usize;
399 let hi = h.ceil() as usize;
400 sorted[lo] + (sorted[hi] - sorted[lo]) * (h - lo as f64)
401}
402
403impl PlotSpec {
406 pub fn to_svg(&self) -> Result<String, FrameError> {
410 render_plot(self)
411 }
412
413 pub fn to_svg_bytes(&self) -> Result<Vec<u8>, FrameError> {
415 self.to_svg().map(String::into_bytes)
416 }
417}
418
419impl HistogramSpec {
420 pub fn to_svg(&self) -> Result<String, FrameError> {
423 let views: Result<Vec<Vec<Option<f64>>>, FrameError> =
424 self.series.iter().map(numeric_view).collect();
425 let views = views?;
426 let finite: Vec<Vec<f64>> = views
427 .iter()
428 .map(|v| v.iter().flatten().copied().collect())
429 .collect();
430 if finite.iter().all(|v| v.is_empty()) {
431 return Err(FrameError::CompatibilityRejected(
432 "no plottable (non-missing) values in this histogram".to_owned(),
433 ));
434 }
435 let names: Vec<String> = self.series.iter().map(|s| s.name.clone()).collect();
436 let title = format!(
437 "histogram ({})",
438 names.first().map(String::as_str).unwrap_or("values")
439 );
440 histogram_body(&finite, &names, self.bins, &title)
441 }
442
443 pub fn to_svg_bytes(&self) -> Result<Vec<u8>, FrameError> {
445 self.to_svg().map(String::into_bytes)
446 }
447}
448
449impl BoxPlotSpec {
450 pub fn to_svg(&self) -> Result<String, FrameError> {
454 let views: Result<Vec<Vec<Option<f64>>>, FrameError> =
455 self.series.iter().map(numeric_view).collect();
456 let views = views?;
457 let mut sorted: Vec<Vec<f64>> = views
458 .iter()
459 .map(|v| {
460 let mut vals: Vec<f64> = v.iter().flatten().copied().collect();
461 vals.sort_by(f64::total_cmp);
462 vals
463 })
464 .collect();
465 sorted.retain(|vals| !vals.is_empty());
466 if sorted.is_empty() {
467 return Err(FrameError::CompatibilityRejected(
468 "no plottable (non-missing) values in this boxplot".to_owned(),
469 ));
470 }
471 let scale = data_scale(&views)?;
472 let y = |v: f64| MARGIN_TOP + (scale.max - v) / (scale.max - scale.min) * PLOT_H;
473 let slot = PLOT_W / sorted.len() as f64;
474 let mut body = String::new();
475 for (si, vals) in sorted.iter().enumerate() {
476 let color = palette(si);
477 let (q1, med, q3) = (
478 quantile(vals, 0.25),
479 quantile(vals, 0.5),
480 quantile(vals, 0.75),
481 );
482 let (lo, hi) = (vals[0], vals[vals.len() - 1]);
483 let cx = MARGIN_LEFT + slot * (si as f64 + 0.5);
484 let bw = slot * 0.5;
485 let top = y(q3);
486 let bottom = y(q1);
487 body.push_str(&format!(
488 "<line x1=\"{cx:.2}\" y1=\"{:.2}\" x2=\"{cx:.2}\" y2=\"{:.2}\" stroke=\"{color}\"/><line x1=\"{:.2}\" y1=\"{:.2}\" x2=\"{:.2}\" y2=\"{:.2}\" stroke=\"{color}\"/>",
489 y(lo),
490 y(q1),
491 cx - bw / 2.0,
492 y(lo),
493 cx + bw / 2.0,
494 y(lo),
495 ));
496 body.push_str(&format!(
497 "<line x1=\"{cx:.2}\" y1=\"{:.2}\" x2=\"{cx:.2}\" y2=\"{:.2}\" stroke=\"{color}\"/><line x1=\"{:.2}\" y1=\"{:.2}\" x2=\"{:.2}\" y2=\"{:.2}\" stroke=\"{color}\"/>",
498 y(q3),
499 y(hi),
500 cx - bw / 2.0,
501 y(hi),
502 cx + bw / 2.0,
503 y(hi),
504 ));
505 body.push_str(&format!(
506 "<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\"/>",
507 cx - bw / 2.0,
508 (bottom - top).abs().max(0.5),
509 cx - bw / 2.0,
510 y(med),
511 cx + bw / 2.0,
512 y(med),
513 ));
514 }
515 let title = format!(
516 "boxplot ({})",
517 self.series
518 .first()
519 .map(|s| s.name.as_str())
520 .unwrap_or("values")
521 );
522 Ok(format!("{}{body}</svg>", svg_open(&title)))
523 }
524
525 pub fn to_svg_bytes(&self) -> Result<Vec<u8>, FrameError> {
527 self.to_svg().map(String::into_bytes)
528 }
529}
530
531#[cfg(test)]
532mod tests {
533 use super::{
534 BoxPlotSpec, FrameError, HistogramSpec, PlotKind, PlotSeriesSpec, PlotSpec, Scalar,
535 numeric_view, quantile,
536 };
537 use crate::DType;
538
539 fn series(name: &str, values: Vec<Scalar>) -> PlotSeriesSpec {
540 PlotSeriesSpec {
541 name: name.to_owned(),
542 dtype: DType::Float64,
543 index: (0..values.len() as i64)
544 .map(crate::IndexLabel::Int64)
545 .collect(),
546 values,
547 group_key: None,
548 }
549 }
550
551 fn floats(values: &[f64]) -> Vec<Scalar> {
552 values.iter().map(|v| Scalar::Float64(*v)).collect()
553 }
554
555 #[test]
556 fn line_plot_renders_deterministic_svg_with_axis_and_legend() {
557 let spec = PlotSpec {
558 method: "plot".to_owned(),
559 kind: PlotKind::Line,
560 series: vec![series("s", floats(&[1.0, 2.0, 3.0]))],
561 };
562 let a = spec.to_svg().expect("render");
563 let b = spec.to_svg().expect("render again");
564 assert_eq!(a, b, "rendering must be deterministic");
565 assert!(a.starts_with("<svg") && a.ends_with("</svg>"));
566 assert!(a.contains("<polyline"), "line kind must draw polylines");
567 assert!(a.contains(">s</text>"), "legend must carry the series name");
568 assert!(a.contains(">plot</text>"), "title must carry the method");
569 }
570
571 #[test]
572 fn nan_and_null_values_become_gaps_not_coordinates() {
573 let spec = PlotSpec {
574 method: "plot".to_owned(),
575 kind: PlotKind::Line,
576 series: vec![series(
577 "gappy",
578 vec![
579 Scalar::Float64(1.0),
580 Scalar::Float64(f64::NAN),
581 Scalar::Float64(3.0),
582 Scalar::Null(crate::NullKind::NaN),
583 Scalar::Float64(5.0),
584 ],
585 )],
586 };
587 let svg = spec.to_svg().expect("render");
588 assert!(svg.contains("<polyline"), "gaps still draw segments");
589 assert_eq!(svg.matches("<polyline").count(), 3);
591 assert!(
592 !svg.contains("NaN"),
593 "missing values must not leak as text coords"
594 );
595 }
596
597 #[test]
598 fn all_missing_and_non_numeric_series_fail_closed() {
599 let all_nan = PlotSpec {
600 method: "plot".to_owned(),
601 kind: PlotKind::Line,
602 series: vec![series("nan", vec![Scalar::Float64(f64::NAN); 3])],
603 };
604 assert!(matches!(
605 all_nan.to_svg(),
606 Err(FrameError::CompatibilityRejected(_))
607 ));
608
609 let utf8 = PlotSeriesSpec {
610 name: "text".to_owned(),
611 dtype: DType::Utf8,
612 index: vec![crate::IndexLabel::Int64(0)],
613 values: vec![Scalar::Utf8("nope".to_owned())],
614 group_key: None,
615 };
616 let err = numeric_view(&utf8).expect_err("utf8 must fail closed");
617 assert!(matches!(err, FrameError::CompatibilityRejected(_)));
618 }
619
620 #[test]
621 fn histogram_bins_cover_every_finite_value_exactly_once() {
622 let spec = HistogramSpec {
623 method: "hist".to_owned(),
624 bins: 4,
625 series: vec![series("h", floats(&[0.0, 1.0, 2.0, 3.0, f64::NAN]))],
626 };
627 let svg = spec.to_svg().expect("render");
628 assert_eq!(
631 svg.matches("stroke=\"white\"").count(),
632 4,
633 "one bar per populated bin"
634 );
635 }
636
637 #[test]
638 fn boxplot_quantiles_match_linear_interpolation() {
639 let vals: Vec<f64> = (1..=5).map(f64::from).collect();
640 assert_eq!(quantile(&vals, 0.5), 3.0);
641 assert!((quantile(&vals, 0.25) - 2.0).abs() < 1e-9);
642 assert!((quantile(&vals, 0.75) - 4.0).abs() < 1e-9);
643 let even: Vec<f64> = vec![1.0, 2.0, 3.0, 4.0];
644 assert!((quantile(&even, 0.5) - 2.5).abs() < 1e-9);
645
646 let spec = BoxPlotSpec {
647 method: "boxplot".to_owned(),
648 series: vec![series("b", floats(&[1.0, 2.0, 3.0, 4.0, 5.0]))],
649 };
650 let svg = spec.to_svg().expect("render");
651 assert!(svg.contains("<rect"), "box body must be drawn");
652 }
653
654 #[test]
655 fn xml_sensitive_names_are_escaped() {
656 let spec = PlotSpec {
657 method: "plot".to_owned(),
658 kind: PlotKind::Line,
659 series: vec![series("<b>&\"x'", floats(&[1.0, 2.0]))],
660 };
661 let svg = spec.to_svg().expect("render");
662 assert!(
663 !svg.contains("<b>&"),
664 "raw XML-sensitive text must not leak"
665 );
666 assert!(svg.contains("<b>&"), "name must be escaped");
667 }
668
669 #[test]
670 fn svg_bytes_and_bar_and_pie_paths_render() {
671 let bar = PlotSpec {
672 method: "bar".to_owned(),
673 kind: PlotKind::Bar,
674 series: vec![series("b", floats(&[1.0, 5.0]))],
675 };
676 assert!(bar.to_svg().expect("bar").contains("<rect"));
677 let bytes = bar.to_svg_bytes().expect("bytes");
678 assert!(bytes.starts_with(b"<svg"));
679
680 let pie = PlotSpec {
681 method: "pie".to_owned(),
682 kind: PlotKind::Pie,
683 series: vec![series("p", floats(&[1.0, 1.0, 2.0]))],
684 };
685 assert!(pie.to_svg().expect("pie").contains("<path"));
686
687 let negative_pie = PlotSpec {
688 method: "pie".to_owned(),
689 kind: PlotKind::Pie,
690 series: vec![series("p", floats(&[-1.0, 2.0]))],
691 };
692 assert!(matches!(
693 negative_pie.to_svg(),
694 Err(FrameError::CompatibilityRejected(_))
695 ));
696 }
697}