1#[cfg(all(feature = "plotters", not(target_arch = "wasm32")))]
2use plotters::prelude::IntoDrawingArea;
3
4use crate::aes::Aes;
5use crate::annotate::Annotation;
6use crate::build::PlotBuilder;
7use crate::coord::cartesian::CoordCartesian;
8use crate::coord::fixed::CoordFixed;
9use crate::coord::flip::CoordFlip;
10use crate::coord::polar::CoordPolar;
11use crate::coord::Coord;
12use crate::data::{DataFrame, GGData, Value};
13use crate::facet::{Facet, FacetLabeller, FacetScales, FacetSpace};
14use crate::geom::area::GeomArea;
15use crate::geom::bar::GeomBar;
16use crate::geom::bin2d::GeomBin2d;
17use crate::geom::blank::GeomBlank;
18use crate::geom::boxplot::GeomBoxplot;
19use crate::geom::col::GeomCol;
20use crate::geom::contour::GeomContour;
21use crate::geom::count::GeomCount;
22use crate::geom::crossbar::GeomCrossbar;
23use crate::geom::curve::GeomCurve;
24use crate::geom::density::GeomDensity;
25use crate::geom::density2d::GeomDensity2d;
26use crate::geom::dotplot::GeomDotplot;
27use crate::geom::errorbar::GeomErrorbar;
28use crate::geom::freqpoly::GeomFreqpoly;
29use crate::geom::hex::GeomHex;
30use crate::geom::histogram::GeomHistogram;
31use crate::geom::jitter::GeomJitter;
32use crate::geom::line::GeomLine;
33use crate::geom::linerange::GeomLinerange;
34use crate::geom::path::GeomPath;
35use crate::geom::point::GeomPoint;
36use crate::geom::pointrange::GeomPointrange;
37use crate::geom::polygon::GeomPolygon;
38use crate::geom::qq::{GeomQQ, GeomQQLine};
39use crate::geom::rect::GeomRect;
40use crate::geom::refline::{GeomAbline, GeomHline, GeomVline};
41use crate::geom::ribbon::GeomRibbon;
42use crate::geom::rug::GeomRug;
43use crate::geom::segment::GeomSegment;
44use crate::geom::smooth::GeomSmooth;
45use crate::geom::spoke::GeomSpoke;
46use crate::geom::step::GeomStep;
47use crate::geom::text::{GeomLabel, GeomText};
48use crate::geom::tile::GeomTile;
49use crate::geom::violin::GeomViolin;
50use crate::geom::{Geom, GeomParams};
51use crate::position::Position;
52use crate::render::layout::PlotLayout;
53#[cfg(all(feature = "plotters", not(target_arch = "wasm32")))]
54use crate::render::plotters_backend::PlottersAdapter;
55use crate::render::renderer::PlotRenderer;
56use crate::render::RenderError;
57use crate::scale::continuous::ScaleContinuous;
58use crate::scale::transform::ScaleTransform;
59use crate::scale::Scale;
60use crate::stat::Stat;
61use crate::theme::Theme;
62
63mod stat_layers;
66
67#[derive(Clone, Debug, Default)]
69pub struct Labels {
70 pub title: Option<String>,
71 pub subtitle: Option<String>,
72 pub x: Option<String>,
73 pub y: Option<String>,
74 pub caption: Option<String>,
75 pub tag: Option<String>,
77}
78
79pub struct Layer {
81 pub data: Option<DataFrame>,
82 pub mapping: Aes,
83 pub geom: Box<dyn Geom>,
84 pub stat: Box<dyn Stat>,
85 pub position: Box<dyn Position>,
86 pub params: GeomParams,
87 pub show_legend: Option<bool>,
88 pub explicit_style: bool,
91}
92
93pub struct GGPlot {
95 pub(crate) data: DataFrame,
96 pub(crate) mapping: Aes,
97 pub(crate) layers: Vec<Layer>,
98 pub(crate) scales: Vec<Box<dyn Scale>>,
99 pub(crate) coord: Box<dyn Coord>,
100 pub(crate) theme: Theme,
101 pub(crate) labels: Labels,
102 pub(crate) facet: Facet,
103 pub(crate) annotations: Vec<Annotation>,
104 pub(crate) guide_legend: crate::guide::config::GuideLegend,
105 pub(crate) warnings: Vec<String>,
108 pub(crate) default_aspect_ratio: Option<f64>,
111 pub(crate) locale: Option<crate::locale::Locale>,
113}
114
115impl GGPlot {
116 pub fn new(data: impl GGData) -> Self {
123 GGPlot {
124 data: data.into_dataframe(),
125 mapping: Aes::default(),
126 layers: Vec::new(),
127 scales: Vec::new(),
128 coord: Box::new(CoordCartesian::new()),
129 theme: Theme::default(),
130 labels: Labels::default(),
131 facet: Facet::default(),
132 annotations: Vec::new(),
133 guide_legend: crate::guide::config::GuideLegend::default(),
134 warnings: Vec::new(),
135 default_aspect_ratio: None,
136 locale: None,
137 }
138 }
139
140 pub fn aes(mut self, mapping: Aes) -> Self {
142 self.mapping = mapping;
143 self
144 }
145
146 pub fn geom_point(self) -> Self {
149 self.add_geom(GeomPoint::default())
150 }
151
152 pub fn geom_point_with(self, geom: GeomPoint) -> Self {
153 self.add_geom_with(geom)
154 }
155
156 pub fn geom_line(self) -> Self {
157 self.add_geom(GeomLine::default())
158 }
159
160 pub fn geom_line_with(self, geom: GeomLine) -> Self {
161 self.add_geom_with(geom)
162 }
163
164 pub fn geom_bar(self) -> Self {
165 self.add_geom(GeomBar::default())
166 }
167
168 pub fn geom_bar_with(self, geom: GeomBar) -> Self {
169 self.add_geom_with(geom)
170 }
171
172 pub fn geom_histogram(self) -> Self {
173 self.add_geom(GeomHistogram::default())
174 }
175
176 pub fn geom_histogram_with(self, geom: GeomHistogram) -> Self {
177 self.add_geom_with(geom)
178 }
179
180 pub fn geom_boxplot(self) -> Self {
181 self.add_geom(GeomBoxplot::default())
182 }
183
184 pub fn geom_boxplot_with(self, geom: GeomBoxplot) -> Self {
185 self.add_geom_with(geom)
186 }
187
188 pub fn geom_smooth(self) -> Self {
189 self.add_geom(GeomSmooth::default())
190 }
191
192 pub fn geom_smooth_with(self, geom: GeomSmooth) -> Self {
193 self.add_geom_with(geom)
194 }
195
196 pub fn geom_col(self) -> Self {
197 self.add_geom(GeomCol::default())
198 }
199
200 pub fn geom_col_with(self, geom: GeomCol) -> Self {
201 self.add_geom_with(geom)
202 }
203
204 pub fn geom_hline(self, yintercept: f64) -> Self {
208 self.add_refline(
209 GeomHline::new(yintercept),
210 false,
211 &[("yintercept", yintercept)],
212 )
213 }
214
215 pub fn geom_hline_with(self, geom: GeomHline) -> Self {
217 let y = geom.yintercept;
218 self.add_refline(geom, true, &[("yintercept", y)])
219 }
220
221 pub fn geom_hline_aes(self, mapping: Aes) -> Self {
245 self.add_geom(GeomHline::mapped()).layer_aes(mapping)
246 }
247
248 pub fn geom_hline_aes_with(self, geom: GeomHline, mapping: Aes) -> Self {
250 self.add_geom_with(geom).layer_aes(mapping)
251 }
252
253 pub fn geom_vline(self, xintercept: f64) -> Self {
256 self.add_refline(
257 GeomVline::new(xintercept),
258 false,
259 &[("xintercept", xintercept)],
260 )
261 }
262
263 pub fn geom_vline_with(self, geom: GeomVline) -> Self {
265 let x = geom.xintercept;
266 self.add_refline(geom, true, &[("xintercept", x)])
267 }
268
269 pub fn geom_vline_aes(self, mapping: Aes) -> Self {
272 self.add_geom(GeomVline::mapped()).layer_aes(mapping)
273 }
274
275 pub fn geom_vline_aes_with(self, geom: GeomVline, mapping: Aes) -> Self {
277 self.add_geom_with(geom).layer_aes(mapping)
278 }
279
280 pub fn geom_abline(self, slope: f64, intercept: f64) -> Self {
283 self.add_refline(
284 GeomAbline::new(slope, intercept),
285 false,
286 &[("slope", slope), ("intercept", intercept)],
287 )
288 }
289
290 pub fn geom_abline_with(self, geom: GeomAbline) -> Self {
292 let (b, a) = (geom.slope, geom.intercept);
293 self.add_refline(geom, true, &[("slope", b), ("intercept", a)])
294 }
295
296 pub fn geom_abline_aes(self, mapping: Aes) -> Self {
299 self.add_geom(GeomAbline::mapped()).layer_aes(mapping)
300 }
301
302 pub fn geom_abline_aes_with(self, geom: GeomAbline, mapping: Aes) -> Self {
304 self.add_geom_with(geom).layer_aes(mapping)
305 }
306
307 fn add_refline(
310 self,
311 geom: impl Geom + 'static,
312 explicit: bool,
313 values: &[(&str, f64)],
314 ) -> Self {
315 let mut data = DataFrame::new();
316 let mut mapping = Aes::new();
317 for (col, v) in values {
318 data.add_column(col.to_string(), vec![Value::Float(*v)]);
319 mapping = match *col {
320 "xintercept" => mapping.xintercept(col),
321 "yintercept" => mapping.yintercept(col),
322 "slope" => mapping.slope(col),
323 _ => mapping.intercept(col),
324 };
325 }
326 let plot = if explicit {
327 self.add_geom_with(geom)
328 } else {
329 self.add_geom(geom)
330 };
331 plot.layer_aes(mapping).layer_data(data)
332 }
333
334 pub fn geom_text(self) -> Self {
335 self.add_geom(GeomText::default())
336 }
337
338 pub fn geom_text_with(self, geom: GeomText) -> Self {
339 self.add_geom_with(geom)
340 }
341
342 #[cfg(feature = "ggpubr")]
347 pub fn stat_cor(self) -> Self {
348 self.geom_text().stat(crate::stat::cor::StatCor::default())
349 }
350
351 #[cfg(feature = "ggpubr")]
354 pub fn stat_cor_with(self, stat: crate::stat::cor::StatCor) -> Self {
355 self.geom_text().stat(stat)
356 }
357
358 #[cfg(feature = "ggpubr")]
363 pub fn stat_compare_means(self) -> Self {
364 self.geom_text()
365 .stat(crate::stat::compare_means::StatCompareMeans::default())
366 }
367
368 #[cfg(feature = "ggpubr")]
371 pub fn stat_compare_means_with(
372 self,
373 stat: crate::stat::compare_means::StatCompareMeans,
374 ) -> Self {
375 self.geom_text().stat(stat)
376 }
377
378 #[cfg(feature = "ggpubr")]
384 pub fn stat_compare_means_pairwise(self, comparisons: &[(&str, &str)]) -> Self {
385 self.stat_compare_means_pairwise_with(
386 crate::stat::compare_means::CompareMethod::Auto,
387 comparisons,
388 )
389 }
390
391 #[cfg(feature = "ggpubr")]
394 pub fn stat_compare_means_pairwise_with(
395 self,
396 method: crate::stat::compare_means::CompareMethod,
397 comparisons: &[(&str, &str)],
398 ) -> Self {
399 let col_for = |a: crate::aes::Aesthetic| {
401 self.mapping
402 .mappings
403 .iter()
404 .find(|m| m.aesthetic == a)
405 .map(|m| m.column.clone())
406 };
407 let (xcol, ycol) = match (
408 col_for(crate::aes::Aesthetic::X),
409 col_for(crate::aes::Aesthetic::Y),
410 ) {
411 (Some(x), Some(y)) => (x, y),
412 _ => return self,
413 };
414 let (xc, yc) = match (self.data.column(&xcol), self.data.column(&ycol)) {
415 (Some(x), Some(y)) => (x, y),
416 _ => return self,
417 };
418
419 let mut groups: Vec<(String, Vec<f64>)> = Vec::new();
421 let mut ymax = f64::NEG_INFINITY;
422 let mut ymin = f64::INFINITY;
423 for (xv, yv) in xc.iter().zip(yc.iter()) {
424 let y = match yv.as_f64() {
425 Some(y) if y.is_finite() => y,
426 _ => continue,
427 };
428 ymax = ymax.max(y);
429 ymin = ymin.min(y);
430 let key = xv.to_group_key();
431 if let Some(g) = groups.iter_mut().find(|(k, _)| *k == key) {
432 g.1.push(y);
433 } else {
434 groups.push((key, vec![y]));
435 }
436 }
437 if groups.len() < 2 {
438 return self;
439 }
440 let step = if ymax > ymin {
441 (ymax - ymin) * 0.12
442 } else {
443 1.0
444 };
445
446 let (mut xmin_v, mut xmax_v, mut y_v, mut label_v) =
448 (Vec::new(), Vec::new(), Vec::new(), Vec::new());
449 let mut placed = 0usize;
450 for (a, b) in comparisons {
451 let ga = groups.iter().find(|(k, _)| k == a).map(|g| &g.1);
452 let gb = groups.iter().find(|(k, _)| k == b).map(|g| &g.1);
453 let (ga, gb) = match (ga, gb) {
454 (Some(x), Some(y)) if x.len() >= 2 && y.len() >= 2 => (x, y),
455 _ => continue,
456 };
457 let p = match crate::stat::compare_means::pairwise_p(method, ga, gb) {
458 Some(p) => p,
459 None => continue,
460 };
461 xmin_v.push(Value::Str((*a).to_string()));
462 xmax_v.push(Value::Str((*b).to_string()));
463 y_v.push(Value::Float(ymax + step * (placed as f64 + 1.0)));
464 label_v.push(Value::Str(crate::stat::cor::format_p_value(p)));
465 placed += 1;
466 }
467 if xmin_v.is_empty() {
468 return self;
469 }
470
471 let data = vec![
472 ("xmin".to_string(), xmin_v),
473 ("xmax".to_string(), xmax_v),
474 ("y".to_string(), y_v),
475 ("label".to_string(), label_v),
476 ];
477 self.add_geom(crate::geom::bracket::GeomBracket::default())
478 .layer_data(data)
479 .layer_aes(Aes::new().xmin("xmin").xmax("xmax").y("y").label("label"))
480 }
481
482 pub fn geom_bracket(self, xmin: &str, xmax: &str, y: f64, label: &str) -> Self {
487 self.geom_bracket_many(
488 crate::geom::bracket::GeomBracket::default(),
489 &[(xmin, xmax, y, label)],
490 )
491 }
492
493 pub fn geom_bracket_many(
497 self,
498 geom: crate::geom::bracket::GeomBracket,
499 brackets: &[(&str, &str, f64, &str)],
500 ) -> Self {
501 let xmin = brackets
502 .iter()
503 .map(|b| Value::Str(b.0.to_string()))
504 .collect::<Vec<_>>();
505 let xmax = brackets
506 .iter()
507 .map(|b| Value::Str(b.1.to_string()))
508 .collect::<Vec<_>>();
509 let y = brackets
510 .iter()
511 .map(|b| Value::Float(b.2))
512 .collect::<Vec<_>>();
513 let label = brackets
514 .iter()
515 .map(|b| Value::Str(b.3.to_string()))
516 .collect::<Vec<_>>();
517 let data = vec![
518 ("xmin".to_string(), xmin),
519 ("xmax".to_string(), xmax),
520 ("y".to_string(), y),
521 ("label".to_string(), label),
522 ];
523 self.add_geom(geom)
524 .layer_data(data)
525 .layer_aes(Aes::new().xmin("xmin").xmax("xmax").y("y").label("label"))
526 }
527
528 pub fn geom_bracket_table(
537 mut self,
538 table: impl GGData,
539 spec: crate::geom::bracket::BracketTable,
540 ) -> Self {
541 let table = table.into_dataframe();
542 let col_for = |a: crate::aes::Aesthetic| {
543 self.mapping
544 .mappings
545 .iter()
546 .find(|m| m.aesthetic == a)
547 .map(|m| m.column.clone())
548 };
549 let x_levels: Vec<String> = col_for(crate::aes::Aesthetic::X)
552 .and_then(|c| self.data.column(&c))
553 .filter(|col| col.iter().any(|v| matches!(v, Value::Str(_))))
554 .map(|col| {
555 let mut seen = std::collections::HashSet::new();
556 col.iter()
557 .filter(|v| !v.is_na())
558 .map(|v| v.to_group_key())
559 .filter(|k| seen.insert(k.clone()))
560 .collect()
561 })
562 .unwrap_or_default();
563 let y_range = col_for(crate::aes::Aesthetic::Y)
564 .and_then(|c| self.data.column(&c))
565 .and_then(|col| {
566 let (lo, hi) = col
567 .iter()
568 .filter_map(|v| v.as_f64())
569 .filter(|v| v.is_finite())
570 .fold((f64::INFINITY, f64::NEG_INFINITY), |(lo, hi), v| {
571 (lo.min(v), hi.max(v))
572 });
573 (lo <= hi).then_some((lo, hi))
574 });
575 let mut warnings = Vec::new();
576 let resolved = spec.resolve(&table, &x_levels, y_range, &mut warnings);
577 self.warnings.extend(warnings);
578 match resolved {
579 Some(data) => self
580 .add_geom(crate::geom::bracket::GeomBracket::from(spec.geom))
581 .layer_data(data)
582 .layer_aes(Aes::new().xmin("xmin").xmax("xmax").y("y").label("label")),
583 None => self,
584 }
585 }
586
587 pub fn geom_text_repel(self) -> Self {
592 self.add_geom(crate::geom::repel::GeomTextRepel::default())
593 }
594
595 pub fn geom_text_repel_with(self, geom: crate::geom::repel::GeomTextRepel) -> Self {
598 self.add_geom_with(geom)
599 }
600
601 pub fn geom_label_repel(self) -> Self {
604 self.add_geom(crate::geom::repel::GeomLabelRepel::default())
605 }
606
607 pub fn geom_label_repel_with(self, geom: crate::geom::repel::GeomLabelRepel) -> Self {
609 self.add_geom_with(geom)
610 }
611
612 pub fn geom_label(self) -> Self {
613 self.add_geom(GeomLabel::default())
614 }
615
616 pub fn geom_label_with(self, geom: GeomLabel) -> Self {
617 self.add_geom_with(geom)
618 }
619
620 pub fn geom_area(self) -> Self {
621 self.add_geom(GeomArea::default())
622 }
623
624 pub fn geom_area_with(self, geom: GeomArea) -> Self {
625 self.add_geom_with(geom)
626 }
627
628 pub fn geom_ribbon(self) -> Self {
629 self.add_geom(GeomRibbon::default())
630 }
631
632 pub fn geom_ribbon_with(self, geom: GeomRibbon) -> Self {
633 self.add_geom_with(geom)
634 }
635
636 pub fn geom_errorbar(self) -> Self {
637 self.add_geom(GeomErrorbar::default())
638 }
639
640 pub fn geom_errorbar_with(self, geom: GeomErrorbar) -> Self {
641 self.add_geom_with(geom)
642 }
643
644 pub fn geom_segment(self) -> Self {
645 self.add_geom(GeomSegment::default())
646 }
647
648 pub fn geom_segment_with(self, geom: GeomSegment) -> Self {
649 self.add_geom_with(geom)
650 }
651
652 pub fn geom_density(self) -> Self {
653 self.add_geom(GeomDensity::default())
654 }
655
656 pub fn geom_density_with(self, geom: GeomDensity) -> Self {
657 self.add_geom_with(geom)
658 }
659
660 pub fn geom_rug(self) -> Self {
661 self.add_geom(GeomRug::default())
662 }
663
664 pub fn geom_rug_with(self, geom: GeomRug) -> Self {
665 self.add_geom_with(geom)
666 }
667
668 pub fn geom_jitter(self) -> Self {
669 self.add_geom(GeomJitter::default())
670 }
671
672 pub fn geom_jitter_with(self, geom: GeomJitter) -> Self {
673 self.add_geom_with(geom)
674 }
675
676 pub fn geom_path(self) -> Self {
677 self.add_geom(GeomPath::default())
678 }
679
680 pub fn geom_path_with(self, geom: GeomPath) -> Self {
681 self.add_geom_with(geom)
682 }
683
684 pub fn stat_ellipse(self) -> Self {
686 self.geom_path()
687 .stat(crate::stat::ellipse::StatEllipse::default())
688 }
689
690 pub fn stat_ellipse_level(self, level: f64) -> Self {
692 self.geom_path()
693 .stat(crate::stat::ellipse::StatEllipse::new(level))
694 }
695
696 #[cfg(feature = "regression")]
699 pub fn stat_quantile(mut self, taus: &[f64]) -> Self {
700 for &tau in taus {
701 self = self
702 .geom_path()
703 .stat(crate::stat::quantile::StatQuantile::new(tau));
704 }
705 self
706 }
707
708 #[cfg(feature = "regression")]
710 pub fn geom_quantile(self) -> Self {
711 self.stat_quantile(&[0.25, 0.5, 0.75])
712 }
713
714 pub fn geom_step(self) -> Self {
715 self.add_geom(GeomStep::default())
716 }
717
718 pub fn geom_step_with(self, geom: GeomStep) -> Self {
719 self.add_geom_with(geom)
720 }
721
722 pub fn geom_freqpoly(self) -> Self {
723 self.add_geom(GeomFreqpoly::default())
724 }
725
726 pub fn geom_freqpoly_with(self, geom: GeomFreqpoly) -> Self {
727 self.add_geom_with(geom)
728 }
729
730 pub fn geom_linerange(self) -> Self {
731 self.add_geom(GeomLinerange::default())
732 }
733
734 pub fn geom_linerange_with(self, geom: GeomLinerange) -> Self {
735 self.add_geom_with(geom)
736 }
737
738 pub fn geom_pointrange(self) -> Self {
739 self.add_geom(GeomPointrange::default())
740 }
741
742 pub fn geom_pointrange_with(self, geom: GeomPointrange) -> Self {
743 self.add_geom_with(geom)
744 }
745
746 pub fn geom_crossbar(self) -> Self {
747 self.add_geom(GeomCrossbar::default())
748 }
749
750 pub fn geom_crossbar_with(self, geom: GeomCrossbar) -> Self {
751 self.add_geom_with(geom)
752 }
753
754 pub fn geom_spoke(self) -> Self {
755 self.add_geom(GeomSpoke::default())
756 }
757
758 pub fn geom_spoke_with(self, geom: GeomSpoke) -> Self {
759 self.add_geom_with(geom)
760 }
761
762 pub fn geom_rect(self) -> Self {
763 self.add_geom(GeomRect::default())
764 }
765
766 pub fn geom_rect_with(self, geom: GeomRect) -> Self {
767 self.add_geom_with(geom)
768 }
769
770 pub fn geom_tile(self) -> Self {
771 self.add_geom(GeomTile::default())
772 }
773
774 pub fn geom_tile_with(self, geom: GeomTile) -> Self {
775 self.add_geom_with(geom)
776 }
777
778 pub fn geom_raster(self) -> Self {
780 self.add_geom(crate::geom::raster::GeomRaster::default())
781 }
782
783 pub fn geom_raster_with(self, geom: crate::geom::raster::GeomRaster) -> Self {
784 self.add_geom_with(geom)
785 }
786
787 pub fn geom_polygon(self) -> Self {
788 self.add_geom(GeomPolygon::default())
789 }
790
791 pub fn geom_polygon_with(self, geom: GeomPolygon) -> Self {
792 self.add_geom_with(geom)
793 }
794
795 #[cfg(feature = "sf")]
797 pub fn geom_sf(self) -> Self {
798 self.add_geom(crate::geom::sf::GeomSf::default())
799 }
800
801 #[cfg(feature = "sf")]
802 pub fn geom_sf_with(self, geom: crate::geom::sf::GeomSf) -> Self {
803 self.add_geom_with(geom)
804 }
805
806 pub fn geom_curve(self) -> Self {
807 self.add_geom(GeomCurve::default())
808 }
809
810 pub fn geom_curve_with(self, geom: GeomCurve) -> Self {
811 self.add_geom_with(geom)
812 }
813
814 pub fn geom_violin(self) -> Self {
815 self.add_geom(GeomViolin::default())
816 }
817
818 pub fn geom_violin_with(self, geom: GeomViolin) -> Self {
819 self.add_geom_with(geom)
820 }
821
822 pub fn geom_dotplot(self) -> Self {
823 self.add_geom(GeomDotplot::default())
824 }
825
826 pub fn geom_dotplot_with(self, geom: GeomDotplot) -> Self {
827 self.add_geom_with(geom)
828 }
829
830 pub fn geom_qq(self) -> Self {
831 self.add_geom(GeomQQ::default())
832 }
833
834 pub fn geom_qq_with(self, geom: GeomQQ) -> Self {
835 self.add_geom_with(geom)
836 }
837
838 pub fn geom_qq_line(self) -> Self {
839 self.add_geom(GeomQQLine::default())
840 }
841
842 pub fn geom_qq_line_with(self, geom: GeomQQLine) -> Self {
843 self.add_geom_with(geom)
844 }
845
846 pub fn geom_bin2d(self) -> Self {
847 self.add_geom(GeomBin2d::default())
848 }
849
850 pub fn geom_bin2d_with(self, geom: GeomBin2d) -> Self {
851 self.add_geom_with(geom)
852 }
853
854 pub fn geom_hex(self) -> Self {
855 self.add_geom(GeomHex::default())
856 }
857
858 pub fn geom_hex_with(self, geom: GeomHex) -> Self {
859 self.add_geom_with(geom)
860 }
861
862 pub fn geom_count(self) -> Self {
863 self.add_geom(GeomCount::default())
864 }
865
866 pub fn geom_count_with(self, geom: GeomCount) -> Self {
867 self.add_geom_with(geom)
868 }
869
870 pub fn geom_contour(self) -> Self {
871 self.add_geom(GeomContour::default())
872 }
873
874 pub fn geom_contour_with(self, geom: GeomContour) -> Self {
875 self.add_geom_with(geom)
876 }
877
878 pub fn geom_contour_filled(self) -> Self {
881 self.add_geom(GeomPolygon {
882 line_width: 0.0,
883 alpha: 1.0,
884 ..GeomPolygon::default()
885 })
886 .stat(crate::stat::contour_filled::StatContourFilled::default())
887 }
888
889 pub fn geom_density2d(self) -> Self {
890 self.add_geom(GeomDensity2d::default())
891 }
892
893 pub fn geom_density2d_with(self, geom: GeomDensity2d) -> Self {
894 self.add_geom_with(geom)
895 }
896
897 pub fn geom_candlestick(self) -> Self {
900 self.add_geom(crate::geom::candlestick::GeomCandlestick::default())
901 }
902
903 pub fn geom_candlestick_with(self, geom: crate::geom::candlestick::GeomCandlestick) -> Self {
904 self.add_geom_with(geom)
905 }
906
907 pub fn geom_ohlc(self) -> Self {
910 self.add_geom(crate::geom::candlestick::GeomOhlc::default())
911 }
912
913 pub fn geom_ohlc_with(self, geom: crate::geom::candlestick::GeomOhlc) -> Self {
914 self.add_geom_with(geom)
915 }
916
917 pub fn geom_calendar(self) -> Self {
928 self.geom_calendar_with(
929 GeomTile {
930 color: (255, 255, 255),
931 line_width: 1.5,
932 ..Default::default()
933 },
934 false,
935 )
936 }
937
938 pub fn geom_calendar_with(mut self, tile: GeomTile, monday_first: bool) -> Self {
941 use crate::stat::calendar::{
942 day_number, month_boundaries, month_breaks, month_breaks_localized, weekday_labels,
943 CalendarGrid, StatCalendar, MAX_CALENDAR_YEARS,
944 };
945 let grid = self
946 .mapping
947 .get_mapping(&crate::aes::Aesthetic::X)
948 .and_then(|c| self.data.column(c))
949 .and_then(|col| {
950 CalendarGrid::from_days(col.iter().filter_map(day_number), monday_first)
951 });
952 let Some((grid, clipped)) = grid else {
953 return self.add_geom_with(tile).stat(StatCalendar {
955 grid: None,
956 monday_first,
957 });
958 };
959 if clipped {
960 self.warnings.push(format!(
961 "geom_calendar: dates more than {MAX_CALENDAR_YEARS} years before the newest were dropped"
962 ));
963 }
964 let (xb, _) = month_breaks(&grid);
965 let yb = if monday_first {
967 vec![6.0, 4.0, 2.0]
968 } else {
969 vec![5.0, 3.0, 1.0]
970 };
971 let segs = month_boundaries(&grid);
972 let col = |f: fn(&(f64, f64, f64, f64)) -> f64| -> Vec<Value> {
973 segs.iter().map(|s| Value::Float(f(s))).collect()
974 };
975 let boundaries = vec![
976 ("x".to_string(), col(|s| s.0)),
977 ("y".to_string(), col(|s| s.1)),
978 ("xend".to_string(), col(|s| s.2)),
979 ("yend".to_string(), col(|s| s.3)),
980 ];
981 self.default_aspect_ratio = Some(7.0 / grid.n_weeks().max(1) as f64);
982 let plot = self
983 .add_geom_with(tile)
984 .stat(StatCalendar {
985 grid: Some(grid),
986 monday_first,
987 })
988 .scale_x_continuous(
989 ScaleContinuous::new()
990 .with_breaks(xb)
991 .with_localized_labels(move |l| month_breaks_localized(&grid, l).1)
993 .with_expand(0.0, 0.0),
994 )
995 .scale_y_continuous(
996 ScaleContinuous::new()
997 .with_breaks(yb)
998 .with_localized_labels(weekday_labels)
999 .with_expand(0.0, 0.0),
1000 );
1001 if segs.is_empty() {
1002 return plot;
1003 }
1004 plot.add_geom_with(crate::geom::segment::GeomCalendarBorder)
1006 .layer_data(boundaries)
1007 .layer_aes(Aes::new().x("x").y("y").xend("xend").yend("yend"))
1008 .show_legend(false)
1009 }
1010
1011 pub fn geom_blank(self) -> Self {
1012 self.add_geom(GeomBlank)
1013 }
1014
1015 fn add_geom_with(self, geom: impl Geom + 'static) -> Self {
1018 let mut plot = self.add_geom(geom);
1019 if let Some(layer) = plot.layers.last_mut() {
1020 layer.explicit_style = true;
1021 }
1022 plot
1023 }
1024
1025 fn add_geom(mut self, geom: impl Geom + 'static) -> Self {
1026 let stat = geom.default_stat();
1027 let position = geom.default_position();
1028 let params = geom.default_params();
1029 self.layers.push(Layer {
1030 data: None,
1031 mapping: Aes::default(),
1032 geom: Box::new(geom),
1033 stat,
1034 position,
1035 params,
1036 show_legend: None,
1037 explicit_style: false,
1038 });
1039 self
1040 }
1041
1042 pub fn stat(mut self, stat: impl Stat + 'static) -> Self {
1046 if let Some(layer) = self.layers.last_mut() {
1047 layer.stat = Box::new(stat);
1048 }
1049 self
1050 }
1051
1052 pub fn position(mut self, pos: impl Position + 'static) -> Self {
1054 if let Some(layer) = self.layers.last_mut() {
1055 layer.position = Box::new(pos);
1056 }
1057 self
1058 }
1059
1060 pub fn layer_data(mut self, data: impl GGData) -> Self {
1062 if let Some(layer) = self.layers.last_mut() {
1063 layer.data = Some(data.into_dataframe());
1064 }
1065 self
1066 }
1067
1068 pub fn layer_aes(mut self, mapping: Aes) -> Self {
1070 if let Some(layer) = self.layers.last_mut() {
1071 layer.mapping = mapping;
1072 }
1073 self
1074 }
1075
1076 pub fn show_legend(mut self, show: bool) -> Self {
1079 if let Some(layer) = self.layers.last_mut() {
1080 layer.show_legend = Some(show);
1081 }
1082 self
1083 }
1084
1085 pub fn scale_x_continuous(mut self, s: ScaleContinuous) -> Self {
1088 let s = s.for_aesthetic(crate::aes::Aesthetic::X);
1089 self.scales.push(Box::new(s));
1090 self
1091 }
1092
1093 pub fn scale_y_continuous(mut self, s: ScaleContinuous) -> Self {
1094 let s = s.for_aesthetic(crate::aes::Aesthetic::Y);
1095 self.scales.push(Box::new(s));
1096 self
1097 }
1098
1099 pub fn scale_x_discrete(mut self, s: crate::scale::discrete::ScaleDiscrete) -> Self {
1100 let s = s.for_aesthetic(crate::aes::Aesthetic::X);
1101 self.scales.push(Box::new(s));
1102 self
1103 }
1104
1105 pub fn scale_y_discrete(mut self, s: crate::scale::discrete::ScaleDiscrete) -> Self {
1106 let s = s.for_aesthetic(crate::aes::Aesthetic::Y);
1107 self.scales.push(Box::new(s));
1108 self
1109 }
1110
1111 pub fn scale_color(mut self, s: impl Scale + 'static) -> Self {
1112 self.scales.push(Box::new(s));
1113 self
1114 }
1115
1116 pub fn scale_fill(mut self, s: impl Scale + 'static) -> Self {
1117 self.scales.push(Box::new(s));
1118 self
1119 }
1120
1121 pub fn scale_color_manual(self, values: Vec<(&str, crate::scale::color::RGBAColor)>) -> Self {
1122 let s = crate::scale::manual::ScaleManual::new(crate::aes::Aesthetic::Color, values);
1123 self.scale_color(s)
1124 }
1125
1126 pub fn scale_fill_manual(self, values: Vec<(&str, crate::scale::color::RGBAColor)>) -> Self {
1127 let s = crate::scale::manual::ScaleManual::new(crate::aes::Aesthetic::Fill, values);
1128 self.scale_fill(s)
1129 }
1130
1131 pub fn scale_color_viridis(self) -> Self {
1132 use crate::scale::color::ScaleColorDiscrete;
1133 use crate::scale::palettes::PaletteName;
1134 let s = ScaleColorDiscrete::new(crate::aes::Aesthetic::Color)
1135 .with_named_palette(&PaletteName::Viridis);
1136 self.scale_color(s)
1137 }
1138
1139 pub fn scale_color_brewer(self, name: crate::scale::palettes::PaletteName) -> Self {
1140 use crate::scale::color::ScaleColorDiscrete;
1141 let s = ScaleColorDiscrete::new(crate::aes::Aesthetic::Color).with_named_palette(&name);
1142 self.scale_color(s)
1143 }
1144
1145 pub fn scale_color_gradient(
1146 self,
1147 low: crate::scale::color::RGBAColor,
1148 high: crate::scale::color::RGBAColor,
1149 ) -> Self {
1150 use crate::scale::color::ScaleColorContinuous;
1151 let s = ScaleColorContinuous::new(crate::aes::Aesthetic::Color).with_colors(low, high);
1152 self.scale_color(s)
1153 }
1154
1155 pub fn scale_fill_gradient(
1156 self,
1157 low: crate::scale::color::RGBAColor,
1158 high: crate::scale::color::RGBAColor,
1159 ) -> Self {
1160 use crate::scale::color::ScaleColorContinuous;
1161 let s = ScaleColorContinuous::new(crate::aes::Aesthetic::Fill).with_colors(low, high);
1162 self.scale_fill(s)
1163 }
1164
1165 pub fn scale_color_gradient2(
1166 self,
1167 low: crate::scale::color::RGBAColor,
1168 mid: crate::scale::color::RGBAColor,
1169 high: crate::scale::color::RGBAColor,
1170 ) -> Self {
1171 use crate::scale::gradient::ScaleColorGradient2;
1172 let s = ScaleColorGradient2::new(crate::aes::Aesthetic::Color).with_colors(low, mid, high);
1173 self.scale_color(s)
1174 }
1175
1176 pub fn scale_fill_gradient2(
1177 self,
1178 low: crate::scale::color::RGBAColor,
1179 mid: crate::scale::color::RGBAColor,
1180 high: crate::scale::color::RGBAColor,
1181 ) -> Self {
1182 use crate::scale::gradient::ScaleColorGradient2;
1183 let s = ScaleColorGradient2::new(crate::aes::Aesthetic::Fill).with_colors(low, mid, high);
1184 self.scale_fill(s)
1185 }
1186
1187 pub fn scale_fill_viridis(self) -> Self {
1188 use crate::scale::color::ScaleColorDiscrete;
1189 use crate::scale::palettes::PaletteName;
1190 let s = ScaleColorDiscrete::new(crate::aes::Aesthetic::Fill)
1191 .with_named_palette(&PaletteName::Viridis);
1192 self.scale_fill(s)
1193 }
1194
1195 pub fn scale_color_viridis_c(self) -> Self {
1197 use crate::scale::gradient_n::ScaleColorGradientN;
1198 let s = ScaleColorGradientN::viridis(crate::aes::Aesthetic::Color);
1199 self.scale_color(s)
1200 }
1201
1202 pub fn scale_fill_viridis_c(self) -> Self {
1204 use crate::scale::gradient_n::ScaleColorGradientN;
1205 let s = ScaleColorGradientN::viridis(crate::aes::Aesthetic::Fill);
1206 self.scale_fill(s)
1207 }
1208
1209 pub fn scale_color_gradientn(self, stops: Vec<(f64, crate::scale::color::RGBAColor)>) -> Self {
1211 use crate::scale::gradient_n::ScaleColorGradientN;
1212 let s = ScaleColorGradientN::new(crate::aes::Aesthetic::Color, stops);
1213 self.scale_color(s)
1214 }
1215
1216 pub fn scale_fill_gradientn(self, stops: Vec<(f64, crate::scale::color::RGBAColor)>) -> Self {
1218 use crate::scale::gradient_n::ScaleColorGradientN;
1219 let s = ScaleColorGradientN::new(crate::aes::Aesthetic::Fill, stops);
1220 self.scale_fill(s)
1221 }
1222
1223 pub fn scale_color_steps(
1226 self,
1227 low: crate::scale::color::RGBAColor,
1228 high: crate::scale::color::RGBAColor,
1229 n_bins: usize,
1230 ) -> Self {
1231 let s = crate::scale::steps::ScaleColorSteps::two(
1232 crate::aes::Aesthetic::Color,
1233 (low.r, low.g, low.b),
1234 (high.r, high.g, high.b),
1235 n_bins,
1236 );
1237 self.scale_color(s)
1238 }
1239
1240 pub fn scale_color_stepsn(
1242 self,
1243 stops: Vec<crate::scale::color::RGBAColor>,
1244 n_bins: usize,
1245 ) -> Self {
1246 let s = crate::scale::steps::ScaleColorSteps::new(
1247 crate::aes::Aesthetic::Color,
1248 stops.iter().map(|c| (c.r, c.g, c.b)).collect(),
1249 n_bins,
1250 );
1251 self.scale_color(s)
1252 }
1253
1254 pub fn scale_color_fermenter(
1256 self,
1257 name: crate::scale::palettes::PaletteName,
1258 n_bins: usize,
1259 ) -> Self {
1260 let stops = crate::scale::palettes::palette(&name)
1261 .iter()
1262 .map(|c| (c.r, c.g, c.b))
1263 .collect();
1264 let s =
1265 crate::scale::steps::ScaleColorSteps::new(crate::aes::Aesthetic::Color, stops, n_bins);
1266 self.scale_color(s)
1267 }
1268
1269 pub fn scale_fill_steps(
1271 self,
1272 low: crate::scale::color::RGBAColor,
1273 high: crate::scale::color::RGBAColor,
1274 n_bins: usize,
1275 ) -> Self {
1276 let s = crate::scale::steps::ScaleColorSteps::two(
1277 crate::aes::Aesthetic::Fill,
1278 (low.r, low.g, low.b),
1279 (high.r, high.g, high.b),
1280 n_bins,
1281 );
1282 self.scale_fill(s)
1283 }
1284
1285 pub fn scale_fill_fermenter(
1287 self,
1288 name: crate::scale::palettes::PaletteName,
1289 n_bins: usize,
1290 ) -> Self {
1291 let stops = crate::scale::palettes::palette(&name)
1292 .iter()
1293 .map(|c| (c.r, c.g, c.b))
1294 .collect();
1295 let s =
1296 crate::scale::steps::ScaleColorSteps::new(crate::aes::Aesthetic::Fill, stops, n_bins);
1297 self.scale_fill(s)
1298 }
1299
1300 pub fn scale_fill_discrete_sorted(self) -> Self {
1305 use crate::scale::color::ScaleColorDiscrete;
1306 self.scale_fill(ScaleColorDiscrete::new(crate::aes::Aesthetic::Fill).sorted())
1307 }
1308
1309 pub fn scale_color_discrete_sorted(self) -> Self {
1312 use crate::scale::color::ScaleColorDiscrete;
1313 self.scale_color(ScaleColorDiscrete::new(crate::aes::Aesthetic::Color).sorted())
1314 }
1315
1316 pub fn scale_fill_brewer(self, name: crate::scale::palettes::PaletteName) -> Self {
1317 use crate::scale::color::ScaleColorDiscrete;
1318 let s = ScaleColorDiscrete::new(crate::aes::Aesthetic::Fill).with_named_palette(&name);
1319 self.scale_fill(s)
1320 }
1321
1322 pub fn scale_linetype_manual(
1323 self,
1324 values: Vec<(&str, crate::render::backend::Linetype)>,
1325 ) -> Self {
1326 let s = crate::scale::linetype_manual::ScaleLinetypeManual::new(values);
1327 self.scale_color(s)
1328 }
1329
1330 pub fn scale_shape_manual(
1331 self,
1332 values: Vec<(&str, crate::render::backend::PointShape)>,
1333 ) -> Self {
1334 let s = crate::scale::shape_manual::ScaleShapeManual::new(values);
1335 self.scale_color(s)
1336 }
1337
1338 pub fn scale_color_grey(self) -> Self {
1339 let s = crate::scale::grey::ScaleColorGrey::new(crate::aes::Aesthetic::Color);
1340 self.scale_color(s)
1341 }
1342
1343 pub fn scale_fill_grey(self) -> Self {
1344 let s = crate::scale::grey::ScaleColorGrey::new(crate::aes::Aesthetic::Fill);
1345 self.scale_fill(s)
1346 }
1347
1348 pub fn scale_color_grey_with(self, s: crate::scale::grey::ScaleColorGrey) -> Self {
1349 self.scale_color(s)
1350 }
1351
1352 pub fn scale_fill_grey_with(self, s: crate::scale::grey::ScaleColorGrey) -> Self {
1353 self.scale_fill(s)
1354 }
1355
1356 pub fn scale_x_reverse(self) -> Self {
1357 self.scale_x_continuous(ScaleContinuous::new().with_transform(ScaleTransform::Reverse))
1358 }
1359
1360 pub fn scale_y_reverse(self) -> Self {
1361 self.scale_y_continuous(ScaleContinuous::new().with_transform(ScaleTransform::Reverse))
1362 }
1363
1364 pub fn scale_x_datetime(mut self, s: crate::scale::datetime::ScaleDateTime) -> Self {
1365 let s = s.for_aesthetic(crate::aes::Aesthetic::X);
1366 self.scales.push(Box::new(s));
1367 self
1368 }
1369
1370 pub fn scale_y_datetime(mut self, s: crate::scale::datetime::ScaleDateTime) -> Self {
1371 let s = s.for_aesthetic(crate::aes::Aesthetic::Y);
1372 self.scales.push(Box::new(s));
1373 self
1374 }
1375
1376 pub fn scale_size(mut self, s: crate::scale::size::ScaleSizeContinuous) -> Self {
1377 self.scales.push(Box::new(s));
1378 self
1379 }
1380
1381 pub fn scale_alpha(mut self, s: crate::scale::alpha::ScaleAlphaContinuous) -> Self {
1382 self.scales.push(Box::new(s));
1383 self
1384 }
1385
1386 pub fn xlim(self, min: f64, max: f64) -> Self {
1387 self.scale_x_continuous(ScaleContinuous::new().with_limits(min, max))
1388 }
1389
1390 pub fn ylim(self, min: f64, max: f64) -> Self {
1391 self.scale_y_continuous(ScaleContinuous::new().with_limits(min, max))
1392 }
1393
1394 pub fn scale_x_log10(self) -> Self {
1395 self.scale_x_continuous(ScaleContinuous::new().with_transform(ScaleTransform::Log10))
1396 }
1397
1398 pub fn scale_y_log10(self) -> Self {
1399 self.scale_y_continuous(ScaleContinuous::new().with_transform(ScaleTransform::Log10))
1400 }
1401
1402 pub fn scale_x_sqrt(self) -> Self {
1403 self.scale_x_continuous(ScaleContinuous::new().with_transform(ScaleTransform::Sqrt))
1404 }
1405
1406 pub fn scale_y_sqrt(self) -> Self {
1407 self.scale_y_continuous(ScaleContinuous::new().with_transform(ScaleTransform::Sqrt))
1408 }
1409
1410 pub fn scale_x_log2(self) -> Self {
1411 self.scale_x_continuous(ScaleContinuous::new().with_transform(ScaleTransform::Log2))
1412 }
1413
1414 pub fn scale_y_log2(self) -> Self {
1415 self.scale_y_continuous(ScaleContinuous::new().with_transform(ScaleTransform::Log2))
1416 }
1417
1418 pub fn scale_x_ln(self) -> Self {
1419 self.scale_x_continuous(ScaleContinuous::new().with_transform(ScaleTransform::Ln))
1420 }
1421
1422 pub fn scale_y_ln(self) -> Self {
1423 self.scale_y_continuous(ScaleContinuous::new().with_transform(ScaleTransform::Ln))
1424 }
1425
1426 pub fn scale_x_logit(self) -> Self {
1428 self.scale_x_continuous(ScaleContinuous::new().with_transform(ScaleTransform::Logit))
1429 }
1430
1431 pub fn scale_y_logit(self) -> Self {
1432 self.scale_y_continuous(ScaleContinuous::new().with_transform(ScaleTransform::Logit))
1433 }
1434
1435 pub fn scale_x_probit(self) -> Self {
1437 self.scale_x_continuous(ScaleContinuous::new().with_transform(ScaleTransform::Probit))
1438 }
1439
1440 pub fn scale_y_probit(self) -> Self {
1441 self.scale_y_continuous(ScaleContinuous::new().with_transform(ScaleTransform::Probit))
1442 }
1443
1444 pub fn scale_x_pseudo_log(self) -> Self {
1446 self.scale_x_continuous(ScaleContinuous::new().with_transform(ScaleTransform::PseudoLog))
1447 }
1448
1449 pub fn scale_y_pseudo_log(self) -> Self {
1450 self.scale_y_continuous(ScaleContinuous::new().with_transform(ScaleTransform::PseudoLog))
1451 }
1452
1453 pub fn scale_x_reciprocal(self) -> Self {
1455 self.scale_x_continuous(ScaleContinuous::new().with_transform(ScaleTransform::Reciprocal))
1456 }
1457
1458 pub fn scale_y_reciprocal(self) -> Self {
1459 self.scale_y_continuous(ScaleContinuous::new().with_transform(ScaleTransform::Reciprocal))
1460 }
1461
1462 pub fn scale_x_exp(self) -> Self {
1464 self.scale_x_continuous(ScaleContinuous::new().with_transform(ScaleTransform::Exp))
1465 }
1466
1467 pub fn scale_y_exp(self) -> Self {
1468 self.scale_y_continuous(ScaleContinuous::new().with_transform(ScaleTransform::Exp))
1469 }
1470
1471 pub fn scale_x_boxcox(self, lambda: f64) -> Self {
1473 self.scale_x_continuous(
1474 ScaleContinuous::new().with_transform(ScaleTransform::BoxCox(lambda)),
1475 )
1476 }
1477
1478 pub fn scale_y_boxcox(self, lambda: f64) -> Self {
1479 self.scale_y_continuous(
1480 ScaleContinuous::new().with_transform(ScaleTransform::BoxCox(lambda)),
1481 )
1482 }
1483
1484 pub fn facet_wrap(mut self, var: &str, ncol: Option<usize>) -> Self {
1487 self.facet = Facet::Wrap {
1488 var: var.to_string(),
1489 ncol,
1490 scales: FacetScales::Fixed,
1491 labeller: FacetLabeller::default(),
1492 };
1493 self
1494 }
1495
1496 pub fn facet_wrap_free(mut self, var: &str, ncol: Option<usize>, scales: FacetScales) -> Self {
1497 self.facet = Facet::Wrap {
1498 var: var.to_string(),
1499 ncol,
1500 scales,
1501 labeller: FacetLabeller::default(),
1502 };
1503 self
1504 }
1505
1506 pub fn facet_wrap_labeller(
1507 mut self,
1508 var: &str,
1509 ncol: Option<usize>,
1510 labeller: FacetLabeller,
1511 ) -> Self {
1512 self.facet = Facet::Wrap {
1513 var: var.to_string(),
1514 ncol,
1515 scales: FacetScales::Fixed,
1516 labeller,
1517 };
1518 self
1519 }
1520
1521 pub fn facet_grid(mut self, row: Option<&str>, col: Option<&str>) -> Self {
1522 self.facet = Facet::Grid {
1523 row_var: row.map(String::from),
1524 col_var: col.map(String::from),
1525 scales: FacetScales::Fixed,
1526 labeller: FacetLabeller::default(),
1527 space: FacetSpace::Fixed,
1528 };
1529 self
1530 }
1531
1532 pub fn facet_grid_free(
1533 mut self,
1534 row: Option<&str>,
1535 col: Option<&str>,
1536 scales: FacetScales,
1537 ) -> Self {
1538 self.facet = Facet::Grid {
1539 row_var: row.map(String::from),
1540 col_var: col.map(String::from),
1541 scales,
1542 labeller: FacetLabeller::default(),
1543 space: FacetSpace::Fixed,
1544 };
1545 self
1546 }
1547
1548 pub fn facet_grid_multi(
1552 mut self,
1553 row: Option<&str>,
1554 cols: &[&str],
1555 scales: FacetScales,
1556 space: FacetSpace,
1557 ) -> Self {
1558 let col_var = if cols.len() > 1 {
1559 let n = self.data.nrows();
1561 let mut combined = Vec::with_capacity(n);
1562 for i in 0..n {
1563 let parts: Vec<String> = cols
1564 .iter()
1565 .map(|c| {
1566 self.data
1567 .column(c)
1568 .and_then(|col| col.get(i))
1569 .map(|v| v.to_group_key())
1570 .unwrap_or_default()
1571 })
1572 .collect();
1573 combined.push(crate::data::Value::Str(parts.join(" . ")));
1574 }
1575 let name = "__facet_cols__".to_string();
1576 self.data.add_column(name.clone(), combined);
1577 Some(name)
1578 } else {
1579 cols.first().map(|s| s.to_string())
1580 };
1581 self.facet = Facet::Grid {
1582 row_var: row.map(String::from),
1583 col_var,
1584 scales,
1585 labeller: FacetLabeller::default(),
1586 space,
1587 };
1588 self
1589 }
1590
1591 pub fn facet_grid_space(
1594 mut self,
1595 row: Option<&str>,
1596 col: Option<&str>,
1597 scales: FacetScales,
1598 space: FacetSpace,
1599 ) -> Self {
1600 self.facet = Facet::Grid {
1601 row_var: row.map(String::from),
1602 col_var: col.map(String::from),
1603 scales,
1604 labeller: FacetLabeller::default(),
1605 space,
1606 };
1607 self
1608 }
1609
1610 pub fn facet_grid_labeller(
1611 mut self,
1612 row: Option<&str>,
1613 col: Option<&str>,
1614 labeller: FacetLabeller,
1615 ) -> Self {
1616 self.facet = Facet::Grid {
1617 row_var: row.map(String::from),
1618 col_var: col.map(String::from),
1619 scales: FacetScales::Fixed,
1620 labeller,
1621 space: FacetSpace::Fixed,
1622 };
1623 self
1624 }
1625
1626 pub fn coord_flip(mut self) -> Self {
1629 self.coord = Box::new(CoordFlip);
1630 self
1631 }
1632
1633 pub fn coord_fixed(mut self, ratio: f64) -> Self {
1634 self.coord = Box::new(CoordFixed::new(ratio));
1635 self
1636 }
1637
1638 #[cfg(feature = "sf")]
1642 pub fn coord_sf(mut self) -> Self {
1643 self.coord = Box::new(crate::coord::sf::CoordSf::new());
1644 self
1645 }
1646
1647 pub fn coord_trans(mut self, x: Option<ScaleTransform>, y: Option<ScaleTransform>) -> Self {
1652 self.coord = Box::new(crate::coord::trans::CoordTrans::new(x, y));
1653 self
1654 }
1655
1656 pub fn coord_trans_y(self, y: ScaleTransform) -> Self {
1658 self.coord_trans(None, Some(y))
1659 }
1660
1661 pub fn coord_trans_x(self, x: ScaleTransform) -> Self {
1663 self.coord_trans(Some(x), None)
1664 }
1665
1666 pub fn coord_cartesian_zoom(
1668 mut self,
1669 xlim: Option<(f64, f64)>,
1670 ylim: Option<(f64, f64)>,
1671 ) -> Self {
1672 let mut c = CoordCartesian::new();
1673 if let Some((min, max)) = xlim {
1674 c = c.xlim(min, max);
1675 }
1676 if let Some((min, max)) = ylim {
1677 c = c.ylim(min, max);
1678 }
1679 self.coord = Box::new(c);
1680 self
1681 }
1682
1683 pub fn coord_polar(mut self) -> Self {
1684 self.coord = Box::new(CoordPolar::new());
1685 self
1686 }
1687
1688 pub fn coord_radar(mut self) -> Self {
1692 self.coord = Box::new(crate::coord::radar::CoordRadar::new());
1693 self
1694 }
1695
1696 pub fn coord_radar_with(mut self, coord: crate::coord::radar::CoordRadar) -> Self {
1697 self.coord = Box::new(coord);
1698 self
1699 }
1700
1701 pub fn coord_polar_with(mut self, coord: CoordPolar) -> Self {
1702 self.coord = Box::new(coord);
1703 self
1704 }
1705
1706 pub fn theme(mut self, theme: Theme) -> Self {
1711 self.apply_preset(theme);
1712 self
1713 }
1714
1715 fn apply_preset(&mut self, theme: Theme) {
1716 let primary = self.theme.primary;
1717 self.theme = theme;
1718 if self.theme.primary.is_none() {
1719 self.theme.primary = primary;
1720 }
1721 }
1722
1723 pub fn axis_text_x_angle(mut self, degrees: f64) -> Self {
1727 self.theme.axis_text_x.angle = degrees;
1728 self
1729 }
1730
1731 pub fn axis_text_y_angle(mut self, degrees: f64) -> Self {
1733 self.theme.axis_text_y.angle = degrees;
1734 self
1735 }
1736
1737 pub fn axis_text_x_dodge(mut self, n: usize) -> Self {
1740 self.theme.axis_text_x_dodge = n.max(1);
1741 self
1742 }
1743
1744 pub fn aspect_ratio(mut self, ratio: f64) -> Self {
1747 self.theme.aspect_ratio = Some(ratio);
1748 self
1749 }
1750
1751 pub fn panel_ontop(mut self) -> Self {
1753 self.theme.panel_ontop = true;
1754 self
1755 }
1756
1757 pub fn axis_minor_ticks(mut self) -> Self {
1759 self.theme.axis_minor_ticks = true;
1760 self
1761 }
1762
1763 pub fn title_position(mut self, pos: crate::theme::TitlePosition) -> Self {
1766 self.theme.title_position = pos;
1767 self
1768 }
1769
1770 pub fn tag_position(mut self, pos: crate::theme::TagPosition) -> Self {
1772 self.theme.tag_position = pos;
1773 self
1774 }
1775
1776 pub fn legend_direction(mut self, dir: crate::theme::LegendDirection) -> Self {
1778 self.theme.legend_direction = Some(dir);
1779 self
1780 }
1781
1782 pub fn legend_position_inside(mut self, x: f64, y: f64) -> Self {
1789 self.theme.legend_position = crate::theme::LegendPosition::Inside(x, y);
1790 self
1791 }
1792
1793 pub fn legend_position(mut self, pos: crate::theme::LegendPosition) -> Self {
1795 self.theme.legend_position = pos;
1796 self
1797 }
1798
1799 pub fn primary_color(mut self, color: (u8, u8, u8)) -> Self {
1800 self.theme.primary = Some(color);
1801 self
1802 }
1803
1804 pub fn theme_minimal(mut self) -> Self {
1805 self.apply_preset(crate::theme::presets::theme_minimal());
1806 self
1807 }
1808
1809 pub fn theme_bw(mut self) -> Self {
1810 self.apply_preset(crate::theme::presets::theme_bw());
1811 self
1812 }
1813
1814 pub fn theme_gray(mut self) -> Self {
1815 self.apply_preset(crate::theme::presets::theme_gray());
1816 self
1817 }
1818
1819 pub fn theme_classic(mut self) -> Self {
1820 self.apply_preset(crate::theme::presets::theme_classic());
1821 self
1822 }
1823
1824 pub fn theme_pubr(mut self) -> Self {
1826 self.apply_preset(crate::theme::presets::theme_pubr());
1827 self
1828 }
1829
1830 pub fn theme_linedraw(mut self) -> Self {
1831 self.apply_preset(crate::theme::presets::theme_linedraw());
1832 self
1833 }
1834
1835 pub fn theme_light(mut self) -> Self {
1836 self.apply_preset(crate::theme::presets::theme_light());
1837 self
1838 }
1839
1840 pub fn theme_dark(mut self) -> Self {
1841 self.apply_preset(crate::theme::presets::theme_dark());
1842 self
1843 }
1844
1845 pub fn theme_void(mut self) -> Self {
1846 self.apply_preset(crate::theme::presets::theme_void());
1847 self
1848 }
1849
1850 pub fn theme_update(mut self, update: crate::theme::ThemeUpdate) -> Self {
1853 self.theme = self.theme.update(update);
1854 self
1855 }
1856
1857 pub fn guides(mut self, guide: crate::guide::config::GuideLegend) -> Self {
1861 self.guide_legend = guide;
1862 self
1863 }
1864
1865 pub fn labs(mut self, labels: Labels) -> Self {
1868 if labels.title.is_some() {
1869 self.labels.title = labels.title;
1870 }
1871 if labels.subtitle.is_some() {
1872 self.labels.subtitle = labels.subtitle;
1873 }
1874 if labels.x.is_some() {
1875 self.labels.x = labels.x;
1876 }
1877 if labels.y.is_some() {
1878 self.labels.y = labels.y;
1879 }
1880 if labels.caption.is_some() {
1881 self.labels.caption = labels.caption;
1882 }
1883 if labels.tag.is_some() {
1884 self.labels.tag = labels.tag;
1885 }
1886 self
1887 }
1888
1889 pub fn title(mut self, title: &str) -> Self {
1890 self.labels.title = Some(title.to_string());
1891 self
1892 }
1893
1894 pub fn tag(mut self, tag: &str) -> Self {
1897 self.labels.tag = Some(tag.to_string());
1898 self
1899 }
1900
1901 pub fn subtitle(mut self, subtitle: &str) -> Self {
1902 self.labels.subtitle = Some(subtitle.to_string());
1903 self
1904 }
1905
1906 pub fn xlab(mut self, label: &str) -> Self {
1907 self.labels.x = Some(label.to_string());
1908 self
1909 }
1910
1911 pub fn ylab(mut self, label: &str) -> Self {
1912 self.labels.y = Some(label.to_string());
1913 self
1914 }
1915
1916 pub fn caption(mut self, caption: &str) -> Self {
1917 self.labels.caption = Some(caption.to_string());
1918 self
1919 }
1920
1921 pub fn annotate(mut self, annotation: Annotation) -> Self {
1925 self.annotations.push(annotation);
1926 self
1927 }
1928
1929 pub fn annotate_text(self, label: &str, x: f64, y: f64) -> Self {
1931 self.annotate(Annotation::text(label, x, y))
1932 }
1933
1934 pub fn annotate_rect(self, xmin: f64, xmax: f64, ymin: f64, ymax: f64) -> Self {
1936 self.annotate(Annotation::rect(xmin, xmax, ymin, ymax))
1937 }
1938
1939 pub fn annotate_segment(self, x: f64, y: f64, xend: f64, yend: f64) -> Self {
1941 self.annotate(Annotation::segment(x, y, xend, yend))
1942 }
1943
1944 pub fn locale(mut self, locale: crate::locale::Locale) -> Self {
1967 self.locale = Some(locale);
1968 self
1969 }
1970
1971 pub fn try_build(self) -> Result<crate::build::BuiltPlot, GGError> {
1975 PlotBuilder::build(self)
1976 }
1977
1978 pub fn build(self) -> crate::build::BuiltPlot {
1982 self.try_build().expect("plot build failed")
1983 }
1984
1985 #[cfg(all(feature = "plotters", not(target_arch = "wasm32")))]
1989 pub fn save(self, path: &str) -> Result<(), GGError> {
1990 self.save_with_size(path, 800, 600)
1991 }
1992
1993 #[cfg(all(feature = "plotters", not(target_arch = "wasm32")))]
1995 pub fn save_with_size(self, path: &str, w: u32, h: u32) -> Result<(), GGError> {
1996 let (built, layout) = self.prepare(w, h)?;
1997
1998 let ext = path.rsplit('.').next().unwrap_or("svg").to_lowercase();
2000
2001 match ext.as_str() {
2002 "svg" => {
2003 let backend = plotters::prelude::SVGBackend::new(path, (w, h));
2004 Self::render_into(backend.into_drawing_area(), &built, &layout)?;
2005 }
2006 "png" | "bmp" | "gif" | "jpeg" | "jpg" | "tiff" => {
2007 let backend = plotters::prelude::BitMapBackend::new(path, (w, h));
2008 Self::render_into(backend.into_drawing_area(), &built, &layout)?;
2009 }
2010 _ => {
2011 return Err(GGError::UnsupportedFormat(ext));
2012 }
2013 }
2014
2015 Ok(())
2016 }
2017
2018 #[cfg(all(feature = "plotters", not(target_arch = "wasm32")))]
2024 pub fn render_svg(self) -> Result<String, GGError> {
2025 self.render_svg_with_size(800, 600)
2026 }
2027
2028 #[cfg(all(feature = "plotters", not(target_arch = "wasm32")))]
2032 pub fn render_svg_with_size(self, w: u32, h: u32) -> Result<String, GGError> {
2033 let (built, layout) = self.prepare(w, h)?;
2034 let mut buf = String::new();
2035 {
2036 let backend = plotters::prelude::SVGBackend::with_string(&mut buf, (w, h));
2037 Self::render_into(backend.into_drawing_area(), &built, &layout)?;
2038 }
2039 Ok(buf)
2040 }
2041
2042 pub fn render_svg_native(self) -> Result<String, GGError> {
2046 self.render_svg_native_with_size(800, 600)
2047 }
2048
2049 pub fn render_svg_native_with_size(self, w: u32, h: u32) -> Result<String, GGError> {
2057 Ok(self.render_native(w, h)?.0.finish())
2058 }
2059
2060 pub fn render_svg_native_with_warnings(
2065 self,
2066 w: u32,
2067 h: u32,
2068 ) -> Result<(String, Vec<String>), GGError> {
2069 let (backend, warnings, _) = self.render_native(w, h)?;
2070 Ok((backend.finish(), warnings))
2071 }
2072
2073 pub fn render_svg_native_at(self, x: f64, y: f64, w: u32, h: u32) -> Result<String, GGError> {
2085 Ok(self.render_native(w, h)?.0.finish_fragment(x, y))
2086 }
2087
2088 pub fn render_svg_area_with_size(self, w: u32, h: u32) -> Result<(String, [f64; 4]), GGError> {
2092 let (backend, _, pa) = self.render_native(w, h)?;
2093 Ok((backend.finish(), [pa.x, pa.y, pa.width, pa.height]))
2094 }
2095
2096 fn render_native(
2100 self,
2101 w: u32,
2102 h: u32,
2103 ) -> Result<
2104 (
2105 crate::render::svg_backend::SvgBackend,
2106 Vec<String>,
2107 crate::render::Rect,
2108 ),
2109 GGError,
2110 > {
2111 let (built, layout) = self.prepare(w, h)?;
2112 let pa = layout.plot_area.clone();
2113 let mut backend = crate::render::svg_backend::SvgBackend::new(w, h, pa.clone());
2114 backend.set_root_attrs(crate::render::svg_backend::root_data_attrs(&built));
2115 PlotRenderer::render(&built, &mut backend).map_err(GGError::Render)?;
2116 let mut warnings = built.warnings;
2117 warnings.extend(backend.take_warnings());
2118 Ok((backend, warnings, pa))
2119 }
2120
2121 #[cfg(feature = "canvas")]
2126 pub fn render_rgba_with_size(self, w: u32, h: u32) -> Result<(u32, u32, Vec<u8>), GGError> {
2127 let (built, layout) = self.prepare(w, h)?;
2128 let mut backend =
2129 crate::render::pixel_backend::PixelBackend::new(w, h, layout.plot_area.clone());
2130 PlotRenderer::render(&built, &mut backend).map_err(GGError::Render)?;
2131 let (ow, oh) = backend.dimensions();
2132 Ok((ow, oh, backend.into_rgba()))
2133 }
2134
2135 #[cfg(feature = "canvas")]
2139 pub fn render_rgba_area_with_size(
2140 self,
2141 w: u32,
2142 h: u32,
2143 ) -> Result<(Vec<u8>, [f64; 4]), GGError> {
2144 let (built, layout) = self.prepare(w, h)?;
2145 let pa = layout.plot_area.clone();
2146 let mut backend = crate::render::pixel_backend::PixelBackend::new(w, h, pa.clone());
2147 PlotRenderer::render(&built, &mut backend).map_err(GGError::Render)?;
2148 Ok((backend.into_rgba(), [pa.x, pa.y, pa.width, pa.height]))
2149 }
2150
2151 #[cfg(feature = "canvas")]
2155 pub fn render_png_raster_with_size(self, w: u32, h: u32) -> Result<Vec<u8>, GGError> {
2156 let (built, layout) = self.prepare(w, h)?;
2157 let mut backend =
2158 crate::render::pixel_backend::PixelBackend::new(w, h, layout.plot_area.clone());
2159 PlotRenderer::render(&built, &mut backend).map_err(GGError::Render)?;
2160 backend.into_png().map_err(GGError::Render)
2161 }
2162
2163 #[cfg(all(feature = "plotters", not(target_arch = "wasm32")))]
2170 pub fn render_png(self) -> Result<Vec<u8>, GGError> {
2171 self.render_png_with_size(800, 600)
2172 }
2173
2174 #[cfg(all(feature = "plotters", not(target_arch = "wasm32")))]
2177 pub fn render_png_with_size(self, w: u32, h: u32) -> Result<Vec<u8>, GGError> {
2178 let (built, layout) = self.prepare(w, h)?;
2179
2180 let mut rgb = vec![0u8; (w as usize) * (h as usize) * 3];
2183 {
2184 let backend = plotters::prelude::BitMapBackend::with_buffer(&mut rgb, (w, h));
2185 Self::render_into(backend.into_drawing_area(), &built, &layout)?;
2186 }
2187
2188 let img = image::RgbImage::from_raw(w, h, rgb).ok_or_else(|| {
2189 GGError::Render(RenderError::BackendError(
2190 "PNG buffer size mismatch".to_string(),
2191 ))
2192 })?;
2193 let mut out = std::io::Cursor::new(Vec::new());
2194 img.write_to(&mut out, image::ImageOutputFormat::Png)
2195 .map_err(|e| GGError::Render(RenderError::BackendError(format!("{:?}", e))))?;
2196 Ok(out.into_inner())
2197 }
2198
2199 pub(crate) fn prepare(
2201 self,
2202 w: u32,
2203 h: u32,
2204 ) -> Result<(crate::build::BuiltPlot, PlotLayout), GGError> {
2205 let (mut built, meta) = self.build_for_render()?;
2206 let layout = Self::layout_built(&mut built, &meta, w, h);
2207 Ok((built, layout))
2208 }
2209
2210 pub(crate) fn build_for_render(self) -> Result<(crate::build::BuiltPlot, RenderMeta), GGError> {
2213 let plot = self;
2214
2215 let has_title = plot.labels.title.is_some();
2216 let has_subtitle = plot.labels.subtitle.is_some();
2217 let has_caption = plot.labels.caption.is_some();
2218 let has_legend = plot.has_legend_mapping();
2219 let x_label = plot.labels.x.clone();
2220 let y_label = plot.labels.y.clone();
2221
2222 let mut built = PlotBuilder::build(plot)?;
2223
2224 built.theme.resolve_inheritance();
2226
2227 if let Some(ref label) = x_label {
2229 if let Some(s) = built.scales.get_mut(&crate::aes::Aesthetic::X) {
2230 s.set_name(label);
2231 }
2232 }
2233 if let Some(ref label) = y_label {
2234 if let Some(s) = built.scales.get_mut(&crate::aes::Aesthetic::Y) {
2235 s.set_name(label);
2236 }
2237 }
2238
2239 Ok((
2240 built,
2241 RenderMeta {
2242 has_title,
2243 has_subtitle,
2244 has_caption,
2245 has_legend,
2246 },
2247 ))
2248 }
2249
2250 pub(crate) fn layout_built(
2253 built: &mut crate::build::BuiltPlot,
2254 meta: &RenderMeta,
2255 w: u32,
2256 h: u32,
2257 ) -> PlotLayout {
2258 let RenderMeta {
2259 has_title,
2260 has_subtitle,
2261 has_caption,
2262 has_legend,
2263 } = *meta;
2264 let x_axis_top = built
2265 .scales
2266 .get(&crate::aes::Aesthetic::X)
2267 .map(|s| s.axis_position_opposite())
2268 .unwrap_or(false);
2269
2270 let flipped = built.coord.is_flipped();
2274 let h_aes = if flipped {
2275 crate::aes::Aesthetic::Y
2276 } else {
2277 crate::aes::Aesthetic::X
2278 };
2279 let v_aes = if flipped {
2280 crate::aes::Aesthetic::X
2281 } else {
2282 crate::aes::Aesthetic::Y
2283 };
2284
2285 let x_rot: Option<(f64, f64)> =
2289 if built.theme.axis_text_x.visible && built.theme.axis_text_x.angle.abs() < 1.0 {
2290 built.scales.get(&h_aes).and_then(|hs| {
2291 if !hs.is_discrete() {
2292 return None;
2293 }
2294 let breaks = hs.breaks();
2295 let n = breaks.len().max(1) as f64;
2296 let max_ch = breaks
2297 .iter()
2298 .map(|(_, l)| l.chars().count())
2299 .max()
2300 .unwrap_or(0) as f64;
2301 let font = built.theme.axis_text_x.size;
2302 let label_w = max_ch * font * 0.6; let spacing = 0.9 * w as f64 / n; if label_w <= spacing {
2305 return None; }
2307 let vertical = label_w * 0.707 > spacing;
2311 let angle = if vertical { 270.0 } else { 45.0 };
2312 let drop = if vertical { label_w } else { label_w * 0.707 };
2313 Some((angle, drop + font + 4.0))
2314 })
2315 } else {
2316 None
2317 };
2318 let x_label_height = x_rot.map(|(_, drop)| drop);
2319 if let Some((angle, _)) = x_rot {
2320 built.theme.axis_text_x.angle = angle;
2321 }
2322
2323 let y_label_width = if built.theme.axis_text_y.visible {
2327 built.scales.get(&v_aes).map(|vs| {
2328 let max_ch = vs
2329 .breaks()
2330 .iter()
2331 .map(|(_, l)| l.chars().count())
2332 .max()
2333 .unwrap_or(0);
2334 let measured = max_ch as f64 * built.theme.axis_text_y.size * 0.6 + 4.0;
2335 let default = built.theme.axis_text_y.size * 3.5 + 4.0;
2336 measured.max(default).min(0.35 * w as f64)
2337 })
2338 } else {
2339 None
2340 };
2341
2342 PlotLayout::compute_full(
2343 w as f64,
2344 h as f64,
2345 &built.theme,
2346 has_title,
2347 has_subtitle,
2348 has_caption,
2349 has_legend,
2350 x_axis_top,
2351 y_label_width,
2352 x_label_height,
2353 )
2354 }
2355
2356 #[cfg(all(feature = "plotters", not(target_arch = "wasm32")))]
2359 fn render_into<DB>(
2360 area: plotters::drawing::DrawingArea<DB, plotters::coord::Shift>,
2361 built: &crate::build::BuiltPlot,
2362 layout: &PlotLayout,
2363 ) -> Result<(), GGError>
2364 where
2365 DB: plotters::prelude::DrawingBackend,
2366 DB::ErrorType: 'static,
2367 {
2368 area.fill(&plotters::prelude::WHITE)
2369 .map_err(|e| GGError::Render(RenderError::BackendError(format!("{:?}", e))))?;
2370 let mut adapter = PlottersAdapter::new(&area, layout.plot_area.clone());
2371 PlotRenderer::render(built, &mut adapter).map_err(GGError::Render)?;
2372 area.present()
2373 .map_err(|e| GGError::Render(RenderError::BackendError(format!("{:?}", e))))?;
2374 Ok(())
2375 }
2376
2377 #[cfg(all(feature = "plotters", not(target_arch = "wasm32")))]
2380 pub fn ggsave(
2381 self,
2382 path: &str,
2383 width_inches: f64,
2384 height_inches: f64,
2385 dpi: f64,
2386 ) -> Result<(), GGError> {
2387 let w = (width_inches * dpi) as u32;
2388 let h = (height_inches * dpi) as u32;
2389 self.save_with_size(path, w, h)
2390 }
2391
2392 fn has_legend_mapping(&self) -> bool {
2393 self.mapping.mappings.iter().any(|m| {
2394 matches!(
2395 m.aesthetic,
2396 crate::aes::Aesthetic::Color
2397 | crate::aes::Aesthetic::Fill
2398 | crate::aes::Aesthetic::Shape
2399 | crate::aes::Aesthetic::Linetype
2400 | crate::aes::Aesthetic::Size
2401 | crate::aes::Aesthetic::Alpha
2402 )
2403 })
2404 }
2405}
2406
2407#[derive(Clone, Copy, Debug)]
2409pub(crate) struct RenderMeta {
2410 pub(crate) has_title: bool,
2411 pub(crate) has_subtitle: bool,
2412 pub(crate) has_caption: bool,
2413 pub(crate) has_legend: bool,
2414}
2415
2416#[derive(Debug)]
2418pub enum GGError {
2419 Render(RenderError),
2420 UnsupportedFormat(String),
2421 Io(std::io::Error),
2422 ValidationError(String),
2423}
2424
2425impl std::fmt::Display for GGError {
2426 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2427 match self {
2428 GGError::Render(e) => write!(f, "Render error: {e}"),
2429 GGError::UnsupportedFormat(ext) => write!(f, "Unsupported output format: {ext}"),
2430 GGError::Io(e) => write!(f, "IO error: {e}"),
2431 GGError::ValidationError(msg) => write!(f, "Validation error: {msg}"),
2432 }
2433 }
2434}
2435
2436impl std::error::Error for GGError {}