1use crate::aes::Aesthetic;
2use crate::annotate::Annotation;
3use crate::build::BuiltPlot;
4use crate::facet::Facet;
5use crate::guide::{axis, legend};
6use crate::render::backend::{DrawBackend, LineStyle, Linetype, RectStyle, TextAnchor, TextStyle};
7use crate::render::RenderError;
8
9pub struct PlotRenderer;
11
12impl PlotRenderer {
13 fn top_axis_lift(built: &BuiltPlot, theme: &crate::theme::Theme) -> f64 {
16 let Some(xs) = built.scales.get(&Aesthetic::X) else {
17 return 0.0;
18 };
19 if xs.axis_position_opposite() {
20 theme.axis_ticks_length + theme.axis_text_x.size + theme.legend_spacing
21 } else if let Some(sec) = xs.sec_axis().filter(|_| built.facet.is_none()) {
22 axis::sec_x_axis_height(theme, sec)
23 } else {
24 0.0
25 }
26 }
27
28 pub fn render(built: &BuiltPlot, backend: &mut dyn DrawBackend) -> Result<(), RenderError> {
29 backend.enable_element_classes(built.svg_classes);
31 let drawn = if !built.facet.is_none() && !built.panels.is_empty() {
32 Self::render_faceted(built, backend)
33 } else {
34 Self::render_single(built, backend)
35 };
36 backend.set_element_class(None);
37 backend.enable_element_classes(false);
38 drawn
39 }
40
41 fn render_single(built: &BuiltPlot, backend: &mut dyn DrawBackend) -> Result<(), RenderError> {
42 let theme = &built.theme;
43 let plot_area = backend.plot_area();
44 let total_area = backend.total_area();
45 backend.clear_corner_claims();
51 if let Some(r) = built.coord.data_rect(&plot_area) {
52 backend.set_viewport(&r);
53 }
54 if let Some(rect) = legend::inside_legend_box(
55 &built.scales,
56 theme,
57 &plot_area,
58 &total_area,
59 &built.guide_legend,
60 &built.suppressed_aes,
61 &built.legend_plans,
62 ) {
63 backend.claim_corner_box(rect);
64 }
65
66 if theme.plot_background.visible {
68 if let Some(fill) = theme.plot_background.fill {
69 backend.set_element_class(Some("gg-plot-background"));
70 backend.draw_rect(
71 (total_area.x, total_area.y),
72 (
73 total_area.x + total_area.width,
74 total_area.y + total_area.height,
75 ),
76 &RectStyle {
77 fill: Some(fill),
78 stroke: None,
79 stroke_width: 0.0,
80 alpha: 1.0,
81 clip: false,
82 corner_radius: 0.0,
83 },
84 )?;
85 }
86 }
87
88 if theme.panel_background.visible {
90 if let Some(fill) = theme.panel_background.fill {
91 backend.set_element_class(Some("gg-panel-background"));
92 backend.draw_rect(
93 (plot_area.x, plot_area.y),
94 (
95 plot_area.x + plot_area.width,
96 plot_area.y + plot_area.height,
97 ),
98 &RectStyle {
99 fill: Some(fill),
100 stroke: theme.panel_background.color,
101 stroke_width: theme.panel_background.width,
102 alpha: 1.0,
103 clip: false,
104 corner_radius: 0.0,
105 },
106 )?;
107 }
108 }
109
110 if theme.panel_border.visible {
112 let style = LineStyle {
113 color: theme.panel_border.color,
114 width: theme.panel_border.width,
115 alpha: 1.0,
116 linetype: Linetype::Solid,
117 ..Default::default()
118 };
119 let x0 = plot_area.x;
120 let y0 = plot_area.y;
121 let x1 = plot_area.x + plot_area.width;
122 let y1 = plot_area.y + plot_area.height;
123 backend.set_element_class(Some("gg-panel-border"));
124 backend.draw_line(&[(x0, y0), (x1, y0)], &style)?;
125 backend.draw_line(&[(x1, y0), (x1, y1)], &style)?;
126 backend.draw_line(&[(x1, y1), (x0, y1)], &style)?;
127 backend.draw_line(&[(x0, y1), (x0, y0)], &style)?;
128 }
129
130 let x_scale = built.scales.get(&Aesthetic::X);
132 let y_scale = built.scales.get(&Aesthetic::Y);
133
134 let (h_scale, v_scale) = if built.coord.is_flipped() {
135 (y_scale, x_scale)
136 } else {
137 (x_scale, y_scale)
138 };
139
140 if let (true, Some(xs), Some(ys)) = (built.coord.is_radar(), x_scale, y_scale) {
141 crate::guide::polar::draw_radar_guides(
143 xs,
144 ys,
145 built.coord.as_ref(),
146 theme,
147 &plot_area,
148 backend,
149 )?;
150 } else if let (true, Some(xs), Some(ys)) = (built.coord.is_polar(), x_scale, y_scale) {
151 crate::guide::polar::draw_polar_guides(
154 xs,
155 ys,
156 built.coord.as_ref(),
157 theme,
158 &plot_area,
159 backend,
160 )?;
161 axis::draw_x_axis_title(xs, theme, &plot_area, backend)?;
162 let reserve = axis::y_label_reserve(theme, &ys.breaks());
163 axis::draw_y_axis_title(ys, theme, &plot_area, reserve, backend)?;
164 } else if let (Some(hs), Some(vs)) = (h_scale, v_scale) {
165 if built.coord.gridlines() && !theme.panel_ontop {
167 axis::draw_gridlines(hs, vs, built.coord.as_ref(), theme, &plot_area, backend)?;
168 }
169
170 axis::draw_x_axis(
172 hs,
173 built.coord.as_ref(),
174 theme,
175 &plot_area,
176 &total_area,
177 backend,
178 )?;
179 axis::draw_y_axis(vs, built.coord.as_ref(), theme, &plot_area, backend)?;
180
181 if let Some(sec) = built.scales.sec_axis(&Aesthetic::Y) {
183 axis::draw_sec_y_axis(vs, sec, built.coord.as_ref(), theme, &plot_area, backend)?;
184 }
185 if let Some(sec) = hs.sec_axis().filter(|_| !hs.axis_position_opposite()) {
188 axis::draw_sec_x_axis(hs, sec, built.coord.as_ref(), theme, &plot_area, backend)?;
189 }
190 }
191
192 backend.set_element_class(None);
198 let clip_group = built.clip
199 && built
200 .layers
201 .iter()
202 .any(|l| layer_spills(&l.data, &built.scales, built.coord.as_ref(), &plot_area));
203 if clip_group {
204 backend.begin_clip(&plot_area);
205 }
206 if !built.clip {
207 backend.set_clipping(false);
208 }
209 for layer in built.layers.iter().filter(|l| l.data.nrows() > 0) {
210 backend.set_mark_geom(Some(layer.geom.name()));
211 let drawn = layer.geom.draw(
212 &layer.data,
213 built.coord.as_ref(),
214 &built.scales,
215 theme,
216 backend,
217 );
218 backend.set_mark_geom(None);
219 drawn?;
220 }
221 if !built.clip {
222 backend.set_clipping(true);
223 }
224 if clip_group {
225 backend.end_clip();
226 }
227
228 if theme.panel_ontop && built.coord.gridlines() {
230 if let (Some(hs), Some(vs)) = (h_scale, v_scale) {
231 axis::draw_gridlines(hs, vs, built.coord.as_ref(), theme, &plot_area, backend)?;
232 }
233 }
234
235 backend.set_element_class(None);
236 Self::draw_annotations(
238 &built.annotations,
239 &built.scales,
240 built.coord.as_ref(),
241 &plot_area,
242 theme,
243 backend,
244 )?;
245
246 let title_ref = Self::title_ref_rect(theme, &plot_area, &total_area);
248 let caption_ref = Self::ref_rect(
249 theme.caption_position.unwrap_or(theme.title_position),
250 theme,
251 &plot_area,
252 &total_area,
253 );
254 let legend_lift = legend::top_legend_lift(
259 theme,
260 &built.scales,
261 &built.suppressed_aes,
262 &built.legend_plans,
263 &built.guide_legend,
264 );
265 if let Some(ref title) = built.labels.title {
266 let (tx, anchor) = Self::hjust_pos(&theme.title, &title_ref);
267 let x_axis_lift = Self::top_axis_lift(built, theme);
270 let (title_y, _) = Self::title_subtitle_y(
271 theme,
272 plot_area.y,
273 x_axis_lift + legend_lift,
274 built.labels.subtitle.is_some(),
275 );
276 let family = if theme.title.family.is_empty() {
277 None
278 } else {
279 Some(theme.title.family.clone())
280 };
281 backend.set_element_class(Some("gg-title"));
282 crate::render::rich::draw(
283 backend,
284 theme.rich_text,
285 title,
286 (tx, title_y),
287 &TextStyle {
288 color: theme.title.color,
289 size: theme.title.size,
290 anchor,
291 angle: 0.0,
292 family,
293 face: theme.title.face,
294 bg_colour: None,
295 bg_r: 0.0,
296 },
297 )?;
298 }
299
300 if let Some(ref subtitle) = built.labels.subtitle {
302 let (sx, anchor) = Self::hjust_pos(&theme.subtitle, &title_ref);
303 let x_axis_lift = Self::top_axis_lift(built, theme);
305 let (_, subtitle_y) =
306 Self::title_subtitle_y(theme, plot_area.y, x_axis_lift + legend_lift, true);
307 let family = if theme.subtitle.family.is_empty() {
308 None
309 } else {
310 Some(theme.subtitle.family.clone())
311 };
312 backend.set_element_class(Some("gg-subtitle"));
313 crate::render::rich::draw(
314 backend,
315 theme.rich_text,
316 subtitle,
317 (sx, subtitle_y),
318 &TextStyle {
319 color: theme.subtitle.color,
320 size: theme.subtitle.size,
321 anchor,
322 angle: 0.0,
323 family,
324 face: theme.subtitle.face,
325 bg_colour: None,
326 bg_r: 0.0,
327 },
328 )?;
329 }
330
331 let direct = built.direct_labels
333 && matches!(theme.legend_position, crate::theme::LegendPosition::Right)
334 && super::direct_labels::draw(built, &plot_area, backend)?;
335 if !direct {
336 legend::draw_legend_planned(
337 &built.scales,
338 theme,
339 &plot_area,
340 plot_area.width,
341 backend,
342 &built.guide_legend,
343 &built.suppressed_aes,
344 &built.legend_plans,
345 )?;
346 }
347
348 if let Some(ref caption) = built.labels.caption {
350 let (cx, anchor) = Self::hjust_pos(&theme.caption, &caption_ref);
351 let caption_y = total_area.y + total_area.height
354 - theme.plot_margin.bottom.max(0.0)
355 - theme.caption.size * 0.5;
356 let family = if theme.caption.family.is_empty() {
357 None
358 } else {
359 Some(theme.caption.family.clone())
360 };
361 backend.set_element_class(Some("gg-caption"));
362 crate::render::rich::draw(
363 backend,
364 theme.rich_text,
365 caption,
366 (cx, caption_y),
367 &TextStyle {
368 color: theme.caption.color,
369 size: theme.caption.size,
370 anchor,
371 angle: 0.0,
372 family,
373 face: theme.caption.face,
374 bg_colour: None,
375 bg_r: 0.0,
376 },
377 )?;
378 }
379
380 let tag_area = if theme.tag_location_panel {
384 &plot_area
385 } else {
386 &total_area
387 };
388 Self::draw_tag(&built.labels, theme, tag_area, backend)?;
389
390 Ok(())
391 }
392
393 fn hjust_pos(
396 el: &crate::theme::elements::ElementText,
397 area: &crate::render::Rect,
398 ) -> (f64, TextAnchor) {
399 let x = area.x + el.hjust.clamp(0.0, 1.0) * area.width;
400 let anchor = if el.hjust <= 0.02 {
401 TextAnchor::Start
402 } else if el.hjust >= 0.98 {
403 TextAnchor::End
404 } else {
405 TextAnchor::Middle
406 };
407 (x, anchor)
408 }
409
410 fn title_subtitle_y(
419 theme: &crate::theme::Theme,
420 panel_top: f64,
421 lift: f64,
422 has_subtitle: bool,
423 ) -> (f64, f64) {
424 let base = panel_top - lift;
425 let subtitle_band = if has_subtitle {
426 theme.subtitle.size * 1.5
427 } else {
428 0.0
429 };
430 let subtitle_y = base - subtitle_band / 2.0;
431 let title_y = (base - subtitle_band - theme.title.size * 0.9).max(theme.title.size);
432 (title_y, subtitle_y)
433 }
434
435 fn title_ref_rect(
438 theme: &crate::theme::Theme,
439 plot_area: &crate::render::Rect,
440 total_area: &crate::render::Rect,
441 ) -> crate::render::Rect {
442 Self::ref_rect(theme.title_position, theme, plot_area, total_area)
443 }
444
445 fn ref_rect(
448 pos: crate::theme::TitlePosition,
449 theme: &crate::theme::Theme,
450 plot_area: &crate::render::Rect,
451 total_area: &crate::render::Rect,
452 ) -> crate::render::Rect {
453 match pos {
454 crate::theme::TitlePosition::Panel => plot_area.clone(),
455 crate::theme::TitlePosition::Plot => crate::render::Rect {
456 x: total_area.x + theme.plot_margin.left,
457 y: plot_area.y,
458 width: (total_area.width - theme.plot_margin.left - theme.plot_margin.right)
459 .max(1.0),
460 height: plot_area.height,
461 },
462 }
463 }
464
465 pub(crate) fn draw_cell_tag(
468 labels: &crate::plot::Labels,
469 theme: &crate::theme::Theme,
470 area: &crate::render::Rect,
471 backend: &mut dyn DrawBackend,
472 ) -> Result<(), RenderError> {
473 Self::draw_tag(labels, theme, area, backend)
474 }
475
476 fn draw_tag(
477 labels: &crate::plot::Labels,
478 theme: &crate::theme::Theme,
479 total_area: &crate::render::Rect,
480 backend: &mut dyn DrawBackend,
481 ) -> Result<(), RenderError> {
482 if let Some(ref tag) = labels.tag {
483 let family = if theme.title.family.is_empty() {
484 None
485 } else {
486 Some(theme.title.family.clone())
487 };
488 use crate::theme::TagPosition::*;
489 let pad = theme.title.size;
490 let (left, right) = (total_area.x + pad, total_area.x + total_area.width - pad);
491 let (top, bottom) = (total_area.y + pad, total_area.y + total_area.height - pad);
492 let (x, y, anchor) = match theme.tag_position {
493 TopLeft => (left, top, TextAnchor::Start),
494 TopRight => (right, top, TextAnchor::End),
495 BottomLeft => (left, bottom, TextAnchor::Start),
496 BottomRight => (right, bottom, TextAnchor::End),
497 };
498 backend.set_element_class(Some("gg-tag"));
499 backend.draw_text(
500 tag,
501 (x, y),
502 &TextStyle {
503 color: theme.title.color,
504 size: theme.title.size,
505 anchor,
506 angle: 0.0,
507 family,
508 face: theme.title.face,
509 bg_colour: None,
510 bg_r: 0.0,
511 },
512 )?;
513 }
514 Ok(())
515 }
516
517 fn render_faceted(built: &BuiltPlot, backend: &mut dyn DrawBackend) -> Result<(), RenderError> {
518 let theme = &built.theme;
519 let plot_area = backend.plot_area();
520 let total_area = backend.total_area();
521
522 if theme.plot_background.visible {
524 if let Some(fill) = theme.plot_background.fill {
525 backend.set_element_class(Some("gg-plot-background"));
526 backend.draw_rect(
527 (total_area.x, total_area.y),
528 (
529 total_area.x + total_area.width,
530 total_area.y + total_area.height,
531 ),
532 &RectStyle {
533 fill: Some(fill),
534 stroke: None,
535 stroke_width: 0.0,
536 alpha: 1.0,
537 clip: false,
538 corner_radius: 0.0,
539 },
540 )?;
541 }
542 }
543
544 let ncol = match &built.facet {
546 Facet::Wrap { ncol, .. } => {
547 ncol.unwrap_or_else(|| (built.panels.len() as f64).sqrt().ceil() as usize)
548 }
549 Facet::Grid { .. } => built.panels.iter().map(|p| p.col).max().unwrap_or(0) + 1,
550 Facet::None => 1,
551 };
552 let mut nrow = built.panels.len().div_ceil(ncol);
553
554 let strip_lines = |label: &dyn Fn(&crate::facet::Panel) -> Option<String>| {
557 built
558 .panels
559 .iter()
560 .filter_map(|p| label(p).map(|l| l.lines().count()))
561 .max()
562 .unwrap_or(1)
563 .max(1)
564 };
565 let size_x = theme
568 .strip_text_x
569 .as_ref()
570 .unwrap_or(&theme.strip_text)
571 .size;
572 let size_y = theme
573 .strip_text_y
574 .as_ref()
575 .unwrap_or(&theme.strip_text)
576 .size;
577 let thickness = |lines: usize, size: f64| size * (1.0 + 1.2 * (lines - 1) as f64) + 8.0;
578 let is_grid = matches!(built.facet, Facet::Grid { .. });
582 let col_strip = |p: &crate::facet::Panel| {
583 if is_grid {
584 p.col_label.clone()
585 } else {
586 Some(p.label.clone())
587 }
588 };
589 let row_strip = |p: &crate::facet::Panel| {
590 if is_grid {
591 p.row_label.clone()
592 } else {
593 None
594 }
595 };
596 let row_strip_width = thickness(strip_lines(&row_strip), size_y);
597 let (wrap_side, switch) = match &built.facet {
598 Facet::Wrap { strip_position, .. } => {
599 (*strip_position, crate::facet::FacetSwitch::None)
600 }
601 Facet::Grid { switch, .. } => (crate::facet::StripPosition::Top, *switch),
602 Facet::None => (
603 crate::facet::StripPosition::Top,
604 crate::facet::FacetSwitch::None,
605 ),
606 };
607 let wrap_vertical = matches!(
609 wrap_side,
610 crate::facet::StripPosition::Left | crate::facet::StripPosition::Right
611 );
612 let (free_x, free_y) = match &built.facet {
615 Facet::Wrap { scales, .. } => (
616 matches!(
617 scales,
618 crate::facet::FacetScales::FreeX | crate::facet::FacetScales::Free
619 ),
620 matches!(
621 scales,
622 crate::facet::FacetScales::FreeY | crate::facet::FacetScales::Free
623 ),
624 ),
625 _ => (false, false),
626 };
627 let flipped = built.coord.is_flipped();
631 let (h_aes, v_aes) = if flipped {
632 (Aesthetic::Y, Aesthetic::X)
633 } else {
634 (Aesthetic::X, Aesthetic::Y)
635 };
636 let (free_x, free_y) = if flipped {
637 (free_y, free_x)
638 } else {
639 (free_x, free_y)
640 };
641 let all_x = built.facet_axes.all_x || free_x;
642 let all_y = built.facet_axes.all_y || free_y;
643 let inner_labels_x = !built.facet_axes.margin_labels_x || free_x;
645 let inner_labels_y = !built.facet_axes.margin_labels_y || free_y;
646 let unlabelled = |x: bool| {
647 let mut t = theme.clone();
648 if x {
649 t.axis_text_x.visible = false;
650 } else {
651 t.axis_text_y.visible = false;
652 }
653 t
654 };
655 let theme_no_x_labels = unlabelled(true);
656 let theme_no_y_labels = unlabelled(false);
657 let gap_x = theme.get_panel_spacing_x()
658 + if all_y && built.panels.len() > 1 {
659 theme.axis_ticks_length
660 + if inner_labels_y && theme.axis_text_y.visible {
661 built
662 .panel_scales
663 .iter()
664 .chain(std::iter::once(&built.scales))
665 .filter_map(|s| s.get(&v_aes))
666 .map(|ys| axis::y_label_reserve(theme, &ys.breaks()))
667 .fold(0.0_f64, f64::max)
668 } else {
669 0.0
670 }
671 } else {
672 0.0
673 };
674 let gap_y = theme.get_panel_spacing_y()
675 + if all_x && built.panels.len() > 1 {
676 if inner_labels_x {
677 super::layout::PlotLayout::x_axis_band(theme, None)
678 } else {
679 theme.axis_ticks_length
680 }
681 } else {
682 0.0
683 };
684 let strip_height = thickness(
685 strip_lines(&col_strip),
686 if wrap_vertical { size_y } else { size_x },
687 );
688
689 let is_figure = |li: usize| {
692 built.layers[li]
693 .geom
694 .figure_band_height(plot_area.width, theme)
695 .is_some()
696 };
697 let band_h: f64 = built
698 .layers
699 .iter()
700 .filter_map(|l| l.geom.figure_band_height(plot_area.width, theme))
701 .sum::<f64>()
702 .min(plot_area.height * 0.5);
703 let band_rect = crate::render::Rect {
704 x: plot_area.x,
705 y: plot_area.y + plot_area.height - band_h,
706 width: plot_area.width,
707 height: band_h,
708 };
709 let plot_area = crate::render::Rect {
710 height: plot_area.height - band_h,
711 ..plot_area
712 };
713
714 let fixed_grid = match (&built.facet, built.coord.fixed_aspect()) {
719 (Facet::Wrap { ncol: want, .. }, Some(aspect)) => Some(crate::facet::wrap::fit_grid(
720 built.panels.len(),
721 *want,
722 aspect,
723 plot_area.width
724 - if wrap_vertical {
725 strip_height * want.unwrap_or(1) as f64
726 } else {
727 0.0
728 },
729 plot_area.height,
730 if wrap_vertical { 0.0 } else { strip_height },
731 gap_x,
732 gap_y,
733 )),
734 _ => None,
735 };
736 let ncol = if let Some(g) = fixed_grid {
737 nrow = g.nrow;
738 g.ncol
739 } else {
740 ncol
741 };
742 let cell: Vec<(usize, usize)> = built
745 .panels
746 .iter()
747 .enumerate()
748 .map(|(i, p)| {
749 if fixed_grid.is_some() {
750 match &built.facet {
751 Facet::Wrap {
752 vertical, as_table, ..
753 } => crate::facet::wrap::wrap_cell(
754 i,
755 built.panels.len(),
756 ncol,
757 *vertical,
758 *as_table,
759 ),
760 _ => (i / ncol, i % ncol),
761 }
762 } else {
763 (p.row, p.col)
764 }
765 })
766 .collect();
767
768 use crate::facet::StripPosition as Side;
772 let outside = theme.strip_placement_outside;
775 let x_axis_off =
776 super::layout::PlotLayout::x_axis_band(theme, None) + theme.strip_switch_pad;
777 let y_axis_off = theme.axis_ticks_length
778 + built
779 .panel_scales
780 .iter()
781 .chain(std::iter::once(&built.scales))
782 .filter_map(|s| s.get(&v_aes))
783 .map(|ys| axis::y_label_reserve(theme, &ys.breaks()))
784 .fold(0.0_f64, f64::max)
785 + theme.strip_switch_pad;
786 let n_panels = built.panels.len();
787 let draws_x = |pi: usize, r: usize| r == nrow - 1 || pi + ncol >= n_panels || all_x;
788 let draws_y = |c: usize| c == 0 || all_y;
789 let off = |side: Side, pi: usize, r: usize, c: usize| match side {
790 Side::Bottom if outside && draws_x(pi, r) => x_axis_off,
791 Side::Left if outside && draws_y(c) => y_axis_off,
792 _ => 0.0,
793 };
794 let strips: Vec<Vec<(Side, String, f64)>> = built
795 .panels
796 .iter()
797 .enumerate()
798 .map(|(pi, p)| {
799 let (r, c) = cell[pi];
800 let mut v = Vec::new();
801 if is_grid {
802 if let Some(l) = &p.col_label {
803 if switch.x() && r == nrow - 1 {
804 v.push((Side::Bottom, l.clone(), strip_height));
805 } else if !switch.x() && r == 0 {
806 v.push((Side::Top, l.clone(), strip_height));
807 }
808 }
809 if let Some(l) = &p.row_label {
810 if switch.y() && c == 0 {
811 v.push((Side::Left, l.clone(), row_strip_width));
812 } else if !switch.y() && c == ncol - 1 {
813 v.push((Side::Right, l.clone(), row_strip_width));
814 }
815 }
816 } else {
817 v.push((wrap_side, p.label.clone(), strip_height));
818 }
819 v
820 })
821 .collect();
822 let mut band_top = vec![0.0_f64; nrow.max(1)];
823 let mut band_bottom = vec![0.0_f64; nrow.max(1)];
824 let mut band_left = vec![0.0_f64; ncol.max(1)];
825 let mut band_right = vec![0.0_f64; ncol.max(1)];
826 for (pi, list) in strips.iter().enumerate() {
827 let (r, c) = cell[pi];
828 for (side, _, t) in list {
829 let o = off(*side, pi, r, c);
830 let b = match side {
831 Side::Top => &mut band_top[r],
832 Side::Bottom => &mut band_bottom[r],
833 Side::Left => &mut band_left[c],
834 Side::Right => &mut band_right[c],
835 };
836 *b = b.max(*t + o);
837 }
838 }
839 if !is_grid {
842 match wrap_side {
843 Side::Top => band_top.fill(strip_height),
844 Side::Bottom => band_bottom
845 .iter_mut()
846 .for_each(|b| *b = b.max(strip_height)),
847 Side::Left => band_left.iter_mut().for_each(|b| *b = b.max(strip_height)),
848 Side::Right => band_right.fill(strip_height),
849 }
850 }
851
852 let space = match &built.facet {
855 Facet::Grid { space, .. } => space.clone(),
856 Facet::Wrap { space, .. } if fixed_grid.is_none() => {
858 use crate::facet::FacetSpace as S;
859 match (space.free_x() && nrow == 1, space.free_y() && ncol == 1) {
860 (true, true) => S::Free,
861 (true, false) => S::FreeX,
862 (false, true) => S::FreeY,
863 _ => S::Fixed,
864 }
865 }
866 _ => crate::facet::FacetSpace::Fixed,
867 };
868 let extent = |pi: usize, col: &str| -> Option<f64> {
869 let (mut lo, mut hi) = (f64::INFINITY, f64::NEG_INFINITY);
870 for df in &built.panels_data[pi] {
871 if let Some(c) = df.column(col) {
872 for v in c {
873 if let Some(f) = v.as_f64() {
874 lo = lo.min(f);
875 hi = hi.max(f);
876 }
877 }
878 }
879 }
880 (lo <= hi).then_some(hi - lo)
881 };
882 let avail_w = plot_area.width
883 - gap_x * (ncol as f64 - 1.0)
884 - band_left.iter().sum::<f64>()
885 - band_right.iter().sum::<f64>();
886 let col_widths: Vec<f64> = if let Some(g) = fixed_grid {
887 vec![g.panel_w; ncol]
888 } else if space.free_x() && ncol > 0 {
889 let mut ranges = vec![0.0f64; ncol];
890 for (pi, panel) in built.panels.iter().enumerate() {
891 if let Some(r) = extent(pi, "x") {
892 ranges[panel.col] = ranges[panel.col].max(r);
893 }
894 }
895 let total: f64 = ranges.iter().sum();
896 if total > 0.0 {
897 ranges.iter().map(|r| avail_w * (r / total)).collect()
898 } else {
899 vec![avail_w / ncol as f64; ncol]
900 }
901 } else {
902 vec![avail_w / ncol.max(1) as f64; ncol.max(1)]
903 };
904 let mut col_x = vec![plot_area.x; ncol.max(1)];
905 {
906 let used_w: f64 = col_widths.iter().sum::<f64>()
907 + gap_x * (ncol as f64 - 1.0)
908 + band_left.iter().sum::<f64>()
909 + band_right.iter().sum::<f64>();
910 let mut acc = if fixed_grid.is_some() {
911 plot_area.x + ((plot_area.width - used_w) / 2.0).max(0.0)
912 } else {
913 plot_area.x
914 };
915 for c in 0..ncol {
916 col_x[c] = acc + band_left[c];
917 acc += band_left[c] + col_widths[c] + band_right[c] + gap_x;
918 }
919 }
920
921 let avail_h = plot_area.height
922 - gap_y * (nrow as f64 - 1.0)
923 - band_top.iter().sum::<f64>()
924 - band_bottom.iter().sum::<f64>();
925 let row_heights: Vec<f64> = if let Some(g) = fixed_grid {
926 vec![g.panel_h; nrow]
927 } else if space.free_y() && nrow > 0 {
928 let mut ranges = vec![0.0f64; nrow];
929 for (pi, panel) in built.panels.iter().enumerate() {
930 if let Some(r) = extent(pi, "y") {
931 ranges[panel.row] = ranges[panel.row].max(r);
932 }
933 }
934 let total: f64 = ranges.iter().sum();
935 if total > 0.0 {
936 ranges.iter().map(|r| avail_h * (r / total)).collect()
937 } else {
938 vec![avail_h / nrow as f64; nrow]
939 }
940 } else {
941 vec![avail_h / nrow.max(1) as f64; nrow.max(1)]
942 };
943 let mut row_y = vec![plot_area.y; nrow.max(1)];
944 {
945 let used_h: f64 = row_heights.iter().sum::<f64>()
946 + gap_y * (nrow as f64 - 1.0)
947 + band_top.iter().sum::<f64>()
948 + band_bottom.iter().sum::<f64>();
949 let mut acc = if fixed_grid.is_some() {
950 plot_area.y + ((plot_area.height - used_h) / 2.0).max(0.0)
951 } else {
952 plot_area.y
953 };
954 for r in 0..nrow {
955 row_y[r] = acc + band_top[r];
957 acc += band_top[r] + row_heights[r] + band_bottom[r] + gap_y;
958 }
959 }
960
961 let mut x_title_area: Option<super::Rect> = None;
965 let mut y_title_area: Option<(super::Rect, f64)> = None;
966 let union = |a: &Option<super::Rect>, b: &super::Rect| match a {
967 None => b.clone(),
968 Some(a) => {
969 let (x0, y0) = (a.x.min(b.x), a.y.min(b.y));
970 let x1 = (a.x + a.width).max(b.x + b.width);
971 let y1 = (a.y + a.height).max(b.y + b.height);
972 super::Rect {
973 x: x0,
974 y: y0,
975 width: x1 - x0,
976 height: y1 - y0,
977 }
978 }
979 };
980
981 for (pi, panel) in built.panels.iter().enumerate() {
982 let (prow, pcol) = cell[pi];
983 let panel_width = col_widths[pcol];
984 let panel_height = row_heights[prow];
985 let px = col_x[pcol];
986 let py = row_y[prow];
987
988 let panel_rect = crate::render::Rect {
989 x: px,
990 y: py,
991 width: panel_width,
992 height: panel_height,
993 };
994 backend.clear_corner_claims();
1002
1003 let mut bottom_strip = 0.0_f64;
1008 let mut left_strip = 0.0_f64;
1009 let mut bottom_title = 0.0_f64;
1010 let mut left_title = 0.0_f64;
1011 for (side, label, t) in &strips[pi] {
1012 let o = off(*side, pi, prow, pcol);
1013 let (rect, angle) = match side {
1014 Side::Top => ((px, py - t, panel_width, *t), 0.0),
1015 Side::Bottom => {
1016 if o > 0.0 {
1017 bottom_title = *t + o;
1018 } else {
1019 bottom_strip = *t;
1020 }
1021 ((px, py + panel_height + o, panel_width, *t), 0.0)
1022 }
1023 Side::Left => {
1024 if o > 0.0 {
1025 left_title = *t + o;
1026 } else {
1027 left_strip = *t;
1028 }
1029 ((px - t - o, py, *t, panel_height), 270.0)
1030 }
1031 Side::Right => ((px + panel_width, py, *t, panel_height), 90.0),
1032 };
1033 draw_strip(backend, theme, rect, label, angle)?;
1034 }
1035
1036 if theme.panel_background.visible {
1038 if let Some(fill) = theme.panel_background.fill {
1039 backend.set_element_class(Some("gg-panel-background"));
1040 backend.draw_rect(
1041 (panel_rect.x, panel_rect.y),
1042 (
1043 panel_rect.x + panel_rect.width,
1044 panel_rect.y + panel_rect.height,
1045 ),
1046 &RectStyle {
1047 fill: Some(fill),
1048 stroke: theme.panel_background.color,
1049 stroke_width: theme.panel_background.width,
1050 alpha: 1.0,
1051 clip: false,
1052 corner_radius: 0.0,
1053 },
1054 )?;
1055 }
1056 }
1057
1058 if theme.panel_border.visible {
1060 let style = LineStyle {
1061 color: theme.panel_border.color,
1062 width: theme.panel_border.width,
1063 alpha: 1.0,
1064 linetype: Linetype::Solid,
1065 ..Default::default()
1066 };
1067 let x0 = panel_rect.x;
1068 let y0 = panel_rect.y;
1069 let x1 = panel_rect.x + panel_rect.width;
1070 let y1 = panel_rect.y + panel_rect.height;
1071 backend.set_element_class(Some("gg-panel-border"));
1072 backend.draw_line(&[(x0, y0), (x1, y0)], &style)?;
1073 backend.draw_line(&[(x1, y0), (x1, y1)], &style)?;
1074 backend.draw_line(&[(x1, y1), (x0, y1)], &style)?;
1075 backend.draw_line(&[(x0, y1), (x0, y0)], &style)?;
1076 }
1077
1078 let panel_scale_set = if pi < built.panel_scales.len() {
1080 &built.panel_scales[pi]
1081 } else {
1082 &built.scales
1083 };
1084
1085 let x_scale = panel_scale_set.get(&h_aes);
1087 let y_scale = panel_scale_set.get(&v_aes);
1088
1089 if let (true, Some(xs), Some(ys)) = (
1090 built.coord.is_polar() && !built.coord.is_radar(),
1091 x_scale,
1092 y_scale,
1093 ) {
1094 crate::guide::polar::draw_polar_guides(
1096 xs,
1097 ys,
1098 built.coord.as_ref(),
1099 theme,
1100 &panel_rect,
1101 backend,
1102 )?;
1103 } else if let (Some(xs), Some(ys)) = (x_scale, y_scale) {
1104 if built.coord.gridlines() {
1105 axis::draw_gridlines(
1106 xs,
1107 ys,
1108 built.coord.as_ref(),
1109 theme,
1110 &panel_rect,
1111 backend,
1112 )?;
1113 }
1114
1115 let bottom_edge = prow == nrow - 1 || pi + ncol >= built.panels.len();
1119 if bottom_edge || all_x {
1120 let axis_rect = crate::render::Rect {
1121 height: panel_rect.height + bottom_strip,
1122 ..panel_rect.clone()
1123 };
1124 let t = if bottom_edge || inner_labels_x {
1125 theme
1126 } else {
1127 &theme_no_x_labels
1128 };
1129 axis::draw_x_axis_with(
1130 xs,
1131 built.coord.as_ref(),
1132 t,
1133 &axis_rect,
1134 &total_area,
1135 false,
1136 backend,
1137 )?;
1138 if bottom_edge {
1139 let title_rect = crate::render::Rect {
1140 height: axis_rect.height + bottom_title,
1141 ..axis_rect.clone()
1142 };
1143 x_title_area = Some(union(&x_title_area, &title_rect));
1144 }
1145 }
1146
1147 if pcol == 0 || all_y {
1149 let axis_rect = crate::render::Rect {
1150 x: panel_rect.x - left_strip,
1151 width: panel_rect.width + left_strip,
1152 ..panel_rect.clone()
1153 };
1154 let t = if pcol == 0 || inner_labels_y {
1155 theme
1156 } else {
1157 &theme_no_y_labels
1158 };
1159 axis::draw_y_axis_with(
1160 ys,
1161 built.coord.as_ref(),
1162 t,
1163 &axis_rect,
1164 false,
1165 backend,
1166 )?;
1167 if pcol == 0 {
1168 let reserve = axis::y_label_reserve(theme, &ys.breaks());
1169 let prev = y_title_area.as_ref().map(|(r, _)| r.clone());
1170 let widest = y_title_area.as_ref().map_or(0.0, |(_, w)| *w);
1171 let title_rect = crate::render::Rect {
1172 x: axis_rect.x - left_title,
1173 width: axis_rect.width + left_title,
1174 ..axis_rect.clone()
1175 };
1176 y_title_area = Some((union(&prev, &title_rect), widest.max(reserve)));
1177 }
1178 }
1179 }
1180
1181 if fixed_grid.is_some() {
1185 let data = built
1186 .coord
1187 .data_rect(&panel_rect)
1188 .unwrap_or_else(|| panel_rect.clone());
1189 backend.begin_panel(pi, &panel.label, &panel_rect, &data);
1190 }
1191 backend.set_element_class(None);
1195 let clip_group = built.clip
1196 && fixed_grid.is_none()
1197 && built.panels_data.get(pi).is_some_and(|layers| {
1198 layers.iter().any(|d| {
1199 layer_spills(d, panel_scale_set, built.coord.as_ref(), &panel_rect)
1200 })
1201 });
1202 if clip_group {
1203 backend.begin_clip(&panel_rect);
1204 }
1205 if !built.clip {
1206 backend.set_clipping(false);
1207 }
1208 if pi < built.panels_data.len() {
1209 for (li, layer_data) in built.panels_data[pi].iter().enumerate() {
1210 if li < built.layers.len() && layer_data.nrows() > 0 && !is_figure(li) {
1211 let mut panel_backend = PanelBackendAdapter {
1212 inner: backend,
1213 panel_rect: panel_rect.clone(),
1214 };
1215 let geom = &built.layers[li].geom;
1216 panel_backend.set_mark_geom(Some(geom.name()));
1217 let drawn = geom.draw(
1218 layer_data,
1219 built.coord.as_ref(),
1220 panel_scale_set,
1221 theme,
1222 &mut panel_backend,
1223 );
1224 panel_backend.set_mark_geom(None);
1225 drawn?;
1226 }
1227 }
1228 }
1229 if !built.clip {
1230 backend.set_clipping(true);
1231 }
1232 if clip_group {
1233 backend.end_clip();
1234 }
1235 if fixed_grid.is_some() {
1236 backend.end_panel();
1237 }
1238 }
1239
1240 let title_scales = built.panel_scales.first().unwrap_or(&built.scales);
1243 if let (Some(area), Some(xs)) = (&x_title_area, title_scales.get(&h_aes)) {
1244 axis::draw_x_axis_title(xs, theme, area, backend)?;
1245 }
1246 if let (Some((area, reserve)), Some(ys)) = (&y_title_area, title_scales.get(&v_aes)) {
1247 axis::draw_y_axis_title(ys, theme, area, *reserve, backend)?;
1248 }
1249
1250 if band_h > 0.0 {
1252 backend.clear_corner_claims();
1253 for li in (0..built.layers.len()).filter(|&li| is_figure(li)) {
1254 let empty = crate::data::DataFrame::new();
1255 let data = built
1256 .panels_data
1257 .iter()
1258 .filter_map(|p| p.get(li))
1259 .find(|d| d.nrows() > 0)
1260 .unwrap_or(&empty);
1261 let mut band_backend = PanelBackendAdapter {
1262 inner: backend,
1263 panel_rect: band_rect.clone(),
1264 };
1265 let geom = &built.layers[li].geom;
1266 band_backend.set_mark_geom(Some(geom.name()));
1267 let drawn = geom.draw(
1268 data,
1269 built.coord.as_ref(),
1270 &built.scales,
1271 theme,
1272 &mut band_backend,
1273 );
1274 band_backend.set_mark_geom(None);
1275 drawn?;
1276 }
1277 }
1278
1279 let title_ref = Self::title_ref_rect(theme, &plot_area, &total_area);
1281 let caption_ref = Self::ref_rect(
1282 theme.caption_position.unwrap_or(theme.title_position),
1283 theme,
1284 &plot_area,
1285 &total_area,
1286 );
1287 let legend_lift = legend::top_legend_lift(
1290 theme,
1291 &built.scales,
1292 &built.suppressed_aes,
1293 &built.legend_plans,
1294 &built.guide_legend,
1295 );
1296 if let Some(ref title) = built.labels.title {
1297 let (tx, anchor) = Self::hjust_pos(&theme.title, &title_ref);
1298 let (title_y, _) = Self::title_subtitle_y(
1299 theme,
1300 plot_area.y,
1301 legend_lift,
1302 built.labels.subtitle.is_some(),
1303 );
1304 let family = if theme.title.family.is_empty() {
1305 None
1306 } else {
1307 Some(theme.title.family.clone())
1308 };
1309 backend.set_element_class(Some("gg-title"));
1310 crate::render::rich::draw(
1311 backend,
1312 theme.rich_text,
1313 title,
1314 (tx, title_y),
1315 &TextStyle {
1316 color: theme.title.color,
1317 size: theme.title.size,
1318 anchor,
1319 angle: 0.0,
1320 family,
1321 face: theme.title.face,
1322 bg_colour: None,
1323 bg_r: 0.0,
1324 },
1325 )?;
1326 }
1327
1328 if let Some(ref subtitle) = built.labels.subtitle {
1330 let (sx, anchor) = Self::hjust_pos(&theme.subtitle, &title_ref);
1331 let (_, subtitle_y) = Self::title_subtitle_y(theme, plot_area.y, legend_lift, true);
1332 let family = if theme.subtitle.family.is_empty() {
1333 None
1334 } else {
1335 Some(theme.subtitle.family.clone())
1336 };
1337 backend.set_element_class(Some("gg-subtitle"));
1338 crate::render::rich::draw(
1339 backend,
1340 theme.rich_text,
1341 subtitle,
1342 (sx, subtitle_y),
1343 &TextStyle {
1344 color: theme.subtitle.color,
1345 size: theme.subtitle.size,
1346 anchor,
1347 angle: 0.0,
1348 family,
1349 face: theme.subtitle.face,
1350 bg_colour: None,
1351 bg_r: 0.0,
1352 },
1353 )?;
1354 }
1355
1356 if let Some(ref caption) = built.labels.caption {
1358 let (cx, anchor) = Self::hjust_pos(&theme.caption, &caption_ref);
1359 let caption_y = total_area.y + total_area.height
1362 - theme.plot_margin.bottom.max(0.0)
1363 - theme.caption.size * 0.5;
1364 let family = if theme.caption.family.is_empty() {
1365 None
1366 } else {
1367 Some(theme.caption.family.clone())
1368 };
1369 backend.set_element_class(Some("gg-caption"));
1370 crate::render::rich::draw(
1371 backend,
1372 theme.rich_text,
1373 caption,
1374 (cx, caption_y),
1375 &TextStyle {
1376 color: theme.caption.color,
1377 size: theme.caption.size,
1378 anchor,
1379 angle: 0.0,
1380 family,
1381 face: theme.caption.face,
1382 bg_colour: None,
1383 bg_r: 0.0,
1384 },
1385 )?;
1386 }
1387
1388 backend.set_element_class(None);
1389 Self::draw_annotations(
1391 &built.annotations,
1392 &built.scales,
1393 built.coord.as_ref(),
1394 &plot_area,
1395 theme,
1396 backend,
1397 )?;
1398
1399 legend::draw_legend_planned(
1401 &built.scales,
1402 theme,
1403 &plot_area,
1404 plot_area.width,
1405 backend,
1406 &built.guide_legend,
1407 &built.suppressed_aes,
1408 &built.legend_plans,
1409 )?;
1410
1411 let tag_area = if theme.tag_location_panel {
1415 &plot_area
1416 } else {
1417 &total_area
1418 };
1419 Self::draw_tag(&built.labels, theme, tag_area, backend)?;
1420
1421 Ok(())
1422 }
1423
1424 fn draw_annotations(
1439 annotations: &[Annotation],
1440 scales: &crate::scale::ScaleSet,
1441 coord: &dyn crate::coord::Coord,
1442 plot_area: &crate::render::Rect,
1443 theme: &crate::theme::Theme,
1444 backend: &mut dyn DrawBackend,
1445 ) -> Result<(), RenderError> {
1446 use crate::data::Value;
1447
1448 let x_scale = scales.get(&Aesthetic::X);
1449 let y_scale = scales.get(&Aesthetic::Y);
1450
1451 for ann in annotations {
1452 match ann {
1453 Annotation::Text {
1454 label,
1455 x,
1456 y,
1457 size,
1458 color,
1459 } => {
1460 let nx = x_scale.map(|s| s.map(&Value::Float(*x))).unwrap_or(0.0);
1461 let ny = y_scale.map(|s| s.map(&Value::Float(*y))).unwrap_or(0.0);
1462 let pos = coord.transform((nx, ny), plot_area);
1463 backend.draw_text(
1464 label,
1465 pos,
1466 &TextStyle {
1467 color: annotation_ink(*color, theme),
1468 size: *size,
1469 anchor: TextAnchor::Middle,
1470 angle: 0.0,
1471 family: crate::geom::resolve_font_family("", theme),
1472 face: crate::render::backend::FontFace::Plain,
1473 bg_colour: None,
1474 bg_r: 0.0,
1475 },
1476 )?;
1477 }
1478 Annotation::Rect {
1479 xmin,
1480 xmax,
1481 ymin,
1482 ymax,
1483 fill,
1484 alpha,
1485 } => {
1486 let nx0 = x_scale.map(|s| s.map(&Value::Float(*xmin))).unwrap_or(0.0);
1487 let nx1 = x_scale.map(|s| s.map(&Value::Float(*xmax))).unwrap_or(1.0);
1488 let ny0 = y_scale.map(|s| s.map(&Value::Float(*ymin))).unwrap_or(0.0);
1489 let ny1 = y_scale.map(|s| s.map(&Value::Float(*ymax))).unwrap_or(1.0);
1490 let tl = coord.transform((nx0, ny1), plot_area);
1491 let br = coord.transform((nx1, ny0), plot_area);
1492 backend.draw_rect(
1493 tl,
1494 br,
1495 &RectStyle {
1496 fill: Some(*fill),
1497 stroke: None,
1498 stroke_width: 0.0,
1499 alpha: *alpha,
1500 clip: false,
1501 corner_radius: 0.0,
1502 },
1503 )?;
1504 }
1505 Annotation::Segment {
1506 x,
1507 y,
1508 xend,
1509 yend,
1510 color,
1511 width,
1512 } => {
1513 let nx0 = x_scale.map(|s| s.map(&Value::Float(*x))).unwrap_or(0.0);
1514 let ny0 = y_scale.map(|s| s.map(&Value::Float(*y))).unwrap_or(0.0);
1515 let nx1 = x_scale.map(|s| s.map(&Value::Float(*xend))).unwrap_or(1.0);
1516 let ny1 = y_scale.map(|s| s.map(&Value::Float(*yend))).unwrap_or(1.0);
1517 let p0 = coord.transform((nx0, ny0), plot_area);
1518 let p1 = coord.transform((nx1, ny1), plot_area);
1519 backend.draw_line(
1520 &[p0, p1],
1521 &LineStyle {
1522 color: annotation_ink(*color, theme),
1523 alpha: 1.0,
1524 width: *width,
1525 linetype: Linetype::Solid,
1526 ..Default::default()
1527 },
1528 )?;
1529 }
1530 Annotation::LogTicks {
1531 sides,
1532 outside,
1533 lengths,
1534 color,
1535 width,
1536 } => {
1537 let style = LineStyle {
1538 color: annotation_ink(*color, theme),
1539 alpha: 1.0,
1540 width: *width,
1541 linetype: Linetype::Solid,
1542 ..Default::default()
1543 };
1544 let dir = if *outside { -1.0 } else { 1.0 };
1545 for side in sides.chars() {
1546 let horizontal = matches!(side, 'b' | 't');
1547 let scale = if horizontal { x_scale } else { y_scale };
1548 let Some((lo, hi)) = scale.and_then(|s| s.expanded_domain()) else {
1549 continue;
1550 };
1551 for (t, kind) in log_ticks(lo, hi) {
1552 let n = scale.map(|s| s.map(&Value::Float(t))).unwrap_or(0.0);
1553 let len = dir
1554 * match kind {
1555 0 => lengths.2,
1556 1 => lengths.1,
1557 _ => lengths.0,
1558 };
1559 let (edge, step) = match side {
1561 'b' => ((n, 0.0), (0.0, -len)),
1562 't' => ((n, 1.0), (0.0, len)),
1563 'l' => ((0.0, n), (len, 0.0)),
1564 'r' => ((1.0, n), (-len, 0.0)),
1565 _ => continue,
1566 };
1567 let p0 = coord.transform(edge, plot_area);
1568 let p1 = (p0.0 + step.0, p0.1 + step.1);
1569 backend.draw_line(&[p0, p1], &style)?;
1570 }
1571 }
1572 }
1573 Annotation::Raster {
1574 image,
1575 xmin,
1576 xmax,
1577 ymin,
1578 ymax,
1579 alpha,
1580 } => {
1581 let rect = data_rect(
1582 x_scale,
1583 y_scale,
1584 coord,
1585 plot_area,
1586 [*xmin, *xmax, *ymin, *ymax],
1587 );
1588 backend.draw_image(image, &rect, plot_area, *alpha)?;
1589 }
1590 Annotation::Inset {
1591 plot,
1592 xmin,
1593 xmax,
1594 ymin,
1595 ymax,
1596 } => {
1597 let rect = data_rect(
1598 x_scale,
1599 y_scale,
1600 coord,
1601 plot_area,
1602 [*xmin, *xmax, *ymin, *ymax],
1603 );
1604 let (w, h) = (rect.width.round().max(1.0), rect.height.round().max(1.0));
1605 let mut guard = plot.0.lock().unwrap_or_else(|e| e.into_inner());
1606 match &mut *guard {
1607 Ok((built, meta)) => {
1608 let layout =
1609 crate::GGPlot::layout_built(built, meta, w as u32, h as u32);
1610 let mut off = crate::render::offset::OffsetBackend::new(
1611 backend,
1612 rect.x,
1613 rect.y,
1614 layout.plot_area.clone(),
1615 layout.total.clone(),
1616 );
1617 Self::render(built, &mut off)?;
1618 }
1619 Err(e) => {
1620 backend.warn(format!("annotation_custom: inset plot failed: {e}"))
1621 }
1622 }
1623 }
1624 }
1625 }
1626 Ok(())
1627 }
1628}
1629
1630fn draw_strip(
1636 backend: &mut dyn DrawBackend,
1637 theme: &crate::theme::Theme,
1638 (x, y, w, h): (f64, f64, f64, f64),
1639 label: &str,
1640 angle: f64,
1641) -> Result<(), RenderError> {
1642 let horizontal = angle == 0.0;
1644 let (bg, text) = if horizontal {
1645 (&theme.strip_background_x, &theme.strip_text_x)
1646 } else {
1647 (&theme.strip_background_y, &theme.strip_text_y)
1648 };
1649 let bg = bg.as_ref().unwrap_or(&theme.strip_background);
1650 let text = text.as_ref().unwrap_or(&theme.strip_text);
1651 if bg.visible {
1652 backend.set_element_class(Some("gg-strip gg-strip-background"));
1653 backend.draw_rect(
1654 (x, y),
1655 (x + w, y + h),
1656 &RectStyle {
1657 fill: bg.fill,
1658 stroke: bg.color,
1659 stroke_width: bg.width,
1660 alpha: 1.0,
1661 clip: false,
1662 corner_radius: 0.0,
1663 },
1664 )?;
1665 }
1666 if !text.visible {
1667 return Ok(());
1668 }
1669 let family = if text.family.is_empty() {
1670 None
1671 } else {
1672 Some(text.family.clone())
1673 };
1674 let lines: Vec<&str> = label.lines().collect();
1675 let n = lines.len().max(1) as f64;
1676 for (k, line) in lines.iter().enumerate() {
1677 let d = (k as f64 - (n - 1.0) / 2.0) * text.size * 1.2;
1678 let (dx, dy) = if angle == 90.0 {
1681 (-d, 0.0)
1682 } else if angle == 270.0 {
1683 (d, 0.0)
1684 } else {
1685 (0.0, d)
1686 };
1687 backend.set_element_class(Some("gg-strip gg-strip-text"));
1688 crate::render::rich::draw(
1689 backend,
1690 theme.rich_text,
1691 line,
1692 (x + w / 2.0 + dx, y + h / 2.0 + dy),
1693 &TextStyle {
1694 color: text.color,
1695 size: text.size,
1696 anchor: TextAnchor::Middle,
1697 angle,
1698 family: family.clone(),
1699 face: text.face,
1700 bg_colour: None,
1701 bg_r: 0.0,
1702 },
1703 )?;
1704 }
1705 Ok(())
1706}
1707
1708fn log_ticks(lo: f64, hi: f64) -> Vec<(f64, u8)> {
1709 let mut out = Vec::new();
1710 if !(lo.is_finite() && hi.is_finite()) || hi - lo > 300.0 {
1711 return out;
1712 }
1713 for k in (lo.floor() as i64)..=(hi.ceil() as i64) {
1714 for m in 1..=9 {
1715 let t = k as f64 + (m as f64).log10();
1716 if t >= lo - 1e-9 && t <= hi + 1e-9 {
1717 out.push((
1718 t,
1719 if m == 1 {
1720 0
1721 } else if m == 5 {
1722 1
1723 } else {
1724 2
1725 },
1726 ));
1727 }
1728 }
1729 }
1730 out
1731}
1732
1733fn data_rect(
1736 x_scale: Option<&dyn crate::scale::Scale>,
1737 y_scale: Option<&dyn crate::scale::Scale>,
1738 coord: &dyn crate::coord::Coord,
1739 plot_area: &crate::render::Rect,
1740 [xmin, xmax, ymin, ymax]: [f64; 4],
1741) -> crate::render::Rect {
1742 use crate::data::Value;
1743 let m = |s: Option<&dyn crate::scale::Scale>, v: f64, edge: f64| {
1744 if v.is_finite() {
1745 s.map(|s| s.map(&Value::Float(v))).unwrap_or(edge)
1746 } else if v > 0.0 {
1747 1.0
1748 } else {
1749 0.0
1750 }
1751 };
1752 let a = coord.transform((m(x_scale, xmin, 0.0), m(y_scale, ymax, 1.0)), plot_area);
1753 let b = coord.transform((m(x_scale, xmax, 1.0), m(y_scale, ymin, 0.0)), plot_area);
1754 crate::render::Rect {
1755 x: a.0.min(b.0),
1756 y: a.1.min(b.1),
1757 width: (a.0 - b.0).abs(),
1758 height: (a.1 - b.1).abs(),
1759 }
1760}
1761
1762fn annotation_ink(color: (u8, u8, u8), theme: &crate::theme::Theme) -> (u8, u8, u8) {
1768 match (color == (50, 50, 50), theme.geom.ink) {
1769 (true, Some(ink)) => ink,
1770 _ => color,
1771 }
1772}
1773
1774fn layer_spills(
1779 data: &crate::data::DataFrame,
1780 scales: &crate::scale::ScaleSet,
1781 coord: &dyn crate::coord::Coord,
1782 area: &crate::render::Rect,
1783) -> bool {
1784 if coord.is_polar() || data.nrows() == 0 {
1785 return false;
1786 }
1787 const SLACK: f64 = 0.5;
1788 let outside = |(px, py): (f64, f64)| {
1789 px < area.x - SLACK
1790 || px > area.x + area.width + SLACK
1791 || py < area.y - SLACK
1792 || py > area.y + area.height + SLACK
1793 };
1794 let axes = [
1795 (Aesthetic::X, ["x", "xmin", "xmax", "xend"], true),
1796 (Aesthetic::Y, ["y", "ymin", "ymax", "yend"], false),
1797 ];
1798 for (aes, cols, is_x) in axes {
1799 let Some(scale) = scales.get(&aes) else {
1800 continue;
1801 };
1802 for col in cols {
1803 let Some(values) = data.column(col) else {
1804 continue;
1805 };
1806 for v in values {
1807 if !v.as_f64().is_some_and(f64::is_finite) {
1808 continue;
1809 }
1810 let n = scale.map(v);
1811 if !n.is_finite() {
1812 continue;
1813 }
1814 let p = if is_x { (n, 0.5) } else { (0.5, n) };
1815 if outside(coord.transform(p, area)) {
1816 return true;
1817 }
1818 }
1819 }
1820 }
1821 false
1822}
1823
1824struct PanelBackendAdapter<'a> {
1826 inner: &'a mut dyn DrawBackend,
1827 panel_rect: crate::render::Rect,
1828}
1829
1830impl<'a> DrawBackend for PanelBackendAdapter<'a> {
1831 fn set_clipping(&mut self, on: bool) {
1832 self.inner.set_clipping(on)
1833 }
1834 fn begin_clip(&mut self, rect: &crate::render::Rect) {
1835 self.inner.begin_clip(rect)
1836 }
1837 fn enable_element_classes(&mut self, on: bool) {
1838 self.inner.enable_element_classes(on)
1839 }
1840 fn draw_rich_text(
1841 &mut self,
1842 runs: &[crate::render::rich::RichRun],
1843 pos: (f64, f64),
1844 style: &crate::render::backend::TextStyle,
1845 ) -> Result<(), RenderError> {
1846 self.inner.draw_rich_text(runs, pos, style)
1847 }
1848 fn set_element_class(&mut self, class: Option<&'static str>) {
1849 self.inner.set_element_class(class)
1850 }
1851 fn end_clip(&mut self) {
1852 self.inner.end_clip()
1853 }
1854 fn draw_image(
1855 &mut self,
1856 bytes: &[u8],
1857 rect: &crate::render::Rect,
1858 clip: &crate::render::Rect,
1859 alpha: f64,
1860 ) -> Result<(), RenderError> {
1861 self.inner.draw_image(bytes, rect, clip, alpha)
1862 }
1863 fn draw_circle(
1864 &mut self,
1865 center: (f64, f64),
1866 radius: f64,
1867 style: &crate::render::backend::PointStyle,
1868 ) -> Result<(), RenderError> {
1869 self.inner.draw_circle(center, radius, style)
1870 }
1871 fn draw_line(
1872 &mut self,
1873 points: &[(f64, f64)],
1874 style: &crate::render::backend::LineStyle,
1875 ) -> Result<(), RenderError> {
1876 self.inner.draw_line(points, style)
1877 }
1878 fn draw_quadratic(
1879 &mut self,
1880 p0: (f64, f64),
1881 ctrl: (f64, f64),
1882 p1: (f64, f64),
1883 style: &crate::render::backend::LineStyle,
1884 ) -> Result<(), RenderError> {
1885 self.inner.draw_quadratic(p0, ctrl, p1, style)
1886 }
1887 fn draw_rect(
1888 &mut self,
1889 top_left: (f64, f64),
1890 bottom_right: (f64, f64),
1891 style: &RectStyle,
1892 ) -> Result<(), RenderError> {
1893 self.inner.draw_rect(top_left, bottom_right, style)
1894 }
1895 fn draw_text(
1896 &mut self,
1897 text: &str,
1898 pos: (f64, f64),
1899 style: &TextStyle,
1900 ) -> Result<(), RenderError> {
1901 self.inner.draw_text(text, pos, style)
1902 }
1903 fn draw_polygon(
1904 &mut self,
1905 points: &[(f64, f64)],
1906 style: &RectStyle,
1907 ) -> Result<(), RenderError> {
1908 self.inner.draw_polygon(points, style)
1909 }
1910 fn draw_polygon_rings(
1911 &mut self,
1912 rings: &[Vec<(f64, f64)>],
1913 style: &RectStyle,
1914 ) -> Result<(), RenderError> {
1915 self.inner.draw_polygon_rings(rings, style)
1916 }
1917 fn draw_shape(
1918 &mut self,
1919 center: (f64, f64),
1920 radius: f64,
1921 style: &crate::render::backend::PointStyle,
1922 ) -> Result<(), RenderError> {
1923 self.inner.draw_shape(center, radius, style)
1924 }
1925 fn plot_area(&self) -> crate::render::Rect {
1926 self.panel_rect.clone()
1927 }
1928 fn set_tooltip(&mut self, tooltip: Option<String>) {
1929 self.inner.set_tooltip(tooltip)
1930 }
1931 fn set_mark_axis(&mut self, key: Option<String>) {
1932 self.inner.set_mark_axis(key)
1933 }
1934 fn set_mark_series(&mut self, series: Option<String>) {
1935 self.inner.set_mark_series(series)
1936 }
1937 fn set_mark_value(&mut self, value: Option<String>) {
1938 self.inner.set_mark_value(value)
1939 }
1940 fn set_mark_geom(&mut self, geom: Option<&str>) {
1941 self.inner.set_mark_geom(geom)
1942 }
1943 fn warn(&mut self, message: String) {
1944 self.inner.warn(message)
1945 }
1946 fn set_mark_part(&mut self, part: Option<&str>) {
1947 self.inner.set_mark_part(part)
1948 }
1949 fn set_mark_attrs(&mut self, attrs: Vec<(String, String)>) {
1950 self.inner.set_mark_attrs(attrs)
1951 }
1952
1953 fn set_mark_class(&mut self, class: Option<String>) {
1954 self.inner.set_mark_class(class)
1955 }
1956
1957 fn set_mark_group(&mut self, group: Option<(String, String)>) {
1958 self.inner.set_mark_group(group)
1959 }
1960
1961 fn set_layer_attrs(&mut self, attrs: Vec<(String, String)>) {
1962 self.inner.set_layer_attrs(attrs)
1963 }
1964 fn wants_formatted_values(&self) -> bool {
1965 self.inner.wants_formatted_values()
1966 }
1967 fn set_mark_fvalue(&mut self, value: Option<String>) {
1968 self.inner.set_mark_fvalue(value)
1969 }
1970 fn set_mark_fx(&mut self, value: Option<String>) {
1971 self.inner.set_mark_fx(value)
1972 }
1973 fn total_area(&self) -> crate::render::Rect {
1974 self.inner.total_area()
1975 }
1976 fn corner_claims(&self) -> Vec<crate::render::Rect> {
1977 self.inner.corner_claims()
1978 }
1979 fn claim_corner_box(&mut self, rect: crate::render::Rect) {
1980 self.inner.claim_corner_box(rect)
1981 }
1982 fn clear_corner_claims(&mut self) {
1983 self.inner.clear_corner_claims()
1984 }
1985}
1986
1987#[cfg(test)]
1988mod tests {
1989 use super::*;
1990 use crate::render::backend::LineStyle;
1991 use crate::render::svg_backend::SvgBackend;
1992
1993 #[test]
1999 fn panel_backend_adapter_forwards_quadratic_and_mark_metadata() {
2000 let total = crate::render::Rect {
2001 x: 0.0,
2002 y: 0.0,
2003 width: 200.0,
2004 height: 200.0,
2005 };
2006 let panel_rect = crate::render::Rect {
2007 x: 10.0,
2008 y: 10.0,
2009 width: 80.0,
2010 height: 80.0,
2011 };
2012 let mut backend = SvgBackend::new(200, 200, total);
2013 let mut adapter = PanelBackendAdapter {
2014 inner: &mut backend,
2015 panel_rect: panel_rect.clone(),
2016 };
2017
2018 assert_eq!(adapter.plot_area().x, panel_rect.x);
2019 assert_eq!(adapter.plot_area().width, panel_rect.width);
2020
2021 adapter.set_mark_part(Some("arrow"));
2022 adapter.set_mark_attrs(vec![("data-x".to_string(), "v".to_string())]);
2023 adapter
2024 .draw_quadratic((0.0, 0.0), (5.0, 10.0), (10.0, 0.0), &LineStyle::default())
2025 .unwrap();
2026 adapter.set_mark_part(None);
2027 adapter.set_mark_attrs(Vec::new());
2028
2029 let svg = backend.finish();
2030 assert!(svg.contains("<path"));
2031 assert!(svg.contains("data-part=\"arrow\""));
2032 assert!(svg.contains("data-x=\"v\""));
2033 }
2034}
2035
2036#[cfg(test)]
2037mod zoom_clip_tests {
2038 use crate::prelude::*;
2039
2040 fn data() -> Vec<(String, Vec<Value>)> {
2041 let f = |v: &[f64]| v.iter().map(|&x| Value::Float(x)).collect::<Vec<_>>();
2042 vec![
2043 ("x".into(), f(&[1.0, 2.0, 3.0, 4.0])),
2044 ("y".into(), f(&[0.0, 0.1, 0.5, 1.0])),
2045 ("lo".into(), f(&[0.0, 0.05, 0.3, 0.8])),
2046 ("hi".into(), f(&[0.0, 0.2, 0.7, 1.0])),
2047 ("g".into(), vec![Value::Str("a".into()); 4]),
2048 ]
2049 }
2050
2051 #[test]
2053 fn a_zoom_clips_layers_to_the_panel() {
2054 for facet in [false, true] {
2055 let mut p = GGPlot::new(data())
2056 .aes(Aes::new().x("x").y("y").ymin("lo").ymax("hi"))
2057 .geom_ribbon()
2058 .geom_line()
2059 .coord_cartesian_zoom(None, Some((0.0, 0.2)));
2060 if facet {
2061 p = p.facet_wrap("g", None);
2062 }
2063 let svg = p.render_svg_native_at(0.0, 0.0, 400, 300).unwrap();
2064 assert!(
2065 svg.contains("clip-path=\"url("),
2066 "facet={facet}: no clip group"
2067 );
2068 }
2069 }
2070}