lichtung_plot/builder/configuration.rs
1use super::Plot;
2use crate::formatting::Labels;
3use crate::input::PlotInput;
4use crate::layers::{BarPointLayer, GuideSpec, PointLayer};
5use crate::layout::AxisTick;
6use crate::spec::{
7 AxisScale, BarSpacing, CategoryOrder, HeatmapAnnotations, HeatmapLayout,
8 HeatmapNullRowAnnotation, HistogramBins, HistogramComposite, HistogramStat, InteractionStyle,
9 LegendPolicy, LinePathStyle, PlotTextAnnotation, QqLine, RawOverlay, RegressionBand,
10 WaterfallLabels,
11};
12use crate::theme::Theme;
13use crate::{
14 data::{Bounds, DataRole, DomainSlot, EstimateStatus, EstimateStatusBinding, SourceRows},
15 elements::Significance,
16 BooleanValues, CategoryValues, NumericFormat, NumericValues,
17};
18
19impl<K: crate::kind::Marker> Plot<K> {
20 /// Set original source-row identities aligned one-to-one with the chart data.
21 #[must_use]
22 pub fn source_rows(mut self, source_rows: SourceRows) -> Self
23 where
24 K: crate::kind::SourceRows,
25 {
26 self.description.payload_mut().source_rows = Some(source_rows);
27 self.description.renew_domain(DomainSlot::Observations);
28 self
29 }
30
31 /// Set categorical color identity independently of graphical grouping.
32 #[must_use]
33 pub fn hue(mut self, values: CategoryValues) -> Self
34 where
35 K: crate::kind::Hue,
36 {
37 self.description.payload_mut().hue = Some(values);
38 self.description.renew_role(DataRole::Hue);
39 self
40 }
41
42 /// Set the graphical-group column used to partition collective marks.
43 #[must_use]
44 pub fn group(mut self, values: CategoryValues) -> Self
45 where
46 K: crate::kind::Group,
47 {
48 self.description.payload_mut().group = Some(values);
49 self.description.renew_role(DataRole::Group);
50 self
51 }
52
53 /// Set one positioned categorical series that owns dodge, color, legend,
54 /// and significance identity where supported.
55 #[must_use]
56 pub fn series(mut self, values: CategoryValues) -> Self
57 where
58 K: crate::kind::Series,
59 {
60 self.description.payload_mut().series = Some(values);
61 self.description.renew_role(DataRole::Series);
62 self
63 }
64
65 /// Set the title shown beside a continuous color scale.
66 /// Content-only replacement preserves earlier Text instructions. Shared guides
67 /// require equal complete title requests, including exact style and layout presence.
68 #[must_use]
69 pub fn color_label(mut self, label: impl Into<crate::Text>) -> Self
70 where
71 K: crate::kind::ContinuousColor,
72 {
73 self.description
74 .payload_mut()
75 .color_label
76 .replace_from(label.into())
77 .expect("public Text always has a source");
78 self
79 }
80
81 /// Replace numeric presentation for this Plot's continuous color guide.
82 /// Shared Canvas guides require identical complete effective formats before fonts.
83 /// ```compile_fail
84 /// use lichtung_plot::{kind, NumericFormat, Plot};
85 /// fn unsupported(plot: Plot<kind::Scatter>, format: NumericFormat) {
86 /// let _ = plot.color_label_format(format);
87 /// }
88 /// ```
89 #[must_use]
90 pub fn color_label_format(mut self, format: NumericFormat) -> Self
91 where
92 K: crate::kind::ContinuousColor,
93 {
94 self.description.payload_mut().color_label_format = Some(std::sync::Arc::new(format));
95 self
96 }
97
98 /// Add caller-owned wrapped text for one fully-null Cartesian heatmap row.
99 #[must_use]
100 pub fn heatmap_null_row_annotation(mut self, annotation: HeatmapNullRowAnnotation) -> Self
101 where
102 K: crate::kind::HeatmapOptions,
103 {
104 self.description
105 .payload_mut()
106 .heatmap_null_row_annotations
107 .push(annotation);
108 self
109 }
110
111 /// Set a strict Boolean column whose true heatmap cells receive a prominent border.
112 #[must_use]
113 pub fn highlight_cells(mut self, values: BooleanValues) -> Self
114 where
115 K: crate::kind::HeatmapOptions,
116 {
117 self.description.payload_mut().highlight_cells = Some(values);
118 self.description.renew_role(DataRole::HighlightCells);
119 self
120 }
121
122 /// Draw numeric labels beside point-only Coefficient estimates.
123 /// One precision is selected from every available prepared estimate in the panel.
124 /// ```compile_fail
125 /// use lichtung_plot::{kind, NumericFormat, Plot};
126 /// fn unsupported(plot: Plot<kind::Forest>, format: NumericFormat) {
127 /// let _ = plot.estimate_labels(format);
128 /// }
129 /// ```
130 #[must_use]
131 pub fn estimate_labels(mut self, format: NumericFormat) -> Self
132 where
133 K: crate::kind::CoefficientOptions,
134 {
135 self.description.payload_mut().estimate_labels = Some(format);
136 self
137 }
138
139 /// Configure significance typography independently of axis text.
140 #[must_use]
141 pub const fn significance_mark_style(
142 mut self,
143 style: crate::elements::SignificanceMarkStyle,
144 ) -> Self
145 where
146 K: crate::kind::SignificanceStyle,
147 {
148 self.description.significance_mark_style = Some(style);
149 self
150 }
151
152 /// Set the chart title.
153 ///
154 /// Plain strings replace content while retaining existing appearance and layout
155 /// instructions. A supplied Text's present style or whole layout replaces that
156 /// instruction; an explicit default layout resets it to owner defaults.
157 #[must_use]
158 pub fn title(mut self, title: impl Into<crate::Text>) -> Self {
159 self.description
160 .title
161 .replace_from(title.into())
162 .expect("public Text always has a source");
163 self
164 }
165
166 /// Set the chart subtitle.
167 /// Content and instruction replacement follow [`Self::title`].
168 #[must_use]
169 pub fn subtitle(mut self, subtitle: impl Into<crate::Text>) -> Self {
170 self.description
171 .subtitle
172 .replace_from(subtitle.into())
173 .expect("public Text always has a source");
174 self
175 }
176
177 /// Align this Plot's title and each of its lines to a physical edge or center.
178 ///
179 /// Overrides the Canvas panel default and this Plot's complete theme. Repeated
180 /// calls replace only this instruction; theme attachment order is independent.
181 /// Start and End are physical left and right after the owning content insets.
182 /// ```
183 /// use lichtung_plot::{NumericValues, Plot, Theme, text::TextAlignment};
184 /// let plot = Plot::scatter(
185 /// NumericValues::new("x", [1.0, 2.0]),
186 /// NumericValues::new("y", [2.0, 1.0]),
187 /// ).title("Title").subtitle("Independent subtitle")
188 /// .title_alignment(TextAlignment::End)
189 /// .subtitle_alignment(TextAlignment::Start)
190 /// .theme(Theme::nature());
191 /// # let _ = plot;
192 /// ```
193 #[must_use]
194 pub const fn title_alignment(mut self, alignment: crate::text::TextAlignment) -> Self {
195 self.description.title.edit_alignment(alignment);
196 self
197 }
198
199 /// Align this Plot's subtitle independently of its title.
200 ///
201 /// Overrides the Canvas panel subtitle default, then the optional theme
202 /// subtitle alignment, then the final effective title alignment. Omitting this
203 /// call contributes no instruction; it does not bypass those lower owners.
204 #[must_use]
205 pub const fn subtitle_alignment(mut self, alignment: crate::text::TextAlignment) -> Self {
206 self.description.subtitle.edit_alignment(alignment);
207 self
208 }
209
210 /// Set the chart caption.
211 /// Content and instruction replacement follow [`Self::title`].
212 #[must_use]
213 pub fn caption(mut self, caption: impl Into<crate::Text>) -> Self {
214 self.description
215 .payload_mut()
216 .caption
217 .replace_from(caption.into())
218 .expect("public Text always has a source");
219 self
220 }
221
222 /// Set the x-axis label.
223 /// Local style and line alignment are independent of the y title. Replacement
224 /// follows [`Self::title`], preserving prior instructions when omitted.
225 #[must_use]
226 pub fn x_label(mut self, label: impl Into<crate::Text>) -> Self {
227 self.description
228 .payload_mut()
229 .x_label
230 .replace_from(label.into())
231 .expect("public Text always has a source");
232 self
233 }
234
235 /// Set the y-axis label.
236 /// Local line alignment applies before the existing vertical title transform.
237 /// Content and instruction replacement follow [`Self::title`].
238 #[must_use]
239 pub fn y_label(mut self, label: impl Into<crate::Text>) -> Self {
240 self.description
241 .payload_mut()
242 .y_label
243 .replace_from(label.into())
244 .expect("public Text always has a source");
245 self
246 }
247
248 /// Set presentation rules for every label inferred from data identities.
249 #[must_use]
250 pub fn labels(mut self, labels: Labels) -> Self {
251 let labels = labels.with_captured_aliases_from(self.description.get_labels());
252 self.description.payload_mut().labels = labels;
253 self
254 }
255
256 /// Select eligible x category labels without removing categories or ticks.
257 /// ```compile_fail
258 /// use lichtung_plot::{NumericValues, Plot, coordinates::CategoryLabelSelection};
259 /// let _ = Plot::scatter(NumericValues::new("x",[1.0]),NumericValues::new("y",[1.0]))
260 /// .x_category_labels(CategoryLabelSelection::all());
261 /// ```
262 #[must_use]
263 pub fn x_category_labels(mut self, value: crate::coordinates::CategoryLabelSelection) -> Self
264 where
265 K: crate::kind::CategoricalX,
266 {
267 self.description.payload_mut().axes[0].category_labels = value;
268 self
269 }
270
271 /// Select eligible y category labels without removing categories or ticks.
272 #[must_use]
273 pub fn y_category_labels(mut self, value: crate::coordinates::CategoryLabelSelection) -> Self
274 where
275 K: crate::kind::CategoricalY,
276 {
277 self.description.payload_mut().axes[1].category_labels = value;
278 self
279 }
280
281 /// Set explicit x-axis limits.
282 #[must_use]
283 pub fn x_limits(mut self, min: f64, max: f64) -> Self
284 where
285 K: crate::kind::NumericX,
286 {
287 let axis = &mut self.description.payload_mut().axes[0];
288 *axis = std::mem::take(axis).limits(min, max);
289 self
290 }
291
292 /// Set explicit y-axis limits.
293 #[must_use]
294 pub fn y_limits(mut self, min: f64, max: f64) -> Self
295 where
296 K: crate::kind::NumericY,
297 {
298 let axis = &mut self.description.payload_mut().axes[1];
299 *axis = std::mem::take(axis).limits(min, max);
300 self
301 }
302
303 /// Replace automatic x-axis ticks with caller-labeled numeric positions.
304 #[must_use]
305 pub fn x_ticks(mut self, ticks: Vec<AxisTick>) -> Self
306 where
307 K: crate::kind::NumericX,
308 {
309 self.description.payload_mut().axes[0].exact_ticks = Some(ticks);
310 self
311 }
312
313 /// Replace automatic y-axis ticks with caller-labeled numeric positions.
314 #[must_use]
315 pub fn y_ticks(mut self, ticks: Vec<AxisTick>) -> Self
316 where
317 K: crate::kind::NumericY,
318 {
319 self.description.payload_mut().axes[1].exact_ticks = Some(ticks);
320 self
321 }
322
323 /// Replace the complete generated x-tick selection.
324 ///
325 /// Exact [`Self::x_ticks`] take precedence in either setter order, independently
326 /// of generated count limits. Targets allow nice-step deviation; maxima bound
327 /// complete in-domain sources, including endpoints. Automatic resets a previous
328 /// interval or count. The actual axis must be numeric; an interval must also
329 /// match its linear/logarithmic scale. Mismatches reject before fonts.
330 /// ```
331 /// use lichtung_plot::{NumericValues, Plot, coordinates::TickGeneration};
332 /// let plot = Plot::scatter(NumericValues::new("x", [0.0, 10.0]),
333 /// NumericValues::new("y", [0.0, 4.0]))
334 /// .x_tick_generation(TickGeneration::target(5)?)
335 /// .y_tick_generation(TickGeneration::maximum(4)?)
336 /// .x_tick_generation(TickGeneration::automatic());
337 /// # let _ = plot;
338 /// # Ok::<(), lichtung_plot::Error>(())
339 /// ```
340 /// ```compile_fail
341 /// use lichtung_plot::{kind, Plot, coordinates::TickGeneration};
342 /// fn categorical(plot: Plot<kind::Bar>, generation: TickGeneration) {
343 /// let _ = plot.x_tick_generation(generation);
344 /// }
345 /// ```
346 /// ```compile_fail
347 /// use lichtung_plot::{Plot, coordinates::TickGeneration};
348 /// fn erased(plot: Plot, generation: TickGeneration) {
349 /// let _ = plot.x_tick_generation(generation);
350 /// }
351 /// ```
352 /// ```compile_fail
353 /// use lichtung_plot::{kind, Plot, coordinates::TickGeneration};
354 /// fn matrix(plot: Plot<kind::Matrix>, generation: TickGeneration) {
355 /// let _ = plot.x_tick_generation(generation);
356 /// }
357 /// ```
358 /// ```compile_fail
359 /// use lichtung_plot::{kind, Plot, coordinates::TickGeneration};
360 /// fn heatmap(plot: Plot<kind::Heatmap>, generation: TickGeneration) {
361 /// let _ = plot.x_tick_generation(generation);
362 /// }
363 /// ```
364 #[must_use]
365 pub fn x_tick_generation(mut self, generation: crate::coordinates::TickGeneration) -> Self
366 where
367 K: crate::kind::NumericX,
368 {
369 self.description.payload_mut().axes[0].generation = generation;
370 self
371 }
372
373 /// Replace the complete generated y-tick selection, independently of x.
374 ///
375 /// Exact [`Self::y_ticks`] take precedence in either setter order. Only the
376 /// existing sealed numeric-y families admit this instruction. Automatic resets
377 /// any previous interval or count; actual categorical axes reject other choices.
378 /// ```compile_fail
379 /// use lichtung_plot::{kind, Plot, coordinates::TickGeneration};
380 /// fn categorical(plot: Plot<kind::Beeswarm>, generation: TickGeneration) {
381 /// let _ = plot.y_tick_generation(generation);
382 /// }
383 /// ```
384 /// ```compile_fail
385 /// use lichtung_plot::{Plot, coordinates::TickGeneration};
386 /// fn erased(plot: Plot, generation: TickGeneration) {
387 /// let _ = plot.y_tick_generation(generation);
388 /// }
389 /// ```
390 /// ```compile_fail
391 /// use lichtung_plot::{kind, Plot, coordinates::TickGeneration};
392 /// fn matrix(plot: Plot<kind::Matrix>, generation: TickGeneration) {
393 /// let _ = plot.y_tick_generation(generation);
394 /// }
395 /// ```
396 /// ```compile_fail
397 /// use lichtung_plot::{kind, Plot, coordinates::TickGeneration};
398 /// fn heatmap(plot: Plot<kind::Heatmap>, generation: TickGeneration) {
399 /// let _ = plot.y_tick_generation(generation);
400 /// }
401 /// ```
402 #[must_use]
403 pub fn y_tick_generation(mut self, generation: crate::coordinates::TickGeneration) -> Self
404 where
405 K: crate::kind::NumericY,
406 {
407 self.description.payload_mut().axes[1].generation = generation;
408 self
409 }
410
411 /// Replace generated numeric x-tick presentation; exact tick text takes precedence.
412 /// Forest Log10 ticks format mathematical powers, retaining exponent-space positions.
413 /// An actual categorical axis rejects this instruction before fonts.
414 /// ```compile_fail
415 /// use lichtung_plot::{kind, NumericFormat, Plot};
416 /// fn unsupported(plot: Plot<kind::Matrix>, format: NumericFormat) {
417 /// let _ = plot.x_tick_format(format);
418 /// }
419 /// ```
420 #[must_use]
421 pub fn x_tick_format(mut self, format: NumericFormat) -> Self
422 where
423 K: crate::kind::NumericX,
424 {
425 self.description.payload_mut().axes[0].format = Some(std::sync::Arc::new(format));
426 self
427 }
428
429 /// Replace generated numeric y-tick presentation; exact tick text takes precedence.
430 /// This changes displayed numbers without changing scientific coordinates.
431 /// ```compile_fail
432 /// use lichtung_plot::{kind, NumericFormat, Plot};
433 /// fn unsupported(plot: Plot<kind::Waterfall>, format: NumericFormat) {
434 /// let _ = plot.y_tick_format(format);
435 /// }
436 /// ```
437 #[must_use]
438 pub fn y_tick_format(mut self, format: NumericFormat) -> Self
439 where
440 K: crate::kind::NumericY,
441 {
442 self.description.payload_mut().axes[1].format = Some(std::sync::Arc::new(format));
443 self
444 }
445
446 /// Append a numeric guide rendered in data space.
447 #[must_use]
448 pub fn guide(mut self, guide: GuideSpec) -> Self
449 where
450 K: crate::kind::Guides,
451 {
452 self.description.payload_mut().guides.push(guide);
453 self
454 }
455
456 /// Set the primary categorical display order.
457 ///
458 /// Passing [`crate::coordinates::ValueSort`] selects value-derived ordering after the
459 /// supported plot family has prepared one scalar value per category. This
460 /// option is supported by bar families and point-interval plots; heatmaps
461 /// use [`Self::x_category_order`] and [`Self::y_category_order`].
462 #[must_use]
463 pub fn category_order(mut self, order: impl Into<CategoryOrder>) -> Self
464 where
465 K: crate::kind::CategoryOrder,
466 {
467 self.description.payload_mut().category_orders.primary = order.into();
468 self
469 }
470
471 /// Set the horizontal categorical order for a heatmap.
472 ///
473 /// Heatmap axes accept observed or explicit ordering. Value-derived
474 /// ordering is ambiguous because one axis category owns multiple cells.
475 #[must_use]
476 pub fn x_category_order(mut self, order: impl Into<CategoryOrder>) -> Self
477 where
478 K: crate::kind::HeatmapOptions,
479 {
480 self.description.payload_mut().category_orders.x = order.into();
481 self
482 }
483
484 /// Set the vertical categorical order for a heatmap.
485 ///
486 /// Heatmap axes accept observed or explicit ordering. Value-derived
487 /// ordering is ambiguous because one axis category owns multiple cells.
488 #[must_use]
489 pub fn y_category_order(mut self, order: impl Into<CategoryOrder>) -> Self
490 where
491 K: crate::kind::HeatmapOptions,
492 {
493 self.description.payload_mut().category_orders.y = order.into();
494 self
495 }
496
497 /// Color positive and negative bars with distinct theme colors.
498 #[must_use]
499 pub fn color_by_sign(mut self) -> Self
500 where
501 K: crate::kind::SignedBars,
502 {
503 self.description.payload_mut().color_by_sign = true;
504 self
505 }
506
507 /// Draw a reference line at zero on the continuous axis.
508 #[must_use]
509 pub fn zero_line(mut self) -> Self
510 where
511 K: crate::kind::ZeroLine,
512 {
513 self.description.payload_mut().zero_line = true;
514 self
515 }
516
517 /// Set one typed availability value per aligned estimate row.
518 #[must_use]
519 pub fn estimate_status(self, statuses: impl IntoIterator<Item = EstimateStatus>) -> Self
520 where
521 K: crate::kind::EstimateStatus,
522 {
523 self.with_estimate_status(EstimateStatusBinding::new(statuses))
524 }
525
526 /// Map an original Boolean estimate availability column.
527 pub fn estimate_status_boolean(self, values: BooleanValues) -> crate::Result<Self>
528 where
529 K: crate::kind::EstimateStatus,
530 {
531 Ok(self.with_estimate_status(EstimateStatusBinding::boolean(values)?))
532 }
533
534 /// Map an original categorical estimate availability column.
535 pub fn estimate_status_categorical<S: AsRef<str>>(
536 self,
537 values: CategoryValues,
538 mapping: impl IntoIterator<Item = (S, EstimateStatus)>,
539 ) -> crate::Result<Self>
540 where
541 K: crate::kind::EstimateStatus,
542 {
543 Ok(self.with_estimate_status(EstimateStatusBinding::categorical(values, mapping)?))
544 }
545
546 fn with_estimate_status(mut self, binding: EstimateStatusBinding) -> Self {
547 self.description.payload_mut().estimate_status = Some(binding);
548 self.description.renew_role(DataRole::EstimateStatus);
549 self
550 }
551
552 /// Inspect explicit availability and its original declaration, if bound.
553 pub fn get_estimate_status(&self) -> Option<&EstimateStatusBinding> {
554 self.description.payload.estimate_status.as_ref()
555 }
556
557 /// Set whether line-like plot families draw markers at estimates.
558 #[must_use]
559 pub fn show_markers(mut self, visible: bool) -> Self
560 where
561 K: crate::kind::Markers,
562 {
563 self.description.payload_mut().markers_visible = visible;
564 self
565 }
566
567 /// Replace the complete categorical palette/map selection for active raw identities.
568 #[must_use]
569 ///
570 /// The retired map-only setter is unavailable:
571 /// ```compile_fail
572 /// use lichtung_plot::{kind, Plot, scales::CategoricalColorScale};
573 /// fn old_setter(plot: Plot<kind::Scatter>, scale: CategoricalColorScale) {
574 /// let _ = plot.categorical_colors(scale);
575 /// }
576 /// ```
577 /// This attachment is not an accent-only or erased-family capability:
578 /// ```compile_fail
579 /// use lichtung_plot::{kind, Plot, scales::CategoricalColorScale};
580 /// fn wrong_family(plot: Plot<kind::Regression>, scale: CategoricalColorScale) {
581 /// let _ = plot.categorical_color_scale(scale);
582 /// }
583 /// ```
584 /// ```compile_fail
585 /// use lichtung_plot::{Plot, scales::CategoricalColorScale};
586 /// fn erased(plot: Plot, scale: CategoricalColorScale) {
587 /// let _ = plot.categorical_color_scale(scale);
588 /// }
589 /// ```
590 pub fn categorical_color_scale(mut self, scale: crate::scales::CategoricalColorScale) -> Self
591 where
592 K: crate::kind::CategoricalScale,
593 {
594 self.description.payload_mut().categorical_color_scale = Some(scale);
595 self
596 }
597
598 /// Replace the complete continuous kind, optional gradient and optional exact domain.
599 #[must_use]
600 ///
601 /// Exact limits belong to the complete typed selection:
602 /// ```compile_fail
603 /// use lichtung_plot::{kind, Plot};
604 /// fn old_limits(plot: Plot<kind::Heatmap>) {
605 /// let _ = plot.color_limits(0.0, 1.0);
606 /// }
607 /// ```
608 /// ```compile_fail
609 /// use lichtung_plot::{kind, Plot};
610 /// fn old_limits(plot: Plot<kind::Beeswarm>) {
611 /// let _ = plot.color_limits(0.0, 1.0);
612 /// }
613 /// ```
614 /// ```compile_fail
615 /// use lichtung_plot::{kind, Plot, scales::ContinuousColorScale};
616 /// fn old_selector(plot: Plot<kind::Heatmap>, scale: ContinuousColorScale) {
617 /// let _ = plot.scale(scale);
618 /// }
619 /// ```
620 pub fn continuous_color_scale(mut self, scale: crate::scales::ContinuousColorScale) -> Self
621 where
622 K: crate::kind::ContinuousColor,
623 {
624 self.description.payload_mut().continuous_color_scale = Some(scale);
625 self
626 }
627
628 /// Add a caller-owned text block at one corner inside the chart panel.
629 #[must_use]
630 pub fn text_annotation(mut self, annotation: PlotTextAnnotation) -> Self
631 where
632 K: crate::kind::TextAnnotation,
633 {
634 self.description
635 .payload_mut()
636 .panel_text_annotations
637 .push(annotation);
638 self
639 }
640
641 /// Render scatter-like point marks without the default white outline.
642 #[must_use]
643 pub fn hide_point_outline(mut self) -> Self
644 where
645 K: crate::kind::PointOutline,
646 {
647 self.description.payload_mut().point_outline_visible = false;
648 self
649 }
650
651 /// Set a complete explicit Plot theme.
652 ///
653 /// Clearing this slot restores inheritance from a parent Canvas, or the
654 /// standalone construction default, or Publication.
655 #[must_use]
656 pub fn theme(mut self, theme: impl Into<Option<Theme>>) -> Self {
657 self.description.payload_mut().theme = theme.into().map(std::sync::Arc::new);
658 self
659 }
660
661 /// Replace or clear this Plot's local construction default independently of
662 /// its explicit theme. A real parent theme takes precedence over this default.
663 #[must_use]
664 pub fn default_theme(mut self, theme: impl Into<Option<Theme>>) -> Self {
665 self.description.payload_mut().default_theme = theme.into().map(std::sync::Arc::new);
666 self
667 }
668
669 /// Append caller-owned significance annotations of one placement.
670 ///
671 /// Ordinary bars accept attached and pairwise annotations through separate
672 /// calls. Other plot families expose only their supported placement.
673 #[must_use]
674 pub fn significance<P>(mut self, annotations: impl IntoIterator<Item = Significance<P>>) -> Self
675 where
676 K: crate::kind::Significance<P>,
677 {
678 self.description
679 .payload_mut()
680 .significance
681 .extend(annotations.into_iter().map(Significance::into_annotation));
682 self
683 }
684
685 /// Allocate exactly this width in CSS pixels and derive height from content.
686 ///
687 /// Without a sizing call, both dimensions are derived from content. This
688 /// replaces the complete request, clearing any height set by [`Self::size`].
689 /// Zero is rejected during preflight, without a setter panic. An embedded
690 /// Plot's standalone request does not control its Canvas cell.
691 ///
692 /// ```no_run
693 /// use lichtung_plot::{NumericValues, Plot};
694 /// let output = Plot::scatter(
695 /// NumericValues::new("x", [0.0, 1.0]),
696 /// NumericValues::new("y", [1.0, 0.0]),
697 /// )
698 /// .size(600, 1)
699 /// .width(600)
700 /// .svg_preserve_text("figure")?;
701 /// assert_eq!(output.width(), 600.0);
702 /// assert!(output.height() > 0.0);
703 /// # Ok::<(), lichtung_plot::Error>(())
704 /// ```
705 #[must_use]
706 pub const fn width(mut self, width: u32) -> Self {
707 self.description.root_size = crate::layout::RootRequest::width(width as f64);
708 self
709 }
710
711 /// Cap the natural complete outer width and measure height at the selected width.
712 ///
713 /// This replaces any earlier sizing request. It does not fill a cap wider
714 /// than natural content, enable text reduction, or change embedded Canvas
715 /// assignments. Zero rejects during owning-root preflight, not in this setter.
716 /// ```
717 /// use lichtung_plot::{NumericValues, Plot};
718 /// let plot = Plot::scatter(NumericValues::new("x", [0.0, 1.0]),
719 /// NumericValues::new("y", [1.0, 0.0]))
720 /// .title("A width-capped scientific figure").max_width(640);
721 /// # let _ = plot;
722 /// ```
723 #[must_use]
724 pub const fn max_width(mut self, maximum: u32) -> Self {
725 self.description.root_size = crate::layout::RootRequest::MaxWidth(maximum);
726 self
727 }
728
729 /// Allocate exactly this width and height in CSS pixels.
730 ///
731 /// This replaces the complete sizing request. Content must fit without
732 /// changing either dimension; zero dimensions reject during preflight.
733 /// Final canonical dimensions are available on [`crate::Output`].
734 #[must_use]
735 pub const fn size(mut self, width: u32, height: u32) -> Self {
736 self.description.root_size = crate::layout::RootRequest::size(width as f64, height as f64);
737 self
738 }
739
740 /// Request an exact physical page size, using absolute publication units.
741 ///
742 /// Layout uses the inward spatial budget of this page. Output retains the
743 /// original size and exact CSS viewport, independently of the raster DPI.
744 pub fn size_with_unit(
745 mut self,
746 width: f64,
747 height: f64,
748 unit: crate::layout::SizeUnit,
749 ) -> crate::Result<Self> {
750 self.description.root_size = crate::layout::RootRequest::ExactSize(
751 crate::layout::RootSize::with_unit(width, height, unit)?,
752 );
753 Ok(self)
754 }
755
756 /// Set the legend visibility and placement policy.
757 ///
758 /// Native Heatmap/Beeswarm keep their right guide track and Matrix its trailing
759 /// grid track; Hidden suppresses their guide. Standard panels use the selected
760 /// inside/outside edge. All exact families can explain declared data alpha.
761 #[must_use]
762 pub fn legend(mut self, policy: LegendPolicy) -> Self
763 where
764 K: crate::kind::Legend,
765 {
766 self.description.payload_mut().legend_policy = policy;
767 self
768 }
769
770 /// Replace discrete guide composition; the default is Combined.
771 ///
772 /// This changes only section semantics, independently of theme, labels,
773 /// visibility, placement and sizing. Facets use this owning Plot selection.
774 /// Canvas Shared uses its own selection; PerPlot uses each Plot's value.
775 /// See [`crate::guides::LegendComposition::Separate`] for truthful factorization.
776 /// ```
777 /// use lichtung_plot::{CategoryValues, NumericValues, Plot, guides::LegendComposition};
778 /// let plot = Plot::scatter(NumericValues::new("x", [0.0, 1.0]),
779 /// NumericValues::new("y", [1.0, 0.0]))
780 /// .hue(CategoryValues::new("cohort", ["control", "treated"])?)
781 /// .legend_composition(LegendComposition::Separate);
782 /// # let _ = plot;
783 /// # Ok::<(), lichtung_plot::Error>(())
784 /// ```
785 /// All exact families can explain declared alpha. Erased plots do not expose this setter:
786 /// ```compile_fail
787 /// use lichtung_plot::{Plot, guides::LegendComposition};
788 /// fn erased(plot: Plot) { let _ = plot.legend_composition(LegendComposition::Separate); }
789 /// ```
790 #[must_use]
791 pub const fn legend_composition(mut self, composition: crate::guides::LegendComposition) -> Self
792 where
793 K: crate::kind::Legend,
794 {
795 self.description.legend_composition = composition;
796 self
797 }
798
799 /// Select a centered or deterministic source-row-displaced raw-observation
800 /// overlay for a boxplot or violin plot.
801 #[must_use]
802 pub const fn raw_overlay(mut self, overlay: RawOverlay) -> Self
803 where
804 K: crate::kind::RawOverlay,
805 {
806 self.description.raw_overlay = overlay;
807 self
808 }
809}
810
811impl Plot<crate::kind::Heatmap> {
812 /// Select Cartesian or structural triangular heatmap cells.
813 #[must_use]
814 pub fn layout(mut self, layout: HeatmapLayout) -> Self {
815 self.description.payload_mut().heatmap_layout = layout;
816 self
817 }
818
819 /// Configure optional heatmap cell-value annotations.
820 #[must_use]
821 pub fn annotations(mut self, annotations: HeatmapAnnotations) -> Self {
822 self.description.payload_mut().heatmap_annotations = annotations;
823 self
824 }
825}
826
827impl Plot<crate::kind::Forest> {
828 /// Set the numeric axis scale used by a forest plot.
829 #[must_use]
830 pub fn scale(mut self, scale: AxisScale) -> Self {
831 self.description.payload_mut().axis_scale = scale;
832 self
833 }
834}
835
836impl Plot<crate::kind::Bar> {
837 /// Set spacing between series inside each category.
838 #[must_use]
839 pub fn spacing(mut self, spacing: BarSpacing) -> Self {
840 self.description.payload_mut().bar_spacing = spacing;
841 self
842 }
843
844 /// Append a strict point layer positioned at prepared bar centers.
845 #[must_use]
846 pub fn point_layer(mut self, mut layer: BarPointLayer) -> Self {
847 layer.identity = crate::data::InstanceId::new();
848 self.description.payload_mut().bar_point_layers.push(layer);
849 self
850 }
851}
852
853impl Plot<crate::kind::HorizontalBar> {
854 /// Set spacing between series inside each category.
855 #[must_use]
856 pub fn spacing(mut self, spacing: BarSpacing) -> Self {
857 self.description.payload_mut().bar_spacing = spacing;
858 self
859 }
860
861 /// Append a strict point layer positioned at prepared bar centers.
862 #[must_use]
863 pub fn point_layer(mut self, mut layer: BarPointLayer) -> Self {
864 layer.identity = crate::data::InstanceId::new();
865 self.description.payload_mut().bar_point_layers.push(layer);
866 self
867 }
868}
869
870impl Plot<crate::kind::Raincloud> {
871 /// Borrow the original supplied raincloud geometry, if present.
872 pub fn get_geometry(&self) -> Option<&crate::plots::RaincloudGeometry> {
873 self.description.raincloud_geometry_input()
874 }
875}
876
877impl Plot<crate::kind::Histogram> {
878 /// Set the histogram bin-selection strategy.
879 #[must_use]
880 pub fn bins(mut self, bins: HistogramBins) -> Self {
881 self.description.payload_mut().histogram_bins = bins;
882 self
883 }
884
885 /// Set sample-derived histogram normalization. Supplied heights retain
886 /// their declared statistic; a conflicting request fails at preparation.
887 #[must_use]
888 pub fn stat(mut self, stat: HistogramStat) -> Self {
889 self.description.payload_mut().histogram_stat = Some(stat);
890 self
891 }
892
893 /// Add a KDE density curve and complete source-observation rug.
894 #[must_use]
895 pub fn composite(mut self, composite: HistogramComposite) -> Self {
896 self.description.payload_mut().histogram_composite = std::sync::Arc::new(composite);
897 self.description.renew_role(DataRole::Kde);
898 self.description.renew_domain(DomainSlot::HistogramKde);
899 self
900 }
901
902 /// Borrow the original geometry, if this histogram uses supplied bins.
903 pub fn get_geometry(&self) -> Option<&crate::plots::HistogramGeometry> {
904 self.description.histogram_geometry_input()
905 }
906
907 fn geometry_mut(&mut self) -> Result<&mut crate::plots::HistogramGeometry, crate::Error> {
908 let input = std::sync::Arc::make_mut(&mut self.description.payload_mut().input);
909 let PlotInput::Histogram { input } = input else {
910 unreachable!("the exact Histogram marker owns a histogram input");
911 };
912 input.geometry_mut().ok_or_else(|| {
913 crate::Error::Data("histogram: supplied components require supplied bins".into())
914 })
915 }
916
917 /// Add or replace the supplied KDE without changing bins, rug or plot configuration.
918 pub fn kde(mut self, x: NumericValues, density: NumericValues) -> Result<Self, crate::Error> {
919 self.geometry_mut()?.set_kde(x, density);
920 self.description.renew_role(DataRole::Geometry);
921 self.description.renew_domain(DomainSlot::HistogramKde);
922 Ok(self)
923 }
924
925 /// Add or replace supplied rug segments independently of the other components.
926 pub fn rug(
927 mut self,
928 x: NumericValues,
929 baseline: NumericValues,
930 top: NumericValues,
931 ) -> Result<Self, crate::Error> {
932 self.geometry_mut()?.set_rug(x, baseline, top);
933 self.description.renew_role(DataRole::Geometry);
934 self.description.renew_domain(DomainSlot::HistogramRug);
935 Ok(self)
936 }
937
938 /// Set the scientific value dimension of supplied geometry.
939 pub fn value_dimension(mut self, name: impl Into<String>) -> Result<Self, crate::Error> {
940 self.geometry_mut()?.set_value_dimension(name.into());
941 self.description.renew_role(DataRole::Geometry);
942 Ok(self)
943 }
944
945 /// Set the scientific height dimension of supplied geometry.
946 pub fn height_dimension(mut self, name: impl Into<String>) -> Result<Self, crate::Error> {
947 self.geometry_mut()?.set_height_dimension(name.into());
948 self.description.renew_role(DataRole::Geometry);
949 Ok(self)
950 }
951}
952
953impl Plot<crate::kind::Raincloud> {
954 /// Set the discrete hue-guide title for supplied Raincloud geometry.
955 ///
956 /// Content is verbatim; plain strings retain earlier Text instructions.
957 /// Empty text remains present. Samples, geometry without hue, and hidden
958 /// legends retain but do not consume this title.
959 #[must_use]
960 pub fn hue_label(mut self, label: impl Into<crate::Text>) -> Self {
961 self.description
962 .payload_mut()
963 .raincloud_hue_label
964 .replace_from(label.into())
965 .expect("public Text always has a source");
966 self
967 }
968}
969
970impl Plot<crate::kind::Qq> {
971 /// Set the normal Q-Q reference-line policy.
972 #[must_use]
973 pub fn reference_line(mut self, line: QqLine) -> Self {
974 self.description.payload_mut().qq_line = line;
975 self
976 }
977}
978
979impl Plot<crate::kind::Line> {
980 /// Append an independently owned supplemental point layer.
981 ///
982 /// Layers accept arbitrary coordinates independent from the primary line
983 /// input. Per-point labels annotate coordinates, while a layer legend label
984 /// identifies the complete layer once.
985 #[must_use]
986 pub fn point_layer(mut self, mut layer: PointLayer) -> Self {
987 layer.identity = crate::data::InstanceId::new();
988 self.description.payload_mut().point_layers.push(layer);
989 self
990 }
991
992 /// Add a drawable band to the line series.
993 #[must_use]
994 pub fn band(mut self, bounds: Bounds) -> Self {
995 self.description.payload_mut().line_band = Some(bounds);
996 self.description.renew_role(DataRole::Lower);
997 self.description.renew_role(DataRole::Upper);
998 self
999 }
1000}
1001
1002impl Plot<crate::kind::Regression> {
1003 /// Select the generated confidence-band policy.
1004 #[must_use]
1005 pub const fn band(mut self, band: RegressionBand) -> Self {
1006 self.description.regression_band = band;
1007 self
1008 }
1009}
1010
1011impl Plot<crate::kind::LinePath> {
1012 /// Select the complete-path color and legend policy.
1013 #[must_use]
1014 pub const fn style(mut self, style: LinePathStyle) -> Self {
1015 self.description.line_path_style = style;
1016 self
1017 }
1018}
1019
1020impl Plot<crate::kind::Coefficient> {
1021 /// Set the scientific reference/null line.
1022 #[must_use]
1023 pub fn reference_line(mut self, value: f64) -> Self {
1024 self.description.payload_mut().coefficient_reference_line = Some(value);
1025 self
1026 }
1027}
1028
1029impl Plot<crate::kind::Interaction> {
1030 /// Set whether connectors are drawn between category estimates.
1031 #[must_use]
1032 pub const fn connectors(mut self, visible: bool) -> Self {
1033 self.description.interaction_connectors = Some(visible);
1034 self
1035 }
1036
1037 /// Set exactly one typed point-and-connector style per interaction group.
1038 #[must_use]
1039 pub fn styles(mut self, styles: impl IntoIterator<Item = InteractionStyle>) -> Self {
1040 self.description.payload_mut().interaction_styles = Some(styles.into_iter().collect());
1041 self
1042 }
1043}
1044
1045impl Plot<crate::kind::Waterfall> {
1046 /// Replace numeric presentation for window-eligible base and terminal totals.
1047 /// Verbatim names from [`Self::total_labels`] join the formatted number with one space.
1048 /// ```compile_fail
1049 /// use lichtung_plot::{kind, NumericFormat, Plot};
1050 /// fn unsupported(plot: Plot<kind::HorizontalBar>, format: NumericFormat) {
1051 /// let _ = plot.total_format(format);
1052 /// }
1053 /// ```
1054 #[must_use]
1055 pub fn total_format(mut self, format: NumericFormat) -> Self {
1056 self.description.payload_mut().total_format = Some(std::sync::Arc::new(format));
1057 self
1058 }
1059
1060 /// Set caller-owned labels for base and terminal annotations.
1061 #[must_use]
1062 pub fn total_labels(mut self, labels: WaterfallLabels) -> Self {
1063 self.description.payload_mut().waterfall_labels = Some(labels);
1064 self
1065 }
1066}