1use crate::layout::Layout;
4use crate::significance::SignificancePlan;
5use crate::{NumericFormat, NumericValues};
6
7mod bar;
8mod categorical;
9mod estimate;
10mod facet;
11mod output;
12pub(crate) mod ticks;
13
14pub use bar::{
15 BarInput, BarSamples, Bootstrap, ConfidenceInterval, ErrorBar, PercentileInterval,
16 StandardDeviation, StandardError,
17};
18pub(crate) use bar::{BarSource, ConfidenceIntervalAlgorithm, ErrorBarKind};
19pub use categorical::{CategoricalColorMap, CategoryOrder, ValueSort};
20pub use estimate::{
21 AxisScale, Bounds, CoefficientInput, EstimateStatus, InteractionStyle, LinePathStyle,
22 LinePattern, PointShape, QqLine, RegressionBand, SignificanceMarkStyle, TextWeight,
23};
24pub use facet::{FacetScales, FacetSpec};
25pub(crate) use output::SVG_CSS_DPI;
26pub use output::{PngCompression, PngOptions, PngSizing};
27pub use ticks::{
28 TickContext, TickGeneration, TickPositions, TickRequirement, TickSingleton, TickSpace,
29};
30mod category_labels;
31pub use category_labels::{CategoryLabelSelection, LabelEndpoints};
32
33#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
35pub enum BarSpacing {
36 #[default]
38 Comfort,
39 Compact,
41}
42
43#[derive(Debug, Clone, Copy, PartialEq, Default)]
45pub enum HistogramBins {
46 #[default]
50 Auto,
51 Count(usize),
54 Width(f64),
58}
59
60#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
62pub enum HistogramStat {
63 #[default]
65 Count,
66 Probability,
68 Density,
70}
71
72#[derive(Debug, Clone)]
74pub enum HistogramKde {
75 Internal,
77 Precomputed {
89 x: NumericValues,
91 y: NumericValues,
93 },
94}
95
96impl PartialEq for HistogramKde {
97 fn eq(&self, other: &Self) -> bool {
98 match (self, other) {
99 (Self::Internal, Self::Internal) => true,
100 (
101 Self::Precomputed { x, y },
102 Self::Precomputed {
103 x: other_x,
104 y: other_y,
105 },
106 ) => {
107 crate::geometry::numeric_equal(x, other_x)
108 && crate::geometry::numeric_equal(y, other_y)
109 }
110 _ => false,
111 }
112 }
113}
114
115#[derive(Debug, Clone, PartialEq, Default)]
117pub enum HistogramComposite {
118 #[default]
120 HistogramOnly,
121 KdeAndRug(HistogramKde),
123}
124
125impl HistogramComposite {
126 pub(crate) const fn is_enabled(&self) -> bool {
127 matches!(self, Self::KdeAndRug(_))
128 }
129}
130
131#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
133pub enum DataAreaCorner {
134 TopLeft,
136 TopRight,
138 BottomLeft,
140 BottomRight,
142}
143
144#[derive(Debug, Clone, PartialEq, Eq)]
146pub struct PlotTextAnnotation {
147 position: crate::TextPosition,
148 text: crate::Text,
149}
150
151impl PlotTextAnnotation {
152 pub fn new(corner: DataAreaCorner, text: impl Into<crate::Text>) -> Result<Self, crate::Error> {
157 Self::at(crate::TextPosition::corner(corner), text)
158 }
159
160 pub fn at(
162 position: crate::TextPosition,
163 text: impl Into<crate::Text>,
164 ) -> Result<Self, crate::Error> {
165 let text = text.into();
166 text.required_source("panel text")?;
167 Ok(Self { position, text })
168 }
169
170 #[must_use]
172 pub const fn position(&self) -> &crate::TextPosition {
173 &self.position
174 }
175
176 #[must_use]
178 pub fn text(&self) -> &str {
179 self.text.as_str()
180 }
181
182 pub(crate) const fn content(&self) -> &crate::Text {
183 &self.text
184 }
185}
186
187#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
193pub enum RawOverlay {
194 #[default]
196 Hidden,
197 Points,
199 Jittered,
202}
203
204impl RawOverlay {
205 #[must_use]
207 pub const fn is_visible(self) -> bool {
208 !matches!(self, Self::Hidden)
209 }
210}
211
212#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
214pub enum HeatmapLayout {
215 #[default]
217 Cartesian,
218 LowerTriangle {
220 diagonal: bool,
222 },
223 UpperTriangle {
225 diagonal: bool,
227 },
228}
229
230#[derive(Debug, Clone, PartialEq, Eq, Default)]
232pub enum HeatmapAnnotations {
233 #[default]
235 Hidden,
236 Values(NumericFormat),
238}
239
240#[derive(Debug, Clone, PartialEq, Eq)]
242pub struct HeatmapNullRowAnnotation {
243 row_label: String,
244 text: crate::Text,
245}
246
247impl HeatmapNullRowAnnotation {
248 pub fn new(
252 row_label: impl Into<String>,
253 text: impl Into<crate::Text>,
254 ) -> Result<Self, crate::Error> {
255 let annotation = Self {
256 row_label: row_label.into(),
257 text: text.into(),
258 };
259 validate_heatmap_annotation_label(&annotation.row_label, "row label")?;
260 annotation
261 .text
262 .required_source("heatmap fully-null row annotation text")?;
263 Ok(annotation)
264 }
265
266 #[must_use]
268 pub fn row_label(&self) -> &str {
269 &self.row_label
270 }
271
272 #[must_use]
274 pub fn text(&self) -> &str {
275 self.text.as_str()
276 }
277
278 pub(crate) const fn content(&self) -> &crate::Text {
279 &self.text
280 }
281}
282
283fn validate_heatmap_annotation_label(value: &str, role: &str) -> Result<(), crate::Error> {
284 if value.is_empty() || value.trim() != value || value.chars().any(char::is_control) {
285 return Err(crate::Error::Data(format!(
286 "heatmap fully-null row annotation {role} must be nonempty, trimmed, and contain no control characters"
287 )));
288 }
289 Ok(())
290}
291
292#[derive(Debug, Clone, PartialEq, Eq)]
311pub struct DumbbellEndpoints {
312 left_label: String,
313 left_color: crate::Color,
314 right_label: String,
315 right_color: crate::Color,
316}
317
318impl DumbbellEndpoints {
319 pub fn new(
321 left_label: impl Into<String>,
322 left_color: crate::Color,
323 right_label: impl Into<String>,
324 right_color: crate::Color,
325 ) -> Result<Self, crate::Error> {
326 let endpoints = Self {
327 left_label: left_label.into(),
328 left_color,
329 right_label: right_label.into(),
330 right_color,
331 };
332 if endpoints.left_label.trim().is_empty() || endpoints.right_label.trim().is_empty() {
333 return Err(crate::Error::Data(
334 "dumbbell endpoint labels must not be empty".into(),
335 ));
336 }
337 if endpoints.left_label.trim() != endpoints.left_label
338 || endpoints.right_label.trim() != endpoints.right_label
339 || endpoints.left_label.chars().any(char::is_control)
340 || endpoints.right_label.chars().any(char::is_control)
341 {
342 return Err(crate::Error::Data(
343 "dumbbell endpoint labels must contain no surrounding whitespace or control characters"
344 .into(),
345 ));
346 }
347 if endpoints.left_label == endpoints.right_label {
348 return Err(crate::Error::Data(
349 "dumbbell endpoint labels must be distinct".into(),
350 ));
351 }
352 Ok(endpoints)
353 }
354
355 #[must_use]
357 pub fn left_label(&self) -> &str {
358 &self.left_label
359 }
360
361 #[must_use]
363 pub const fn left_color(&self) -> crate::Color {
364 self.left_color
365 }
366
367 #[must_use]
369 pub fn right_label(&self) -> &str {
370 &self.right_label
371 }
372
373 #[must_use]
375 pub const fn right_color(&self) -> crate::Color {
376 self.right_color
377 }
378}
379
380#[derive(Debug, Clone, PartialEq, Eq)]
382pub struct WaterfallLabels {
383 base: crate::Text,
384 terminal: crate::Text,
385}
386
387impl WaterfallLabels {
388 pub fn new(
392 base: impl Into<crate::Text>,
393 terminal: impl Into<crate::Text>,
394 ) -> Result<Self, crate::Error> {
395 let labels = Self {
396 base: base.into(),
397 terminal: terminal.into(),
398 };
399 labels.base.required_source("waterfall base label")?;
400 labels
401 .terminal
402 .required_source("waterfall terminal label")?;
403 Ok(labels)
404 }
405
406 #[must_use]
408 pub fn base(&self) -> &str {
409 self.base.as_str()
410 }
411
412 #[must_use]
414 pub fn terminal(&self) -> &str {
415 self.terminal.as_str()
416 }
417
418 pub(crate) const fn contents(&self) -> [&crate::Text; 2] {
419 [&self.base, &self.terminal]
420 }
421}
422
423#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
425pub enum CanvasLegendPolicy {
426 #[default]
428 PerPlot,
429 Shared,
431 Hidden,
433}
434
435#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
442pub enum LegendComposition {
443 #[default]
445 Combined,
446 Separate,
452}
453
454#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
459pub enum LegendPosition {
460 #[default]
462 Auto,
463 InsideTopLeft,
465 InsideTop,
467 InsideTopRight,
469 InsideRightTop,
471 InsideRight,
473 InsideRightBottom,
475 InsideBottomLeft,
477 InsideBottom,
479 InsideBottomRight,
481 InsideLeftTop,
483 InsideLeft,
485 InsideLeftBottom,
487 OutsideRightTop,
489 OutsideRight,
491 OutsideRightBottom,
493 OutsideTopLeft,
495 OutsideTop,
497 OutsideTopRight,
499 OutsideBottomLeft,
501 OutsideBottom,
503 OutsideBottomRight,
505 OutsideLeftTop,
507 OutsideLeft,
509 OutsideLeftBottom,
511}
512
513#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
515pub enum LegendPolicy {
516 #[default]
518 Automatic,
519 Hidden,
521 Visible(LegendPosition),
523}
524
525impl LegendPolicy {
526 pub(crate) const fn position(self) -> LegendPosition {
527 match self {
528 Self::Visible(position) => position,
529 Self::Automatic | Self::Hidden => LegendPosition::Auto,
530 }
531 }
532}
533
534macro_rules! define_plot_kinds {
535 ($($variant:ident => $documentation:literal),+ $(,)?) => {
536 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
538 pub enum PlotKind {
539 $(
540 #[doc = $documentation]
541 $variant,
542 )+
543 }
544 };
545}
546
547define_plot_kinds! {
548 Scatter => "Scatter plot.",
549 Histogram => "Single-series numeric histogram with an optional KDE-and-rug density composite.",
550 Density => "Gaussian kernel density estimate.",
551 Qq => "Quantile-quantile plot against a standard normal distribution.",
552 PointInterval => "Point estimates with explicit lower and upper interval bounds.",
553 Line => "Grouped ordered numeric series with optional precomputed ribbons.",
554 Trajectory => "Explicit-group repeated trajectories with neutral connectors.",
555 LinePath => "Explicit-group numeric paths in source-row order.",
556 Interaction => "Precomputed interaction profiles with explicit bounds and optional closed trace styles.",
557 Coefficient => "Named model coefficients with optional drawable bounds.",
558 Forest => "Complete interval estimates with an explicit scientific null.",
559 Dumbbell => "Horizontal paired endpoint estimates with optional replicate identity.",
560 Heatmap => "Categorical grid with a continuous numeric fill.",
561 Bar => "Bar plot with CI error bars.",
562 HorizontalBar => "Horizontal bar plot.",
563 StackedBar => "Stacked vertical bar plot using one categorical series.",
564 StackedHorizontalBar => "Stacked horizontal bar plot using one categorical series.",
565 Boxplot => "Box-and-whisker plot.",
566 Violin => "Mirrored KDE violins with centered inner summaries.",
567 Raincloud => "One-sided KDE clouds with separated summaries and complete observation strips.",
568 Regression => "Regression plot (scatter + fit line).",
569 Marginal => "Marginal plot (marginal histograms + central scatter).",
570 Matrix => "Scatter matrix (small multiples).",
571 Beeswarm => "Categorical rows of collision-separated points with continuous x and color values.",
572 Waterfall => "Cumulative signed deltas between a base and terminal value.",
573}
574
575impl PlotKind {
576 pub(crate) const fn uses_unified_series(self) -> bool {
577 matches!(
578 self,
579 Self::Bar
580 | Self::HorizontalBar
581 | Self::StackedBar
582 | Self::StackedHorizontalBar
583 | Self::Boxplot
584 | Self::Violin
585 | Self::Raincloud
586 )
587 }
588
589 pub(crate) const fn supports_significance_annotations(self) -> bool {
590 matches!(
591 self,
592 Self::Bar
593 | Self::HorizontalBar
594 | Self::StackedBar
595 | Self::StackedHorizontalBar
596 | Self::Boxplot
597 | Self::Violin
598 | Self::Raincloud
599 | Self::Coefficient
600 )
601 }
602
603 pub(crate) const fn legend_default(self, explicit_y_limits: bool) -> LegendDefault {
604 match self {
605 Self::HorizontalBar | Self::StackedHorizontalBar | Self::Dumbbell => {
606 LegendDefault::TopRight(LegendClearance::HorizontalMaximum)
607 }
608 Self::Bar
609 | Self::StackedBar
610 | Self::Line
611 | Self::Trajectory
612 | Self::LinePath
613 | Self::Interaction
614 | Self::Boxplot
615 | Self::Violin
616 | Self::Raincloud
617 | Self::Regression => LegendDefault::TopRight(LegendClearance::VerticalMaximum),
618 Self::Scatter | Self::Marginal if !explicit_y_limits => {
619 LegendDefault::TopRight(LegendClearance::VerticalMaximum)
620 }
621 Self::Matrix => LegendDefault::SelfManaged,
622 _ => LegendDefault::LowestOverlap,
623 }
624 }
625}
626
627#[derive(Debug, Clone, Copy, PartialEq, Eq)]
628pub(crate) enum LegendDefault {
629 LowestOverlap,
630 TopRight(LegendClearance),
631 SelfManaged,
632}
633
634#[derive(Debug, Clone, Copy, PartialEq, Eq)]
635pub(crate) enum LegendClearance {
636 HorizontalMaximum,
637 VerticalMaximum,
638}
639
640use crate::Error;
641
642pub(crate) struct PlotMeasureContext<'v, 'src> {
645 pub(crate) registered: &'v crate::orchestrator::registration::PlotRegistration<'src>,
646 pub(crate) assignment: crate::orchestrator::assignment::RootPlotAssignmentRef<'v>,
647 pub(crate) canvas: Option<&'src crate::Canvas>,
648 pub(crate) text: &'v crate::text::TextService,
649 pub(crate) operation: &'v crate::font::canonical::OperationContext,
650 pub(crate) intrinsic: &'v crate::orchestrator::root::PlotIntrinsics,
651 pub(crate) guides: crate::decorations::legend::discrete::scoped::GuideConsumption<'v>,
652 pub(crate) fit_scope: &'v crate::layout::fit::FitScope,
653}
654
655impl<'v, 'src> PlotMeasureContext<'v, 'src> {
656 pub(crate) const fn fit_scope(&self) -> &'v crate::layout::fit::FitScope {
657 self.fit_scope
658 }
659
660 pub(crate) const fn intrinsic(&self) -> &'v crate::orchestrator::root::PlotIntrinsics {
661 self.intrinsic
662 }
663
664 pub(crate) fn family(&self) -> Result<crate::orchestrator::registration::FamilyRef<'v>, Error> {
665 crate::layout::interior::InteriorRoute::classify(self.registered.family.kind())
666 .validate(self.registered.source)?;
667 self.registered.family()
668 }
669
670 #[expect(
671 clippy::unnecessary_wraps,
672 reason = "the fixed fallible axis-pair interface projects prepared operands without adding validation"
673 )]
674 pub(crate) fn axis_pair(
675 &self,
676 scope: crate::orchestrator::assignment::AxisPairScope,
677 ) -> Result<crate::orchestrator::assignment::AxisPairRef<'v>, Error> {
678 use crate::layout::AxisSide::{Bottom, Left};
679 use crate::orchestrator::assignment::{AssignedAxisRef, AxisDomainAssignments as D};
680 use crate::orchestrator::assignment::{AxisPairRef, AxisPairScope as S};
681 use crate::orchestrator::registration::{AxisSlot as A, MarginalStrip};
682 let axes = &self.registered.axes;
683 let source = self.registered.source;
684 let pair = match (scope, &self.assignment.local.domains) {
685 (S::Pair, D::Pair(domains)) => {
686 [(A::Pair(Bottom), &domains[0]), (A::Pair(Left), &domains[1])]
687 }
688 (S::MarginalCentral, D::Marginal { central, .. }) => [
689 (A::MarginalCentral(Bottom), ¢ral[0]),
690 (A::MarginalCentral(Left), ¢ral[1]),
691 ],
692 (
693 S::MarginalTop,
694 D::Marginal {
695 central,
696 strip_density,
697 },
698 ) => [
699 (A::MarginalCentral(Bottom), ¢ral[0]),
700 (
701 A::MarginalStripDensity(MarginalStrip::Top),
702 &strip_density[0],
703 ),
704 ],
705 (
706 S::MarginalRight,
707 D::Marginal {
708 central,
709 strip_density,
710 },
711 ) => [
712 (
713 A::MarginalStripDensity(MarginalStrip::Right),
714 &strip_density[1],
715 ),
716 (A::MarginalCentral(Left), ¢ral[1]),
717 ],
718 (S::MatrixCell { row, column }, D::Matrix { variables, .. }) => [
719 (A::MatrixVariable(column), &variables[column]),
720 (A::MatrixVariable(row), &variables[row]),
721 ],
722 (
723 S::MatrixDiagonalDensity { variable },
724 D::Matrix {
725 variables,
726 diagonal_density,
727 },
728 ) => [
729 (A::MatrixVariable(variable), &variables[variable]),
730 (
731 A::MatrixDiagonalDensity(variable),
732 &diagonal_density[variable],
733 ),
734 ],
735 _ => unreachable!("axis pair belongs to the selected interior route"),
736 };
737 Ok(AxisPairRef {
738 axes: pair.map(|(slot, domain)| AssignedAxisRef {
739 base: axes.axis_at(source, slot),
740 domain,
741 }),
742 })
743 }
744
745 pub(crate) fn data(&self) -> Result<crate::data::PlotData<'src, 'v>, Error> {
746 self.registered.data(self.operation)
747 }
748
749 pub(crate) fn request(&self) -> crate::text::TextRequestContext<'v, 'src> {
750 crate::text::TextRequestContext::new(&self.registered.appearance, self.text)
751 }
752
753 #[expect(
754 clippy::unnecessary_wraps,
755 reason = "native measurements share the existing fallible range-reader interface"
756 )]
757 pub(crate) fn axis_range(&self, side: crate::layout::AxisSide) -> Result<(f64, f64), Error> {
758 use crate::orchestrator::assignment::AxisDomainAssignments;
759 let index = usize::from(side == crate::layout::AxisSide::Left);
760 let pair = match &self.assignment.local.domains {
761 AxisDomainAssignments::Pair(pair) => pair,
762 AxisDomainAssignments::Marginal { central, .. } => central,
763 AxisDomainAssignments::Matrix { .. } => {
764 unreachable!("Matrix selects an indexed axis pair")
765 }
766 };
767 Ok(pair[index].extent.pair())
768 }
769
770 pub(crate) fn prepared_category_labels(
771 &self,
772 side: usize,
773 ) -> Option<&'v [crate::layout::AxisTick]> {
774 Some(&self.registered.axes.coordinate()?.categories(side)?.ticks)
775 }
776
777 pub(crate) fn semantic_inputs(
778 &self,
779 scope: crate::orchestrator::assignment::AxisPairScope,
780 ) -> Result<[crate::layout::AxisSemanticInputs; 2], Error> {
781 use crate::orchestrator::assignment::AssignedAxisRef;
782
783 let mut inputs = self
784 .axis_pair(scope)?
785 .axes
786 .map(AssignedAxisRef::semantic_inputs);
787 for (side, input) in inputs.iter_mut().enumerate() {
788 input
789 .text_layout
790 .clone_from(&self.registered.appearance.text_layouts.ticks[side]);
791 }
792 Ok(inputs)
793 }
794}
795
796#[derive(Debug)]
800pub(crate) struct PlotRenderResult {
801 pub(crate) layout: Layout,
802 pub(crate) axes: Option<crate::layout::AxisSystemPlan>,
803 pub(crate) grid_axis_gutters: Option<[f64; 4]>,
804 pub(crate) x_domain: AxisDomain,
805 pub(crate) y_domain: AxisDomain,
806 pub(crate) significance: Option<SignificancePlan>,
807 pub(crate) discrete_guide:
808 Option<std::sync::Arc<crate::decorations::legend::discrete::PreparedGuide>>,
809 pub(crate) decoration_mode: DecorationMode,
810 pub(crate) x_tick_keys: Option<Vec<String>>,
811 pub(crate) y_tick_keys: Option<Vec<String>>,
812 pub(crate) deferred_annotation_text: Vec<crate::layout::DeferredAnnotationTextPlan>,
813 pub(crate) producer_text: Vec<crate::render::backend::PlacedText>,
814 pub(crate) panel_text: Vec<crate::decorations::panel_text::PlotTextAnnotationPlan>,
815 pub(crate) self_managed_legend: Option<std::sync::Arc<crate::decorations::legend::Legend>>,
816 pub(crate) matrix_axes: Option<std::sync::Arc<crate::plots::matrix::MatrixAxisPlan>>,
817 pub(crate) marks: Option<std::sync::Arc<crate::layout::interior::SelectedMarkPlan>>,
818 pub(crate) annotations: Option<std::sync::Arc<crate::layout::interior::SelectedAnnotationPlan>>,
819 pub(crate) numeric_presentation:
820 Option<std::sync::Arc<crate::numeric::set::NumericPresentation>>,
821}
822
823#[derive(Debug, Clone, Copy, PartialEq, Eq)]
825pub(crate) enum AxisDomain {
826 Continuous,
827 Categorical,
828}
829
830#[derive(Debug, Clone, Copy, PartialEq, Eq)]
831pub(crate) enum DecorationMode {
832 Standard,
833 SelfManaged,
834}
835
836impl PlotRenderResult {
837 pub(crate) fn draw_body(
838 &self,
839 backend: &mut dyn crate::render::backend::Backend,
840 ) -> Result<DecorationMode, Error> {
841 self.marks
842 .as_ref()
843 .ok_or_else(|| Error::Render("selected mark payload is missing".into()))?
844 .draw(backend)?;
845 self.annotations
846 .as_ref()
847 .ok_or_else(|| Error::Render("selected annotation payload is missing".into()))?
848 .draw(backend)?;
849 Ok(self.decoration_mode)
850 }
851
852 pub(crate) fn new(
853 layout: Layout,
854 discrete_guide: Option<std::sync::Arc<crate::decorations::legend::discrete::PreparedGuide>>,
855 ) -> Self {
856 Self {
857 layout,
858 axes: None,
859 grid_axis_gutters: None,
860 x_domain: AxisDomain::Continuous,
861 y_domain: AxisDomain::Continuous,
862 significance: None,
863 discrete_guide,
864 decoration_mode: DecorationMode::Standard,
865 x_tick_keys: None,
866 y_tick_keys: None,
867 deferred_annotation_text: Vec::new(),
868 producer_text: Vec::new(),
869 panel_text: Vec::new(),
870 self_managed_legend: None,
871 matrix_axes: None,
872 marks: None,
873 annotations: None,
874 numeric_presentation: None,
875 }
876 }
877
878 pub(crate) fn with_self_managed_decorations(mut self) -> Self {
879 self.decoration_mode = DecorationMode::SelfManaged;
880 self
881 }
882
883 pub(crate) fn with_resolved_axis_keys(
884 mut self,
885 x_keys: Vec<String>,
886 y_keys: Vec<String>,
887 ) -> Self {
888 self.x_tick_keys = Some(x_keys);
889 self.y_tick_keys = Some(y_keys);
890 self
891 }
892}