1use std::ops::{BitOr, Div};
27
28use crate::aes::Aesthetic;
29use crate::guide::legend;
30use crate::plot::{GGError, GGPlot, RenderMeta};
31use crate::render::backend::{
32 DrawBackend, LineStyle, PointStyle, RectStyle, TextAnchor, TextStyle,
33};
34use crate::render::renderer::PlotRenderer;
35use crate::render::svg_backend::{root_data_attrs, SvgBackend};
36use crate::render::{Rect, RenderError};
37use crate::theme::elements::{ElementLine, ElementText};
38use crate::theme::{AxisLabelFit, LegendPosition, Theme};
39
40#[derive(Clone, Debug, PartialEq)]
42pub enum TagLevels {
43 Lower,
45 Upper,
47 Numeric,
49 LowerRoman,
51 UpperRoman,
53 Custom(Vec<String>),
55}
56
57impl TagLevels {
58 pub fn tag(&self, i: usize) -> String {
60 match self {
61 TagLevels::Lower => alpha(i, b'a'),
62 TagLevels::Upper => alpha(i, b'A'),
63 TagLevels::Numeric => (i + 1).to_string(),
64 TagLevels::LowerRoman => roman(i + 1).to_lowercase(),
65 TagLevels::UpperRoman => roman(i + 1),
66 TagLevels::Custom(v) => v.get(i).cloned().unwrap_or_else(|| (i + 1).to_string()),
67 }
68 }
69}
70
71fn alpha(mut i: usize, base: u8) -> String {
72 let mut out = Vec::new();
74 loop {
75 out.push(base + (i % 26) as u8);
76 if i < 26 {
77 break;
78 }
79 i = i / 26 - 1;
80 }
81 out.reverse();
82 String::from_utf8(out).unwrap_or_default()
83}
84
85fn roman(mut n: usize) -> String {
86 if n >= 4000 {
87 return n.to_string();
88 }
89 const T: [(usize, &str); 13] = [
90 (1000, "M"),
91 (900, "CM"),
92 (500, "D"),
93 (400, "CD"),
94 (100, "C"),
95 (90, "XC"),
96 (50, "L"),
97 (40, "XL"),
98 (10, "X"),
99 (9, "IX"),
100 (5, "V"),
101 (4, "IV"),
102 (1, "I"),
103 ];
104 let mut s = String::new();
105 for (v, r) in T {
106 while n >= v {
107 s.push_str(r);
108 n -= v;
109 }
110 }
111 s
112}
113
114#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
122pub enum AxisCollect {
123 #[default]
125 Keep,
126 Align,
141 CollectX,
148}
149
150#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
152pub enum GridLegendPosition {
153 #[default]
155 Right,
156 Bottom,
158}
159
160#[derive(Clone, Copy, Debug, PartialEq, Eq)]
163enum Op {
164 Row,
165 Col,
166}
167
168pub enum GridCell {
170 Plot(Box<GGPlot>),
171 Grid(Box<PlotGrid>),
172 Spacer,
174}
175
176impl From<GGPlot> for GridCell {
177 fn from(p: GGPlot) -> Self {
178 GridCell::Plot(Box::new(p))
179 }
180}
181
182impl From<PlotGrid> for GridCell {
183 fn from(g: PlotGrid) -> Self {
184 GridCell::Grid(Box::new(g))
185 }
186}
187
188pub struct PlotGrid {
207 cells: Vec<GridCell>,
208 ncol: Option<usize>,
209 nrow: Option<usize>,
210 byrow: bool,
211 widths: Vec<f64>,
212 heights: Vec<f64>,
213 title: Option<String>,
214 subtitle: Option<String>,
215 caption: Option<String>,
216 tags: Option<TagLevels>,
217 tag_prefix: String,
218 tag_suffix: String,
219 collect_legends: bool,
220 legend_position: GridLegendPosition,
221 spacing: f64,
222 theme: Theme,
223 axis_collect: AxisCollect,
224 op: Option<Op>,
225 root_attrs: Vec<(String, String)>,
228 svg_warnings_attr: bool,
233}
234
235impl Default for PlotGrid {
236 fn default() -> Self {
237 PlotGrid {
238 cells: Vec::new(),
239 ncol: None,
240 nrow: None,
241 byrow: true,
242 widths: Vec::new(),
243 heights: Vec::new(),
244 title: None,
245 subtitle: None,
246 caption: None,
247 tags: None,
248 tag_prefix: String::new(),
249 tag_suffix: String::new(),
250 collect_legends: false,
251 legend_position: GridLegendPosition::Right,
252 spacing: 0.0,
253 theme: Theme::default(),
254 axis_collect: AxisCollect::Keep,
255 op: None,
256 root_attrs: Vec::new(),
257 svg_warnings_attr: false,
258 }
259 }
260}
261
262const MAX_TRACKS: usize = 10_000;
264
265impl PlotGrid {
266 pub fn new() -> Self {
267 Self::default()
268 }
269
270 #[allow(clippy::should_implement_trait)]
272 pub fn add(mut self, cell: impl Into<GridCell>) -> Self {
273 self.cells.push(cell.into());
274 self
275 }
276
277 pub fn add_all(mut self, plots: impl IntoIterator<Item = GGPlot>) -> Self {
279 self.cells.extend(plots.into_iter().map(GridCell::from));
280 self
281 }
282
283 pub fn add_spacer(mut self) -> Self {
285 self.cells.push(GridCell::Spacer);
286 self
287 }
288
289 pub fn ncol(mut self, n: usize) -> Self {
291 self.ncol = (n > 0).then_some(n.min(MAX_TRACKS));
292 self
293 }
294
295 pub fn nrow(mut self, n: usize) -> Self {
297 self.nrow = (n > 0).then_some(n.min(MAX_TRACKS));
298 self
299 }
300
301 pub fn byrow(mut self, byrow: bool) -> Self {
303 self.byrow = byrow;
304 self
305 }
306
307 pub fn widths(mut self, widths: &[f64]) -> Self {
309 self.widths = widths.to_vec();
310 self
311 }
312
313 pub fn heights(mut self, heights: &[f64]) -> Self {
315 self.heights = heights.to_vec();
316 self
317 }
318
319 pub fn title(mut self, title: &str) -> Self {
321 self.title = Some(title.to_string());
322 self
323 }
324
325 pub fn subtitle(mut self, subtitle: &str) -> Self {
327 self.subtitle = Some(subtitle.to_string());
328 self
329 }
330
331 pub fn caption(mut self, caption: &str) -> Self {
333 self.caption = Some(caption.to_string());
334 self
335 }
336
337 pub fn tag_levels(mut self, levels: TagLevels) -> Self {
339 self.tags = Some(levels);
340 self
341 }
342
343 pub fn tag_affixes(mut self, prefix: &str, suffix: &str) -> Self {
345 self.tag_prefix = prefix.to_string();
346 self.tag_suffix = suffix.to_string();
347 self
348 }
349
350 pub fn collect_legends(mut self, collect: bool) -> Self {
353 self.collect_legends = collect;
354 self
355 }
356
357 pub fn legend_position(mut self, pos: GridLegendPosition) -> Self {
359 self.legend_position = pos;
360 self
361 }
362
363 pub fn axis_collect(mut self, mode: AxisCollect) -> Self {
367 self.axis_collect = mode;
368 self
369 }
370
371 pub fn spacing(mut self, px: f64) -> Self {
373 self.spacing = if px.is_finite() { px.max(0.0) } else { 0.0 };
374 self
375 }
376
377 pub fn theme(mut self, theme: Theme) -> Self {
380 self.theme = theme;
381 self
382 }
383
384 pub fn svg_attr(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
391 self.root_attrs.push((name.into(), value.into()));
392 self
393 }
394
395 pub fn svg_attrs(mut self, attrs: impl IntoIterator<Item = (String, String)>) -> Self {
397 self.root_attrs.extend(attrs);
398 self
399 }
400
401 pub fn svg_warnings_attr(mut self, on: bool) -> Self {
405 self.svg_warnings_attr = on;
406 self
407 }
408
409 pub fn len(&self) -> usize {
411 self.cells.len()
412 }
413
414 pub fn is_empty(&self) -> bool {
416 self.cells.is_empty()
417 }
418
419 pub fn render_svg_native(self) -> Result<String, GGError> {
421 self.render_svg_native_with_size(800, 600)
422 }
423
424 pub fn render_svg_native_with_size(self, w: u32, h: u32) -> Result<String, GGError> {
428 Ok(self.render_page(w, h)?.0.finish())
429 }
430
431 pub fn render_svg_native_with_warnings(
434 self,
435 w: u32,
436 h: u32,
437 ) -> Result<(String, Vec<String>), GGError> {
438 let (page, warnings) = self.render_page(w, h)?;
439 Ok((page.finish(), warnings))
440 }
441
442 pub fn render_svg_native_at(self, x: f64, y: f64, w: u32, h: u32) -> Result<String, GGError> {
445 Ok(self.render_page(w, h)?.0.finish_fragment(x, y))
446 }
447
448 fn render_page(self, w: u32, h: u32) -> Result<(SvgBackend, Vec<String>), GGError> {
449 let (w, h) = (w.max(1), h.max(1));
450 let mut theme = self.theme.clone();
451 theme.resolve_inheritance();
452 let collect = self.collect_legends;
453 let legend_pos = self.legend_position;
454 let root_attrs = self.root_attrs.clone();
455 let svg_warnings_attr = self.svg_warnings_attr;
456
457 let mut ctx = PrepCtx {
460 tags: self
461 .tags
462 .clone()
463 .map(|t| (t, self.tag_prefix.clone(), self.tag_suffix.clone())),
464 next_tag: 0,
465 next_index: 0,
466 collect: collect.then_some(legend_pos),
467 legends: Vec::new(),
468 page_w: w as f64,
469 page_h: h as f64,
470 legend_warnings: Vec::new(),
471 };
472 let prepared = prepare_grid(self, &mut ctx)?;
473 let legends = ctx.legends;
474 let legend_warnings = ctx.legend_warnings;
475
476 let full = Rect {
478 x: 0.0,
479 y: 0.0,
480 width: w as f64,
481 height: h as f64,
482 };
483 let mut page = SvgBackend::new(w, h, full.clone());
484 page.without_plot_attr();
485 let (rows, cols) = prepared.dims();
486 let data_grid_attr = ("data-grid".to_string(), format!("{rows} {cols}"));
487 page.set_root_attrs(vec![data_grid_attr.clone()]);
488 if let Some(fill) = theme
489 .plot_background
490 .fill
491 .filter(|_| theme.plot_background.visible)
492 {
493 page.draw_rect(
494 (0.0, 0.0),
495 (w as f64, h as f64),
496 &RectStyle {
497 fill: Some(fill),
498 stroke: None,
499 stroke_width: 0.0,
500 alpha: 1.0,
501 clip: false,
502 corner_radius: 0.0,
503 },
504 )
505 .map_err(GGError::Render)?;
506 }
507
508 let mut body = full;
509 if !legends.is_empty() {
510 let gap = theme.legend_spacing.max(0.0) * 2.0;
511 let pad = 8.0;
512 match legend_pos {
513 GridLegendPosition::Right => {
514 let strip_w = legends.iter().map(|l| l.w).fold(0.0, f64::max) + 2.0 * pad;
515 let strip_w = strip_w.min(body.width * 0.4);
516 body.width -= strip_w;
517 let total_h =
518 legends.iter().map(|l| l.h).sum::<f64>() + gap * (legends.len() - 1) as f64;
519 let mut y = (body.y + (body.height - total_h) / 2.0).max(body.y + pad);
520 for l in &legends {
521 place_legend(&mut page, l, body.x + body.width + pad, y);
522 y += l.h + gap;
523 }
524 }
525 GridLegendPosition::Bottom => {
526 let strip_h = legends.iter().map(|l| l.h).fold(0.0, f64::max) + 2.0 * pad;
527 let strip_h = strip_h.min(body.height * 0.4);
528 body.height -= strip_h;
529 let total_w =
530 legends.iter().map(|l| l.w).sum::<f64>() + gap * (legends.len() - 1) as f64;
531 let mut x = (body.x + (body.width - total_w) / 2.0).max(body.x + pad);
532 for l in &legends {
533 place_legend(&mut page, l, x, body.y + body.height + pad);
534 x += l.w + gap;
535 }
536 }
537 }
538 }
539
540 let mut warnings = legend_warnings;
542 render_prepared(prepared, &body, &mut page, &mut warnings)?;
543
544 let mut reserved = vec![data_grid_attr];
545 if svg_warnings_attr {
546 reserved.push(("data-warnings".to_string(), String::new()));
547 }
548 let extra = crate::render::svg_backend::validate_root_attrs(
549 &root_attrs,
550 &reserved,
551 "grid",
552 &mut warnings,
553 );
554 page.extend_root_attrs(extra);
555 if svg_warnings_attr {
556 page.extend_root_attrs(vec![(
557 "data-warnings".to_string(),
558 crate::render::svg_backend::warnings_json(&warnings),
559 )]);
560 }
561 Ok((page, warnings))
562 }
563}
564
565struct Legend {
567 body: String,
568 x0: f64,
569 y0: f64,
570 w: f64,
571 h: f64,
572}
573
574fn place_legend(page: &mut SvgBackend, l: &Legend, x: f64, y: f64) {
575 let (tx, ty) = (x - l.x0, y - l.y0);
576 if tx.is_finite() && ty.is_finite() {
577 page.push_raw(&format!(
578 "<g class=\"legend\" transform=\"translate({tx:.2} {ty:.2})\">{}</g>",
579 l.body
580 ));
581 }
582}
583
584struct PrepCtx {
585 tags: Option<(TagLevels, String, String)>,
586 next_tag: usize,
587 next_index: usize,
588 collect: Option<GridLegendPosition>,
589 legends: Vec<Legend>,
590 page_w: f64,
596 page_h: f64,
597 legend_warnings: Vec<String>,
603}
604
605struct PreparedPlot {
607 built: crate::build::BuiltPlot,
608 meta: RenderMeta,
609 panel: String,
610 svg_formatted_values: bool,
618}
619
620enum Prepared {
621 Plot(Box<PreparedPlot>),
622 Grid(Box<PreparedGrid>),
623 Spacer,
624}
625
626struct PreparedGrid {
627 cells: Vec<Prepared>,
628 ncol: usize,
629 nrow: usize,
630 byrow: bool,
631 widths: Vec<f64>,
632 heights: Vec<f64>,
633 title: Option<String>,
634 subtitle: Option<String>,
635 caption: Option<String>,
636 spacing: f64,
637 theme: Theme,
638 axis_collect: AxisCollect,
639}
640
641impl Prepared {
642 fn dims(&self) -> (usize, usize) {
643 match self {
644 Prepared::Grid(g) => (g.nrow, g.ncol),
645 _ => (1, 1),
646 }
647 }
648}
649
650fn prepare_grid(grid: PlotGrid, ctx: &mut PrepCtx) -> Result<Prepared, GGError> {
651 let n = grid.cells.len();
652 let (ncol, nrow) = match (grid.ncol, grid.nrow, grid.op) {
653 (Some(c), Some(r), _) => {
654 (c, r.max(n.div_ceil(c)))
656 }
657 (Some(c), None, _) => (c, n.div_ceil(c).max(1)),
658 (None, Some(r), _) => (n.div_ceil(r).max(1), r),
659 (None, None, Some(Op::Row)) => (n.max(1), 1),
660 (None, None, Some(Op::Col)) => (1, n.max(1)),
661 (None, None, None) => {
662 let c = ((n as f64).sqrt().ceil() as usize).max(1);
663 (c, n.div_ceil(c).max(1))
664 }
665 };
666 let mut theme = grid.theme;
667 theme.resolve_inheritance();
668 let mut cells = Vec::with_capacity(n);
669 for cell in grid.cells {
670 cells.push(match cell {
671 GridCell::Spacer => Prepared::Spacer,
672 GridCell::Grid(g) => prepare_grid(*g, ctx)?,
673 GridCell::Plot(p) => Prepared::Plot(Box::new(prepare_plot(*p, ctx)?)),
674 });
675 }
676 Ok(Prepared::Grid(Box::new(PreparedGrid {
677 cells,
678 ncol,
679 nrow,
680 byrow: grid.byrow,
681 widths: grid.widths,
682 heights: grid.heights,
683 title: grid.title,
684 subtitle: grid.subtitle,
685 caption: grid.caption,
686 spacing: grid.spacing,
687 theme,
688 axis_collect: grid.axis_collect,
689 })))
690}
691
692fn prepare_plot(mut plot: GGPlot, ctx: &mut PrepCtx) -> Result<PreparedPlot, GGError> {
693 ctx.next_index += 1;
694 if let Some((levels, pre, suf)) = &ctx.tags {
695 plot.labels.tag = Some(format!("{pre}{}{suf}", levels.tag(ctx.next_tag)));
696 ctx.next_tag += 1;
697 }
698 let panel = plot
699 .labels
700 .tag
701 .clone()
702 .unwrap_or_else(|| ctx.next_index.to_string());
703
704 let original = plot.theme.legend_position.clone();
706 let collect = ctx.collect.filter(|_| {
707 matches!(
708 original,
709 LegendPosition::Right
710 | LegendPosition::Left
711 | LegendPosition::Top
712 | LegendPosition::Bottom
713 )
714 });
715 if collect.is_some() {
716 plot.theme.legend_position = LegendPosition::None;
717 }
718 let svg_formatted_values = plot.svg_formatted_values;
719 let (built, mut meta) = plot.build_for_render()?;
720 if let Some(pos) = collect {
721 meta.has_legend = false;
722 if let Some(l) = capture_legend(
723 &built,
724 pos,
725 ctx.page_w,
726 ctx.page_h,
727 &mut ctx.legend_warnings,
728 )
729 .map_err(GGError::Render)?
730 {
731 if !ctx.legends.iter().any(|o| o.body == l.body) {
732 ctx.legends.push(l);
733 }
734 }
735 }
736 Ok(PreparedPlot {
737 built,
738 meta,
739 panel,
740 svg_formatted_values,
741 })
742}
743
744fn capture_legend(
752 built: &crate::build::BuiltPlot,
753 pos: GridLegendPosition,
754 page_w: f64,
755 page_h: f64,
756 warnings: &mut Vec<String>,
764) -> Result<Option<Legend>, RenderError> {
765 let mut theme = built.theme.clone();
766 let m = theme.legend_margin.clone();
767 let (pa, lp, is_horizontal) = match pos {
769 GridLegendPosition::Right => (
770 Rect {
771 x: -m.left,
772 y: -m.top,
773 width: 0.0,
774 height: 0.0,
775 },
776 LegendPosition::Right,
777 false,
778 ),
779 GridLegendPosition::Bottom => (
780 Rect {
781 x: -m.left,
782 y: -(m.top + 30.0),
783 width: 0.0,
784 height: 0.0,
785 },
786 LegendPosition::Bottom,
787 true,
788 ),
789 };
790 theme.legend_position = lp;
791 let mut svg = SvgBackend::new(1, 1, pa.clone());
792 let mut meas = Measure::new(&mut svg, pa.clone());
793 let avail_width = (page_w + m.left).max(0.0);
794 let avail_height = (page_h + m.top).max(0.0);
795 let legend_plans = legend::plan_all_legends(
796 &built.scales,
797 &built.guide_legend,
798 &theme,
799 &built.suppressed_aes,
800 avail_width,
801 avail_height,
802 is_horizontal,
803 warnings,
804 );
805 legend::draw_legend_planned(
806 &built.scales,
807 &theme,
808 &pa,
809 avail_width,
816 &mut meas,
817 &built.guide_legend,
818 &built.suppressed_aes,
819 &legend_plans,
820 )?;
821 let ext = meas.extent();
822 if svg.body().is_empty() {
823 return Ok(None);
824 }
825 let (x0, y0, x1, y1) = match ext {
826 Some(e) => e,
827 None => return Ok(None),
828 };
829 Ok(Some(Legend {
830 body: svg.body().to_string(),
831 x0,
832 y0,
833 w: (x1 - x0).max(0.0),
834 h: (y1 - y0).max(0.0),
835 }))
836}
837
838fn tracks(weights: &[f64], n: usize, total: f64, gap: f64) -> Vec<(f64, f64)> {
840 let ws: Vec<f64> = (0..n)
841 .map(|i| {
842 if weights.is_empty() {
843 1.0
844 } else {
845 let w = weights[i % weights.len()];
846 if w.is_finite() && w > 0.0 {
847 w
848 } else {
849 1.0
850 }
851 }
852 })
853 .collect();
854 let sum: f64 = ws.iter().sum();
855 let avail = (total - gap * n.saturating_sub(1) as f64).max(0.0);
856 let mut pos = 0.0;
857 ws.iter()
858 .map(|w| {
859 let size = avail * w / sum;
860 let t = (pos, size);
861 pos += size + gap;
862 t
863 })
864 .collect()
865}
866
867fn text_style(el: &crate::theme::elements::ElementText, anchor: TextAnchor) -> TextStyle {
868 TextStyle {
869 color: el.color,
870 size: el.size,
871 anchor,
872 angle: 0.0,
873 family: (!el.family.is_empty()).then(|| el.family.clone()),
874 face: el.face,
875 }
876}
877
878fn hjust_x(el: &crate::theme::elements::ElementText, x0: f64, x1: f64) -> (f64, TextAnchor) {
879 let hj = if el.hjust.is_finite() {
880 el.hjust.clamp(0.0, 1.0)
881 } else {
882 0.0
883 };
884 let anchor = if hj <= 0.02 {
885 TextAnchor::Start
886 } else if hj >= 0.98 {
887 TextAnchor::End
888 } else {
889 TextAnchor::Middle
890 };
891 (x0 + hj * (x1 - x0), anchor)
892}
893
894fn render_prepared(
895 prepared: Prepared,
896 area: &Rect,
897 page: &mut SvgBackend,
898 warnings: &mut Vec<String>,
899) -> Result<(), GGError> {
900 match prepared {
901 Prepared::Spacer => Ok(()),
902 Prepared::Plot(p) => {
903 let PreparedPlot {
904 mut built,
905 meta,
906 panel,
907 svg_formatted_values,
908 } = *p;
909 let (cw, ch) = (
910 area.width.floor().max(1.0) as u32,
911 area.height.floor().max(1.0) as u32,
912 );
913 let layout = GGPlot::layout_built(&mut built, &meta, cw, ch);
914 let mut backend = SvgBackend::new(cw, ch, layout.plot_area.clone());
915 backend.set_formatted_values(svg_formatted_values);
916 let mut attrs = root_data_attrs(&built);
917 attrs.push(("data-panel".into(), panel.clone()));
918 backend.set_root_attrs(attrs);
919 PlotRenderer::render(&built, &mut backend).map_err(GGError::Render)?;
920 warnings.extend(
921 built
922 .warnings
923 .iter()
924 .cloned()
925 .chain(backend.take_warnings())
926 .map(|w| format!("panel {panel}: {w}")),
927 );
928 page.push_raw(&backend.finish_fragment(area.x, area.y));
929 Ok(())
930 }
931 Prepared::Grid(g) => {
932 let mut g = *g;
933 let theme = &g.theme;
934 let m = &theme.plot_margin;
935 let mut top = area.y;
937 let (x0, x1) = (area.x + m.left, area.x + area.width - m.right);
938 if let Some(t) = &g.title {
939 top += m.top;
940 let (tx, anchor) = hjust_x(&theme.title, x0, x1);
941 page.draw_text(
942 t,
943 (tx, top + theme.title.size * 0.8),
944 &text_style(&theme.title, anchor),
945 )
946 .map_err(GGError::Render)?;
947 top += theme.title.size * 1.6;
948 }
949 if let Some(s) = &g.subtitle {
950 if g.title.is_none() {
951 top += m.top;
952 }
953 let (sx, anchor) = hjust_x(&theme.subtitle, x0, x1);
954 page.draw_text(
955 s,
956 (sx, top + theme.subtitle.size * 0.7),
957 &text_style(&theme.subtitle, anchor),
958 )
959 .map_err(GGError::Render)?;
960 top += theme.subtitle.size * 1.5;
961 }
962 let mut bottom = area.y + area.height;
963 if let Some(c) = &g.caption {
964 let (cx, anchor) = hjust_x(&theme.caption, x0, x1);
965 bottom -= theme.caption.size * 1.8;
966 page.draw_text(
967 c,
968 (cx, bottom + theme.caption.size * 0.9),
969 &text_style(&theme.caption, anchor),
970 )
971 .map_err(GGError::Render)?;
972 }
973 let body_h = (bottom - top).max(1.0);
974 let cols = tracks(&g.widths, g.ncol, area.width, g.spacing);
975 let rows = tracks(&g.heights, g.nrow, body_h, g.spacing);
976 if g.axis_collect != AxisCollect::Keep {
977 align_axes(
978 &mut g.cells,
979 (g.ncol, g.nrow, g.byrow),
980 &cols,
981 &rows,
982 g.axis_collect,
983 warnings,
984 );
985 }
986 for (k, cell) in g.cells.into_iter().enumerate() {
987 let (r, c) = if g.byrow {
988 (k / g.ncol, k % g.ncol)
989 } else {
990 (k % g.nrow, k / g.nrow)
991 };
992 if r >= g.nrow || c >= g.ncol {
993 warnings.push(format!(
995 "plot_grid: cell {} does not fit a {}×{} grid; skipped",
996 k + 1,
997 g.nrow,
998 g.ncol
999 ));
1000 continue;
1001 }
1002 let rect = Rect {
1003 x: area.x + cols[c].0,
1004 y: top + rows[r].0,
1005 width: cols[c].1,
1006 height: rows[r].1,
1007 };
1008 render_prepared(cell, &rect, page, warnings)?;
1009 }
1010 Ok(())
1011 }
1012 }
1013}
1014
1015fn align_axes(
1021 cells: &mut [Prepared],
1022 (ncol, nrow, byrow): (usize, usize, bool),
1025 cols: &[(f64, f64)],
1026 rows: &[(f64, f64)],
1027 mode: AxisCollect,
1028 warnings: &mut Vec<String>,
1029) {
1030 let idx_of = |r: usize, c: usize| -> usize {
1031 if byrow {
1032 r * ncol + c
1033 } else {
1034 c * nrow + r
1035 }
1036 };
1037 for c in 0..ncol {
1038 let cw = cols.get(c).map_or(0.0, |t| t.1);
1039 if !cw.is_finite() || cw <= 0.0 {
1040 continue;
1041 }
1042 let plot_cells: Vec<(usize, usize)> = (0..nrow)
1046 .filter_map(|r| {
1047 let k = idx_of(r, c);
1048 (k < cells.len() && matches!(cells[k], Prepared::Plot(_))).then_some((r, k))
1049 })
1050 .collect();
1051 if plot_cells.len() < 2 {
1052 continue; }
1054 let bottom_row = plot_cells.iter().map(|&(r, _)| r).max().unwrap();
1055
1056 for &(r, k) in &plot_cells {
1061 if let Prepared::Plot(p) = &mut cells[k] {
1062 p.built.theme.axis_text_x_fit = AxisLabelFit::Shift;
1063 if mode == AxisCollect::CollectX && r != bottom_row {
1064 p.built.theme.axis_text_x = ElementText::blank();
1065 p.built.theme.axis_title_x = ElementText::blank();
1066 p.built.theme.axis_ticks_x = Some(ElementLine::blank());
1067 }
1068 }
1069 }
1070
1071 let mut natural: Vec<(f64, f64, f64, f64, f64)> = Vec::with_capacity(plot_cells.len());
1080 for &(r, k) in &plot_cells {
1081 let ch = rows.get(r).map_or(0.0, |t| t.1);
1082 match &mut cells[k] {
1083 Prepared::Plot(p) => {
1084 let layout = GGPlot::layout_built(
1085 &mut p.built,
1086 &p.meta,
1087 cw.floor().max(1.0) as u32,
1088 ch.floor().max(1.0) as u32,
1089 );
1090 natural.push((
1091 layout.plot_area.x,
1092 layout.plot_area.x + layout.plot_area.width,
1093 layout.plot_area.y,
1094 layout.plot_area.height,
1095 ch,
1096 ));
1097 }
1098 _ => unreachable!("plot_cells only holds Prepared::Plot indices"),
1099 }
1100 }
1101
1102 let target_left = natural.iter().fold(f64::MIN, |m, &(l, ..)| m.max(l));
1107 let target_right_inset = natural
1108 .iter()
1109 .fold(f64::MIN, |m, &(_, r, ..)| m.max(cw - r));
1110 let width = cw - target_right_inset - target_left;
1111 if target_left.is_finite() && target_right_inset.is_finite() {
1112 for (&(_, k), &(nl, nr, ..)) in plot_cells.iter().zip(&natural) {
1113 if let Prepared::Plot(p) = &mut cells[k] {
1114 p.built.theme.plot_margin.left += (target_left - nl).max(0.0);
1115 p.built.theme.plot_margin.right += (target_right_inset - (cw - nr)).max(0.0);
1116 }
1117 }
1118 }
1119
1120 if width.is_finite() && width > 0.0 {
1131 for (&(_, k), &(_, _, y, h, ch)) in plot_cells.iter().zip(&natural) {
1132 if let Prepared::Plot(p) = &mut cells[k] {
1133 let bottom_budget = ch - p.built.theme.plot_margin.bottom;
1134 if y + h > bottom_budget + 0.5 {
1135 let fits = (ch - y - p.built.theme.plot_margin.bottom).max(8.0);
1136 p.built.theme.aspect_ratio = Some(fits / width);
1137 p.built.theme.plot_margin.top -= (h - fits) / 2.0;
1138 }
1139 }
1140 }
1141 }
1142
1143 if mode == AxisCollect::CollectX {
1144 collect_x_domain(cells, &plot_cells, warnings);
1145 }
1146 }
1147}
1148
1149fn collect_x_domain(
1158 cells: &mut [Prepared],
1159 plot_cells: &[(usize, usize)],
1160 warnings: &mut Vec<String>,
1161) {
1162 let mut domains = Vec::with_capacity(plot_cells.len());
1163 for &(_, k) in plot_cells {
1164 let d = match &cells[k] {
1165 Prepared::Plot(p) => match p.built.scales.get(&Aesthetic::X) {
1166 Some(s) if !s.is_discrete() => s.domain(),
1167 _ => None,
1168 },
1169 _ => None,
1170 };
1171 match d {
1172 Some(d) => domains.push(d),
1173 None => {
1174 warnings.push(
1175 "plot_grid: a column's x scale is discrete or untrained; x domain not \
1176 collected"
1177 .to_string(),
1178 );
1179 return;
1180 }
1181 }
1182 }
1183 let lo = domains.iter().map(|d| d.0).fold(f64::INFINITY, f64::min);
1184 let hi = domains
1185 .iter()
1186 .map(|d| d.1)
1187 .fold(f64::NEG_INFINITY, f64::max);
1188 if lo.is_finite() && hi.is_finite() && hi >= lo {
1189 for &(_, k) in plot_cells {
1190 if let Prepared::Plot(p) = &mut cells[k] {
1191 p.built.scales.set_limits(&Aesthetic::X, lo, hi);
1192 }
1193 }
1194 }
1195}
1196
1197struct Measure<'a> {
1199 inner: &'a mut SvgBackend,
1200 pa: Rect,
1201 bbox: Option<(f64, f64, f64, f64)>,
1202}
1203
1204impl<'a> Measure<'a> {
1205 fn new(inner: &'a mut SvgBackend, pa: Rect) -> Self {
1206 Measure {
1207 inner,
1208 pa,
1209 bbox: None,
1210 }
1211 }
1212
1213 fn grow(&mut self, x0: f64, y0: f64, x1: f64, y1: f64) {
1214 if !(x0.is_finite() && y0.is_finite() && x1.is_finite() && y1.is_finite()) {
1215 return;
1216 }
1217 self.bbox = Some(match self.bbox {
1218 None => (x0.min(x1), y0.min(y1), x0.max(x1), y0.max(y1)),
1219 Some((a, b, c, d)) => (
1220 a.min(x0.min(x1)),
1221 b.min(y0.min(y1)),
1222 c.max(x0.max(x1)),
1223 d.max(y0.max(y1)),
1224 ),
1225 });
1226 }
1227
1228 fn extent(&self) -> Option<(f64, f64, f64, f64)> {
1229 self.bbox
1230 }
1231}
1232
1233impl DrawBackend for Measure<'_> {
1234 fn draw_circle(
1235 &mut self,
1236 c: (f64, f64),
1237 r: f64,
1238 style: &PointStyle,
1239 ) -> Result<(), RenderError> {
1240 self.grow(c.0 - r, c.1 - r, c.0 + r, c.1 + r);
1241 self.inner.draw_circle(c, r, style)
1242 }
1243 fn draw_line(&mut self, pts: &[(f64, f64)], style: &LineStyle) -> Result<(), RenderError> {
1244 for p in pts {
1245 self.grow(p.0, p.1, p.0, p.1);
1246 }
1247 self.inner.draw_line(pts, style)
1248 }
1249 fn draw_quadratic(
1250 &mut self,
1251 p0: (f64, f64),
1252 ctrl: (f64, f64),
1253 p1: (f64, f64),
1254 style: &LineStyle,
1255 ) -> Result<(), RenderError> {
1256 self.grow(p0.0, p0.1, p0.0, p0.1);
1257 self.grow(ctrl.0, ctrl.1, ctrl.0, ctrl.1);
1258 self.grow(p1.0, p1.1, p1.0, p1.1);
1259 self.inner.draw_quadratic(p0, ctrl, p1, style)
1260 }
1261 fn draw_rect(
1262 &mut self,
1263 a: (f64, f64),
1264 b: (f64, f64),
1265 style: &RectStyle,
1266 ) -> Result<(), RenderError> {
1267 self.grow(a.0, a.1, b.0, b.1);
1268 self.inner.draw_rect(a, b, style)
1269 }
1270 fn draw_text(
1271 &mut self,
1272 text: &str,
1273 pos: (f64, f64),
1274 style: &TextStyle,
1275 ) -> Result<(), RenderError> {
1276 self.draw_text_with_title(text, pos, style, None)
1277 }
1278 fn draw_text_with_title(
1279 &mut self,
1280 text: &str,
1281 pos: (f64, f64),
1282 style: &TextStyle,
1283 title: Option<&str>,
1284 ) -> Result<(), RenderError> {
1285 let w = text.chars().count() as f64 * style.size * 0.6;
1293 let (x0, x1) = match style.anchor {
1294 TextAnchor::Start => (pos.0, pos.0 + w),
1295 TextAnchor::Middle => (pos.0 - w / 2.0, pos.0 + w / 2.0),
1296 TextAnchor::End => (pos.0 - w, pos.0),
1297 };
1298 self.grow(x0, pos.1 - style.size / 2.0, x1, pos.1 + style.size / 2.0);
1299 self.inner.draw_text_with_title(text, pos, style, title)
1300 }
1301 fn draw_polygon(&mut self, pts: &[(f64, f64)], style: &RectStyle) -> Result<(), RenderError> {
1302 for p in pts {
1303 self.grow(p.0, p.1, p.0, p.1);
1304 }
1305 self.inner.draw_polygon(pts, style)
1306 }
1307 fn draw_shape(&mut self, c: (f64, f64), r: f64, style: &PointStyle) -> Result<(), RenderError> {
1308 self.grow(c.0 - r, c.1 - r, c.0 + r, c.1 + r);
1309 self.inner.draw_shape(c, r, style)
1310 }
1311 fn plot_area(&self) -> Rect {
1312 self.pa.clone()
1313 }
1314 fn total_area(&self) -> Rect {
1315 self.inner.total_area()
1316 }
1317 fn set_tooltip(&mut self, t: Option<String>) {
1318 self.inner.set_tooltip(t)
1319 }
1320 fn set_mark_axis(&mut self, k: Option<String>) {
1321 self.inner.set_mark_axis(k)
1322 }
1323 fn set_mark_series(&mut self, s: Option<String>) {
1324 self.inner.set_mark_series(s)
1325 }
1326 fn set_mark_value(&mut self, v: Option<String>) {
1327 self.inner.set_mark_value(v)
1328 }
1329 fn warn(&mut self, m: String) {
1330 self.inner.warn(m)
1331 }
1332 fn set_mark_geom(&mut self, geom: Option<&str>) {
1333 self.inner.set_mark_geom(geom)
1334 }
1335 fn set_mark_part(&mut self, part: Option<&str>) {
1336 self.inner.set_mark_part(part)
1337 }
1338 fn set_mark_attrs(&mut self, attrs: Vec<(String, String)>) {
1339 self.inner.set_mark_attrs(attrs)
1340 }
1341 fn wants_formatted_values(&self) -> bool {
1342 self.inner.wants_formatted_values()
1343 }
1344 fn set_mark_fvalue(&mut self, value: Option<String>) {
1345 self.inner.set_mark_fvalue(value)
1346 }
1347 fn set_mark_fx(&mut self, value: Option<String>) {
1348 self.inner.set_mark_fx(value)
1349 }
1350}
1351
1352fn join(op: Op, a: GridCell, b: GridCell) -> PlotGrid {
1355 let flatten = |c: GridCell| -> Vec<GridCell> {
1356 match c {
1357 GridCell::Grid(g) if g.op == Some(op) && g.is_plain() => g.cells,
1358 other => vec![other],
1359 }
1360 };
1361 let mut cells = flatten(a);
1362 cells.extend(flatten(b));
1363 PlotGrid {
1364 cells,
1365 op: Some(op),
1366 ..PlotGrid::default()
1367 }
1368}
1369
1370impl PlotGrid {
1371 fn is_plain(&self) -> bool {
1374 self.ncol.is_none()
1375 && self.nrow.is_none()
1376 && self.widths.is_empty()
1377 && self.heights.is_empty()
1378 && self.title.is_none()
1379 && self.subtitle.is_none()
1380 && self.caption.is_none()
1381 && self.tags.is_none()
1382 && !self.collect_legends
1383 && self.axis_collect == AxisCollect::Keep
1384 }
1385}
1386
1387macro_rules! grid_ops {
1388 ($lhs:ty, $rhs:ty) => {
1389 impl BitOr<$rhs> for $lhs {
1391 type Output = PlotGrid;
1392 fn bitor(self, rhs: $rhs) -> PlotGrid {
1393 join(Op::Row, self.into(), rhs.into())
1394 }
1395 }
1396 impl Div<$rhs> for $lhs {
1398 type Output = PlotGrid;
1399 fn div(self, rhs: $rhs) -> PlotGrid {
1400 join(Op::Col, self.into(), rhs.into())
1401 }
1402 }
1403 };
1404}
1405
1406grid_ops!(GGPlot, GGPlot);
1407grid_ops!(GGPlot, PlotGrid);
1408grid_ops!(PlotGrid, GGPlot);
1409grid_ops!(PlotGrid, PlotGrid);
1410
1411#[cfg(test)]
1412mod tests {
1413 use super::*;
1414
1415 #[test]
1416 fn tag_sequences() {
1417 let l: Vec<String> = (0..28).map(|i| TagLevels::Lower.tag(i)).collect();
1418 assert_eq!(&l[..3], &["a", "b", "c"]);
1419 assert_eq!(l[25], "z");
1420 assert_eq!(l[26], "aa");
1421 assert_eq!(l[27], "ab");
1422 assert_eq!(TagLevels::Upper.tag(1), "B");
1423 assert_eq!(TagLevels::Numeric.tag(9), "10");
1424 assert_eq!(TagLevels::LowerRoman.tag(3), "iv");
1425 assert_eq!(TagLevels::UpperRoman.tag(13), "XIV");
1426 assert_eq!(TagLevels::Custom(vec!["x".into()]).tag(1), "2");
1427 }
1428
1429 #[test]
1430 fn tracks_are_relative_and_robust() {
1431 let t = tracks(&[2.0, 1.0], 2, 300.0, 0.0);
1432 assert_eq!(t, vec![(0.0, 200.0), (200.0, 100.0)]);
1433 let t = tracks(&[f64::NAN, -1.0], 2, 100.0, 10.0);
1434 assert_eq!(t, vec![(0.0, 45.0), (55.0, 45.0)]);
1435 let t = tracks(&[], 3, 30.0, 100.0);
1436 assert!(t.iter().all(|(p, s)| p.is_finite() && *s == 0.0));
1437 }
1438
1439 #[test]
1443 fn measure_forwards_draw_quadratic_and_mark_metadata_and_grows_its_extent() {
1444 let pa = Rect {
1445 x: 0.0,
1446 y: 0.0,
1447 width: 100.0,
1448 height: 100.0,
1449 };
1450 let mut backend = SvgBackend::new(100, 100, pa.clone());
1451 backend.set_formatted_values(true);
1452 let mut meas = Measure::new(&mut backend, pa);
1453
1454 assert!(meas.extent().is_none());
1455 assert!(meas.wants_formatted_values());
1457 meas.set_mark_geom(Some("line"));
1458 meas.set_mark_part(Some("arrow"));
1459 meas.set_mark_attrs(vec![("data-x".to_string(), "v".to_string())]);
1460 meas.set_mark_fvalue(Some("1,234.5".to_string()));
1461 meas.set_mark_fx(Some("2026-10-12".to_string()));
1462 meas.draw_quadratic(
1463 (10.0, 20.0),
1464 (90.0, 5.0),
1465 (50.0, 80.0),
1466 &LineStyle::default(),
1467 )
1468 .unwrap();
1469 meas.set_mark_geom(None);
1470 meas.set_mark_part(None);
1471 meas.set_mark_attrs(Vec::new());
1472 meas.set_mark_fvalue(None);
1473 meas.set_mark_fx(None);
1474
1475 let (x0, y0, x1, y1) = meas.extent().expect("extent after drawing");
1476 assert_eq!((x0, y0, x1, y1), (10.0, 5.0, 90.0, 80.0));
1477
1478 let svg = backend.finish();
1482 assert!(svg.contains("data-part=\"arrow\""));
1483 assert!(svg.contains("data-x=\"v\""));
1484 assert!(svg.contains("gg-arrow"));
1485 assert!(svg.contains("data-fvalue=\"1,234.5\""));
1486 assert!(svg.contains("data-fx=\"2026-10-12\""));
1487 }
1488
1489 #[test]
1500 fn measure_forwards_the_title_to_its_inner_backend() {
1501 let pa = Rect {
1502 x: 0.0,
1503 y: 0.0,
1504 width: 100.0,
1505 height: 100.0,
1506 };
1507 let mut backend = SvgBackend::new(100, 100, pa.clone());
1508 let mut meas = Measure::new(&mut backend, pa);
1509 meas.draw_text_with_title(
1510 "Grp…",
1511 (10.0, 20.0),
1512 &TextStyle {
1513 size: 12.0,
1514 anchor: TextAnchor::Start,
1515 ..Default::default()
1516 },
1517 Some("Group 01"),
1518 )
1519 .unwrap();
1520 let svg = backend.finish();
1521 assert!(
1522 svg.contains("<title>Group 01</title>"),
1523 "the full label should reach the inner backend's <title>: {svg}"
1524 );
1525 }
1526}