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::density_ridges::GeomDensityRidges;
27use crate::geom::dotplot::GeomDotplot;
28use crate::geom::errorbar::GeomErrorbar;
29use crate::geom::freqpoly::GeomFreqpoly;
30use crate::geom::hex::GeomHex;
31use crate::geom::histogram::GeomHistogram;
32use crate::geom::jitter::GeomJitter;
33use crate::geom::line::GeomLine;
34use crate::geom::linerange::GeomLinerange;
35use crate::geom::path::GeomPath;
36use crate::geom::point::GeomPoint;
37use crate::geom::pointrange::GeomPointrange;
38use crate::geom::polygon::GeomPolygon;
39use crate::geom::qq::{GeomQQ, GeomQQLine};
40use crate::geom::rect::GeomRect;
41use crate::geom::refline::{GeomAbline, GeomHline, GeomVline};
42use crate::geom::ribbon::GeomRibbon;
43use crate::geom::rug::GeomRug;
44use crate::geom::segment::GeomSegment;
45use crate::geom::smooth::GeomSmooth;
46use crate::geom::spoke::GeomSpoke;
47use crate::geom::step::GeomStep;
48use crate::geom::text::{GeomLabel, GeomText};
49use crate::geom::tile::GeomTile;
50use crate::geom::violin::GeomViolin;
51use crate::geom::{Geom, GeomParams};
52use crate::position::Position;
53use crate::render::layout::PlotLayout;
54#[cfg(all(feature = "plotters", not(target_arch = "wasm32")))]
55use crate::render::plotters_backend::PlottersAdapter;
56use crate::render::renderer::PlotRenderer;
57use crate::render::RenderError;
58use crate::scale::continuous::ScaleContinuous;
59use crate::scale::transform::ScaleTransform;
60use crate::scale::Scale;
61use crate::stat::Stat;
62use crate::theme::Theme;
63
64mod stat_layers;
67
68#[derive(Clone, Debug, Default)]
70pub struct Labels {
71 pub title: Option<String>,
72 pub subtitle: Option<String>,
73 pub x: Option<String>,
74 pub y: Option<String>,
75 pub caption: Option<String>,
76 pub tag: Option<String>,
78}
79
80pub struct Layer {
82 pub data: Option<DataFrame>,
83 pub mapping: Aes,
84 pub geom: Box<dyn Geom>,
85 pub stat: Box<dyn Stat>,
86 pub position: Box<dyn Position>,
87 pub params: GeomParams,
88 pub show_legend: Option<bool>,
89 pub explicit_style: bool,
92 pub tooltip_template: Option<String>,
95 pub key_glyph: Option<crate::guide::key::KeyGlyph>,
97 pub show_legend_aes: Vec<(crate::aes::Aesthetic, bool)>,
99}
100
101pub struct GGPlot {
103 pub(crate) data: DataFrame,
104 pub(crate) mapping: Aes,
105 pub(crate) layers: Vec<Layer>,
106 pub(crate) scales: Vec<Box<dyn Scale>>,
107 pub(crate) coord: Box<dyn Coord>,
108 pub(crate) theme: Theme,
109 pub(crate) labels: Labels,
110 pub(crate) facet: Facet,
111 pub(crate) facet_axes: crate::facet::FacetAxes,
113 pub(crate) annotations: Vec<Annotation>,
114 pub(crate) guide_legend: crate::guide::config::GuideLegend,
115 pub(crate) warnings: Vec<String>,
118 pub(crate) legend_bottom_share: Option<f64>,
120 pub(crate) clip: bool,
123 pub(crate) svg_classes: bool,
126 pub(crate) direct_labels: bool,
128 pub(crate) legend_auto: Option<LegendAuto>,
130 pub(crate) default_aspect_ratio: Option<f64>,
133 pub(crate) hide_position_guides: bool,
136 pub(crate) hide_y_guides: bool,
138 pub(crate) locale: Option<crate::locale::Locale>,
140 pub(crate) svg_root_data: bool,
145 pub(crate) root_attrs: Vec<(String, String)>,
148 pub(crate) svg_warnings_attr: bool,
152 pub(crate) svg_formatted_values: bool,
156 pub(crate) layer_svg_attrs: Vec<(usize, String, String)>,
160 pub(crate) svg_title: Option<String>,
165 pub(crate) svg_desc: Option<String>,
170}
171
172impl GGPlot {
173 pub fn qplot(data: impl GGData, x: &str, y: Option<&str>) -> Self {
182 let plot = GGPlot::new(data);
183 match y {
184 Some(y) => plot.aes(Aes::new().x(x).y(y)).geom_point(),
185 None => {
186 let text = plot
187 .data
188 .column(x)
189 .and_then(|c| c.iter().find(|v| !v.is_na()))
190 .is_some_and(|v| matches!(v, Value::Str(_) | Value::Bool(_)));
191 let plot = plot.aes(Aes::new().x(x));
192 if text {
193 plot.geom_bar()
194 } else {
195 plot.geom_histogram()
196 }
197 }
198 }
199 }
200
201 pub fn new(data: impl GGData) -> Self {
202 GGPlot {
203 data: data.into_dataframe(),
204 mapping: Aes::default(),
205 layers: Vec::new(),
206 scales: Vec::new(),
207 coord: Box::new(CoordCartesian::new()),
208 theme: Theme::default(),
209 labels: Labels::default(),
210 facet: Facet::default(),
211 facet_axes: crate::facet::FacetAxes::default(),
212 annotations: Vec::new(),
213 guide_legend: crate::guide::config::GuideLegend::default(),
214 warnings: Vec::new(),
215 legend_bottom_share: None,
216 clip: true,
217 svg_classes: false,
218 direct_labels: false,
219 legend_auto: None,
220 default_aspect_ratio: None,
221 hide_position_guides: false,
222 hide_y_guides: false,
223 locale: None,
224 svg_root_data: true,
225 root_attrs: Vec::new(),
226 svg_warnings_attr: false,
227 svg_formatted_values: false,
228 layer_svg_attrs: Vec::new(),
229 svg_title: None,
230 svg_desc: None,
231 }
232 }
233
234 pub fn aes(mut self, mapping: Aes) -> Self {
236 self.warnings.extend(mapping.warnings.iter().cloned());
237 self.mapping = mapping;
238 self
239 }
240
241 pub fn geom_point(self) -> Self {
244 self.add_geom(GeomPoint::default())
245 }
246
247 pub fn geom_point_with(self, geom: GeomPoint) -> Self {
248 self.add_geom_with(geom)
249 }
250
251 pub fn geom_line(self) -> Self {
252 self.add_geom(GeomLine::default())
253 }
254
255 pub fn geom_line_with(self, geom: GeomLine) -> Self {
256 self.add_geom_with(geom)
257 }
258
259 pub fn geom_bar(self) -> Self {
260 self.add_geom(GeomBar::default())
261 }
262
263 pub fn geom_bar_with(self, geom: GeomBar) -> Self {
264 self.add_geom_with(geom)
265 }
266
267 pub fn geom_histogram(self) -> Self {
268 self.add_geom(GeomHistogram::default())
269 }
270
271 pub fn geom_histogram_with(self, geom: GeomHistogram) -> Self {
272 self.add_geom_with(geom)
273 }
274
275 pub fn geom_boxplot(self) -> Self {
276 self.add_geom(GeomBoxplot::default())
277 }
278
279 pub fn geom_boxplot_with(self, geom: GeomBoxplot) -> Self {
280 self.add_geom_with(geom)
281 }
282
283 pub fn geom_smooth(self) -> Self {
284 self.add_geom(GeomSmooth::default())
285 }
286
287 pub fn geom_smooth_with(self, geom: GeomSmooth) -> Self {
288 self.add_geom_with(geom)
289 }
290
291 pub fn geom_col(self) -> Self {
292 self.add_geom(GeomCol::default())
293 }
294
295 pub fn geom_col_with(self, geom: GeomCol) -> Self {
296 self.add_geom_with(geom)
297 }
298
299 pub fn geom_hline(self, yintercept: f64) -> Self {
303 self.add_refline(
304 GeomHline::new(yintercept),
305 false,
306 &[("yintercept", yintercept)],
307 )
308 }
309
310 pub fn geom_hline_with(self, geom: GeomHline) -> Self {
312 let y = geom.yintercept;
313 self.add_refline(geom, true, &[("yintercept", y)])
314 }
315
316 pub fn geom_hline_aes(self, mapping: Aes) -> Self {
340 self.add_geom(GeomHline::mapped()).layer_aes(mapping)
341 }
342
343 pub fn geom_hline_aes_with(self, geom: GeomHline, mapping: Aes) -> Self {
345 self.add_geom_with(geom).layer_aes(mapping)
346 }
347
348 pub fn geom_vline(self, xintercept: f64) -> Self {
351 self.add_refline(
352 GeomVline::new(xintercept),
353 false,
354 &[("xintercept", xintercept)],
355 )
356 }
357
358 pub fn geom_vline_with(self, geom: GeomVline) -> Self {
360 let x = geom.xintercept;
361 self.add_refline(geom, true, &[("xintercept", x)])
362 }
363
364 pub fn geom_vline_aes(self, mapping: Aes) -> Self {
367 self.add_geom(GeomVline::mapped()).layer_aes(mapping)
368 }
369
370 pub fn geom_vline_aes_with(self, geom: GeomVline, mapping: Aes) -> Self {
372 self.add_geom_with(geom).layer_aes(mapping)
373 }
374
375 pub fn geom_abline(self, slope: f64, intercept: f64) -> Self {
378 self.add_refline(
379 GeomAbline::new(slope, intercept),
380 false,
381 &[("slope", slope), ("intercept", intercept)],
382 )
383 }
384
385 pub fn geom_abline_with(self, geom: GeomAbline) -> Self {
387 let (b, a) = (geom.slope, geom.intercept);
388 self.add_refline(geom, true, &[("slope", b), ("intercept", a)])
389 }
390
391 pub fn geom_abline_aes(self, mapping: Aes) -> Self {
394 self.add_geom(GeomAbline::mapped()).layer_aes(mapping)
395 }
396
397 pub fn geom_abline_aes_with(self, geom: GeomAbline, mapping: Aes) -> Self {
399 self.add_geom_with(geom).layer_aes(mapping)
400 }
401
402 fn add_refline(
405 self,
406 geom: impl Geom + 'static,
407 explicit: bool,
408 values: &[(&str, f64)],
409 ) -> Self {
410 let mut data = DataFrame::new();
411 let mut mapping = Aes::new();
412 for (col, v) in values {
413 data.add_column(col.to_string(), vec![Value::Float(*v)]);
414 mapping = match *col {
415 "xintercept" => mapping.xintercept(col),
416 "yintercept" => mapping.yintercept(col),
417 "slope" => mapping.slope(col),
418 _ => mapping.intercept(col),
419 };
420 }
421 let plot = if explicit {
422 self.add_geom_with(geom)
423 } else {
424 self.add_geom(geom)
425 };
426 plot.layer_aes(mapping).layer_data(data)
427 }
428
429 pub fn geom_text(self) -> Self {
430 self.add_geom(GeomText::default())
431 }
432
433 pub fn geom_text_with(self, geom: GeomText) -> Self {
434 self.add_geom_with(geom)
435 }
436
437 #[cfg(feature = "ggpubr")]
442 pub fn stat_cor(self) -> Self {
443 self.geom_text().stat(crate::stat::cor::StatCor::default())
444 }
445
446 #[cfg(feature = "ggpubr")]
449 pub fn stat_cor_with(self, stat: crate::stat::cor::StatCor) -> Self {
450 self.geom_text().stat(stat)
451 }
452
453 #[cfg(feature = "ggpubr")]
458 pub fn stat_compare_means(self) -> Self {
459 self.geom_text()
460 .stat(crate::stat::compare_means::StatCompareMeans::default())
461 }
462
463 #[cfg(feature = "ggpubr")]
466 pub fn stat_compare_means_with(
467 self,
468 stat: crate::stat::compare_means::StatCompareMeans,
469 ) -> Self {
470 self.geom_text().stat(stat)
471 }
472
473 #[cfg(feature = "ggpubr")]
479 pub fn stat_compare_means_pairwise(self, comparisons: &[(&str, &str)]) -> Self {
480 self.stat_compare_means_pairwise_with(
481 crate::stat::compare_means::CompareMethod::Auto,
482 comparisons,
483 )
484 }
485
486 #[cfg(feature = "ggpubr")]
489 pub fn stat_compare_means_pairwise_with(
490 self,
491 method: crate::stat::compare_means::CompareMethod,
492 comparisons: &[(&str, &str)],
493 ) -> Self {
494 let col_for = |a: crate::aes::Aesthetic| {
496 self.mapping
497 .mappings
498 .iter()
499 .find(|m| m.aesthetic == a)
500 .map(|m| m.column.clone())
501 };
502 let (xcol, ycol) = match (
503 col_for(crate::aes::Aesthetic::X),
504 col_for(crate::aes::Aesthetic::Y),
505 ) {
506 (Some(x), Some(y)) => (x, y),
507 _ => return self,
508 };
509 let (xc, yc) = match (self.data.column(&xcol), self.data.column(&ycol)) {
510 (Some(x), Some(y)) => (x, y),
511 _ => return self,
512 };
513
514 let mut groups: Vec<(String, Vec<f64>)> = Vec::new();
516 let mut ymax = f64::NEG_INFINITY;
517 let mut ymin = f64::INFINITY;
518 for (xv, yv) in xc.iter().zip(yc.iter()) {
519 let y = match yv.as_f64() {
520 Some(y) if y.is_finite() => y,
521 _ => continue,
522 };
523 ymax = ymax.max(y);
524 ymin = ymin.min(y);
525 let key = xv.to_group_key();
526 if let Some(g) = groups.iter_mut().find(|(k, _)| *k == key) {
527 g.1.push(y);
528 } else {
529 groups.push((key, vec![y]));
530 }
531 }
532 if groups.len() < 2 {
533 return self;
534 }
535 let step = if ymax > ymin {
536 (ymax - ymin) * 0.12
537 } else {
538 1.0
539 };
540
541 let (mut xmin_v, mut xmax_v, mut y_v, mut label_v) =
543 (Vec::new(), Vec::new(), Vec::new(), Vec::new());
544 let mut placed = 0usize;
545 for (a, b) in comparisons {
546 let ga = groups.iter().find(|(k, _)| k == a).map(|g| &g.1);
547 let gb = groups.iter().find(|(k, _)| k == b).map(|g| &g.1);
548 let (ga, gb) = match (ga, gb) {
549 (Some(x), Some(y)) if x.len() >= 2 && y.len() >= 2 => (x, y),
550 _ => continue,
551 };
552 let p = match crate::stat::compare_means::pairwise_p(method, ga, gb) {
553 Some(p) => p,
554 None => continue,
555 };
556 xmin_v.push(Value::Str((*a).to_string()));
557 xmax_v.push(Value::Str((*b).to_string()));
558 y_v.push(Value::Float(ymax + step * (placed as f64 + 1.0)));
559 label_v.push(Value::Str(crate::stat::cor::format_p_value(p)));
560 placed += 1;
561 }
562 if xmin_v.is_empty() {
563 return self;
564 }
565
566 let data = vec![
567 ("xmin".to_string(), xmin_v),
568 ("xmax".to_string(), xmax_v),
569 ("y".to_string(), y_v),
570 ("label".to_string(), label_v),
571 ];
572 self.add_geom(crate::geom::bracket::GeomBracket::default())
573 .layer_data(data)
574 .layer_aes(Aes::new().xmin("xmin").xmax("xmax").y("y").label("label"))
575 }
576
577 pub fn geom_bracket(self, xmin: &str, xmax: &str, y: f64, label: &str) -> Self {
582 self.geom_bracket_many(
583 crate::geom::bracket::GeomBracket::default(),
584 &[(xmin, xmax, y, label)],
585 )
586 }
587
588 pub fn geom_bracket_many(
592 self,
593 geom: crate::geom::bracket::GeomBracket,
594 brackets: &[(&str, &str, f64, &str)],
595 ) -> Self {
596 let xmin = brackets
597 .iter()
598 .map(|b| Value::Str(b.0.to_string()))
599 .collect::<Vec<_>>();
600 let xmax = brackets
601 .iter()
602 .map(|b| Value::Str(b.1.to_string()))
603 .collect::<Vec<_>>();
604 let y = brackets
605 .iter()
606 .map(|b| Value::Float(b.2))
607 .collect::<Vec<_>>();
608 let label = brackets
609 .iter()
610 .map(|b| Value::Str(b.3.to_string()))
611 .collect::<Vec<_>>();
612 let data = vec![
613 ("xmin".to_string(), xmin),
614 ("xmax".to_string(), xmax),
615 ("y".to_string(), y),
616 ("label".to_string(), label),
617 ];
618 self.add_geom(geom)
619 .layer_data(data)
620 .layer_aes(Aes::new().xmin("xmin").xmax("xmax").y("y").label("label"))
621 }
622
623 pub fn geom_bracket_table(
632 mut self,
633 table: impl GGData,
634 spec: crate::geom::bracket::BracketTable,
635 ) -> Self {
636 let table = table.into_dataframe();
637 let col_for = |a: crate::aes::Aesthetic| {
638 self.mapping
639 .mappings
640 .iter()
641 .find(|m| m.aesthetic == a)
642 .map(|m| m.column.clone())
643 };
644 let x_levels: Vec<String> = col_for(crate::aes::Aesthetic::X)
647 .and_then(|c| self.data.column(&c))
648 .filter(|col| col.iter().any(|v| matches!(v, Value::Str(_))))
649 .map(|col| {
650 let mut seen = std::collections::HashSet::new();
651 col.iter()
652 .filter(|v| !v.is_na())
653 .map(|v| v.to_group_key())
654 .filter(|k| seen.insert(k.clone()))
655 .collect()
656 })
657 .unwrap_or_default();
658 let y_range = col_for(crate::aes::Aesthetic::Y)
659 .and_then(|c| self.data.column(&c))
660 .and_then(|col| {
661 let (lo, hi) = col
662 .iter()
663 .filter_map(|v| v.as_f64())
664 .filter(|v| v.is_finite())
665 .fold((f64::INFINITY, f64::NEG_INFINITY), |(lo, hi), v| {
666 (lo.min(v), hi.max(v))
667 });
668 (lo <= hi).then_some((lo, hi))
669 });
670 let mut warnings = Vec::new();
671 let resolved = spec.resolve(&table, &x_levels, y_range, &mut warnings);
672 self.warnings.extend(warnings);
673 match resolved {
674 Some(data) => self
675 .add_geom(crate::geom::bracket::GeomBracket::from(spec.geom))
676 .layer_data(data)
677 .layer_aes(Aes::new().xmin("xmin").xmax("xmax").y("y").label("label")),
678 None => self,
679 }
680 }
681
682 pub fn geom_text_repel(self) -> Self {
687 self.add_geom(crate::geom::repel::GeomTextRepel::default())
688 }
689
690 pub fn geom_text_repel_with(self, geom: crate::geom::repel::GeomTextRepel) -> Self {
693 self.add_geom_with(geom)
694 }
695
696 pub fn geom_label_repel(self) -> Self {
699 self.add_geom(crate::geom::repel::GeomLabelRepel::default())
700 }
701
702 pub fn geom_label_repel_with(self, geom: crate::geom::repel::GeomLabelRepel) -> Self {
704 self.add_geom_with(geom)
705 }
706
707 pub fn geom_label(self) -> Self {
708 self.add_geom(GeomLabel::default())
709 }
710
711 pub fn geom_label_with(self, geom: GeomLabel) -> Self {
712 self.add_geom_with(geom)
713 }
714
715 pub fn geom_area(self) -> Self {
716 self.add_geom(GeomArea::default())
717 }
718
719 pub fn geom_area_with(self, geom: GeomArea) -> Self {
720 self.add_geom_with(geom)
721 }
722
723 pub fn geom_ribbon(self) -> Self {
724 self.add_geom(GeomRibbon::default())
725 }
726
727 pub fn geom_ribbon_with(self, geom: GeomRibbon) -> Self {
728 self.add_geom_with(geom)
729 }
730
731 pub fn geom_errorbar(self) -> Self {
732 self.add_geom(GeomErrorbar::default())
733 }
734
735 pub fn geom_errorbar_with(self, geom: GeomErrorbar) -> Self {
736 self.add_geom_with(geom)
737 }
738
739 pub fn geom_segment(self) -> Self {
740 self.add_geom(GeomSegment::default())
741 }
742
743 pub fn geom_segment_with(self, geom: GeomSegment) -> Self {
744 self.add_geom_with(geom)
745 }
746
747 pub fn geom_density(self) -> Self {
748 self.add_geom(GeomDensity::default())
749 }
750
751 pub fn geom_density_with(self, geom: GeomDensity) -> Self {
752 self.add_geom_with(geom)
753 }
754
755 pub fn geom_rug(self) -> Self {
756 self.add_geom(GeomRug::default())
757 }
758
759 pub fn geom_rug_with(self, geom: GeomRug) -> Self {
760 self.add_geom_with(geom)
761 }
762
763 pub fn geom_jitter(self) -> Self {
764 self.add_geom(GeomJitter::default())
765 }
766
767 pub fn geom_jitter_with(self, geom: GeomJitter) -> Self {
768 self.add_geom_with(geom)
769 }
770
771 pub fn geom_path(self) -> Self {
772 self.add_geom(GeomPath::default())
773 }
774
775 pub fn geom_path_with(self, geom: GeomPath) -> Self {
776 self.add_geom_with(geom)
777 }
778
779 pub fn geom_function(self, fun: impl Fn(f64) -> f64 + Send + Sync + 'static) -> Self {
783 self.geom_line()
784 .stat(crate::stat::function::StatFunction::new(fun))
785 }
786
787 pub fn geom_function_xlim(
789 self,
790 fun: impl Fn(f64) -> f64 + Send + Sync + 'static,
791 lo: f64,
792 hi: f64,
793 ) -> Self {
794 let range = vec![("x".to_string(), vec![Value::Float(lo), Value::Float(hi)])];
795 self.geom_line()
796 .layer_data(range)
797 .layer_aes(Aes::new().x("x"))
798 .stat(crate::stat::function::StatFunction::new(fun).with_xlim(lo, hi))
799 }
800
801 pub fn stat_connect(self, connection: crate::stat::connect::Connection) -> Self {
804 self.geom_path()
805 .stat(crate::stat::connect::StatConnect::new(connection))
806 }
807
808 pub fn stat_unique(self) -> Self {
811 self.geom_point().stat(crate::stat::unique::StatUnique)
812 }
813
814 pub fn stat_manual(
817 self,
818 fun: impl Fn(&crate::data::DataFrame) -> crate::data::DataFrame + Send + Sync + 'static,
819 ) -> Self {
820 self.geom_point()
821 .stat(crate::stat::manual::StatManual::new(fun))
822 }
823
824 pub fn stat_summary_hex(self, fun: crate::stat::summary::SummaryFun) -> Self {
827 self.geom_hex()
828 .stat(crate::stat::binhex::StatSummaryHex::new(fun))
829 }
830
831 #[cfg(feature = "sf")]
835 pub fn stat_sf_coordinates(self) -> Self {
836 self.geom_point()
837 .stat(crate::stat::sf_coordinates::StatSfCoordinates::default())
838 }
839
840 pub fn stat_ellipse(self) -> Self {
842 self.geom_path()
843 .stat(crate::stat::ellipse::StatEllipse::default())
844 }
845
846 pub fn stat_ellipse_level(self, level: f64) -> Self {
848 self.geom_path()
849 .stat(crate::stat::ellipse::StatEllipse::new(level))
850 }
851
852 #[cfg(feature = "regression")]
855 pub fn stat_quantile(mut self, taus: &[f64]) -> Self {
856 for &tau in taus {
857 self = self
858 .geom_path()
859 .stat(crate::stat::quantile::StatQuantile::new(tau));
860 }
861 self
862 }
863
864 #[cfg(feature = "regression")]
866 pub fn geom_quantile(self) -> Self {
867 self.stat_quantile(&[0.25, 0.5, 0.75])
868 }
869
870 pub fn geom_step(self) -> Self {
871 self.add_geom(GeomStep::default())
872 }
873
874 pub fn geom_step_with(self, geom: GeomStep) -> Self {
875 self.add_geom_with(geom)
876 }
877
878 pub fn geom_freqpoly(self) -> Self {
879 self.add_geom(GeomFreqpoly::default())
880 }
881
882 pub fn geom_freqpoly_with(self, geom: GeomFreqpoly) -> Self {
883 self.add_geom_with(geom)
884 }
885
886 pub fn geom_linerange(self) -> Self {
887 self.add_geom(GeomLinerange::default())
888 }
889
890 pub fn geom_linerange_with(self, geom: GeomLinerange) -> Self {
891 self.add_geom_with(geom)
892 }
893
894 pub fn geom_pointrange(self) -> Self {
895 self.add_geom(GeomPointrange::default())
896 }
897
898 pub fn geom_pointrange_with(self, geom: GeomPointrange) -> Self {
899 self.add_geom_with(geom)
900 }
901
902 pub fn geom_crossbar(self) -> Self {
903 self.add_geom(GeomCrossbar::default())
904 }
905
906 pub fn geom_crossbar_with(self, geom: GeomCrossbar) -> Self {
907 self.add_geom_with(geom)
908 }
909
910 pub fn geom_spoke(self) -> Self {
911 self.add_geom(GeomSpoke::default())
912 }
913
914 pub fn geom_spoke_with(self, geom: GeomSpoke) -> Self {
915 self.add_geom_with(geom)
916 }
917
918 pub fn geom_rect(self) -> Self {
919 self.add_geom(GeomRect::default())
920 }
921
922 pub fn geom_rect_with(self, geom: GeomRect) -> Self {
923 self.add_geom_with(geom)
924 }
925
926 pub fn geom_tile(self) -> Self {
927 self.add_geom(GeomTile::default())
928 }
929
930 pub fn geom_tile_with(self, geom: GeomTile) -> Self {
931 self.add_geom_with(geom)
932 }
933
934 pub fn geom_raster(self) -> Self {
936 self.add_geom(crate::geom::raster::GeomRaster::default())
937 }
938
939 pub fn geom_raster_with(self, geom: crate::geom::raster::GeomRaster) -> Self {
940 self.add_geom_with(geom)
941 }
942
943 pub fn geom_polygon(self) -> Self {
944 self.add_geom(GeomPolygon::default())
945 }
946
947 pub fn geom_polygon_with(self, geom: GeomPolygon) -> Self {
948 self.add_geom_with(geom)
949 }
950
951 #[cfg(feature = "sf")]
953 pub fn geom_sf(self) -> Self {
954 self.add_geom(crate::geom::sf::GeomSf::default())
955 }
956
957 #[cfg(feature = "sf")]
958 pub fn geom_sf_with(self, geom: crate::geom::sf::GeomSf) -> Self {
959 self.add_geom_with(geom)
960 }
961
962 #[cfg(feature = "sf")]
965 pub fn geom_sf_text(self) -> Self {
966 self.add_geom(crate::geom::sf_text::GeomSfText::default())
967 }
968
969 #[cfg(feature = "sf")]
970 pub fn geom_sf_text_with(self, geom: crate::geom::sf_text::GeomSfText) -> Self {
971 self.add_geom_with(geom)
972 }
973
974 #[cfg(feature = "sf")]
977 pub fn geom_sf_label(self) -> Self {
978 self.add_geom(crate::geom::sf_text::GeomSfLabel::default())
979 }
980
981 #[cfg(feature = "sf")]
982 pub fn geom_sf_label_with(self, geom: crate::geom::sf_text::GeomSfLabel) -> Self {
983 self.add_geom_with(geom)
984 }
985
986 #[cfg(feature = "sf")]
990 pub fn annotation_scale(self) -> Self {
991 self.add_geom(crate::geom::annotation_scale::GeomAnnotationScale::default())
992 }
993
994 #[cfg(feature = "sf")]
995 pub fn annotation_scale_with(
996 self,
997 geom: crate::geom::annotation_scale::GeomAnnotationScale,
998 ) -> Self {
999 self.add_geom_with(geom)
1000 }
1001
1002 #[cfg(feature = "sf")]
1005 pub fn annotation_north_arrow_with(
1006 self,
1007 geom: crate::geom::annotation_scale::GeomNorthArrow,
1008 ) -> Self {
1009 self.add_geom_with(geom)
1010 }
1011
1012 #[cfg(feature = "sf")]
1015 pub fn annotation_attribution(self, text: impl Into<String>) -> Self {
1016 self.add_geom(crate::geom::annotation_scale::GeomAttribution::new(text))
1017 }
1018
1019 #[cfg(feature = "tiles")]
1027 pub fn annotation_map_tile(
1028 self,
1029 source: crate::geom::map_tile::TileSource,
1030 fetcher: impl crate::geom::map_tile::TileFetcher + 'static,
1031 ) -> Self {
1032 self.annotation_map_tile_with(crate::geom::map_tile::GeomMapTile::new(source, fetcher))
1033 }
1034
1035 #[cfg(feature = "tiles")]
1038 pub fn annotation_map_tile_with(self, geom: crate::geom::map_tile::GeomMapTile) -> Self {
1039 let attribution = geom.source.attribution.clone();
1040 let mut plot = self.add_geom_with(geom);
1041 if let Some(layer) = plot.layers.pop() {
1043 plot.layers.insert(0, layer);
1044 for (idx, ..) in plot.layer_svg_attrs.iter_mut() {
1045 *idx += 1;
1046 }
1047 }
1048 if attribution.is_empty() {
1049 plot
1050 } else {
1051 plot.annotation_attribution(attribution)
1052 }
1053 }
1054
1055 #[cfg(feature = "sf")]
1056 pub fn annotation_attribution_with(
1057 self,
1058 geom: crate::geom::annotation_scale::GeomAttribution,
1059 ) -> Self {
1060 self.add_geom_with(geom)
1061 }
1062
1063 #[cfg(feature = "sf")]
1071 pub fn bivariate_legend(
1072 self,
1073 geom: crate::geom::bivariate_legend::GeomBivariateLegend,
1074 ) -> Self {
1075 self.add_geom(geom)
1076 }
1077
1078 #[cfg(feature = "sf")]
1083 pub fn bivariate_legend_counts(
1084 self,
1085 geom: crate::geom::bivariate_legend::GeomBivariateLegendCounts,
1086 ) -> Self {
1087 self.add_geom(geom)
1088 }
1089
1090 pub fn geom_curve(self) -> Self {
1091 self.add_geom(GeomCurve::default())
1092 }
1093
1094 pub fn geom_curve_with(self, geom: GeomCurve) -> Self {
1095 self.add_geom_with(geom)
1096 }
1097
1098 pub fn geom_violin(self) -> Self {
1099 self.add_geom(GeomViolin::default())
1100 }
1101
1102 pub fn geom_violin_with(self, geom: GeomViolin) -> Self {
1103 self.add_geom_with(geom)
1104 }
1105
1106 pub fn geom_density_ridges(self) -> Self {
1110 self.add_geom(GeomDensityRidges::default())
1111 }
1112
1113 pub fn geom_density_ridges_with(self, geom: GeomDensityRidges) -> Self {
1114 self.add_geom_with(geom)
1115 }
1116
1117 pub fn geom_dotplot(self) -> Self {
1118 self.add_geom(GeomDotplot::default())
1119 }
1120
1121 pub fn geom_dotplot_with(self, geom: GeomDotplot) -> Self {
1122 self.add_geom_with(geom)
1123 }
1124
1125 pub fn geom_qq(self) -> Self {
1126 self.add_geom(GeomQQ::default())
1127 }
1128
1129 pub fn geom_qq_with(self, geom: GeomQQ) -> Self {
1130 self.add_geom_with(geom)
1131 }
1132
1133 pub fn geom_qq_line(self) -> Self {
1134 self.add_geom(GeomQQLine::default())
1135 }
1136
1137 pub fn geom_qq_line_with(self, geom: GeomQQLine) -> Self {
1138 self.add_geom_with(geom)
1139 }
1140
1141 pub fn geom_bin2d(self) -> Self {
1142 self.add_geom(GeomBin2d::default())
1143 }
1144
1145 pub fn geom_bin2d_with(self, geom: GeomBin2d) -> Self {
1146 self.add_geom_with(geom)
1147 }
1148
1149 pub fn geom_hex(self) -> Self {
1150 self.add_geom(GeomHex::default())
1151 }
1152
1153 pub fn geom_hex_with(self, geom: GeomHex) -> Self {
1154 self.add_geom_with(geom)
1155 }
1156
1157 pub fn geom_count(self) -> Self {
1158 self.add_geom(GeomCount::default())
1159 }
1160
1161 pub fn geom_count_with(self, geom: GeomCount) -> Self {
1162 self.add_geom_with(geom)
1163 }
1164
1165 pub fn geom_contour(self) -> Self {
1166 self.add_geom(GeomContour::default())
1167 }
1168
1169 pub fn geom_contour_with(self, geom: GeomContour) -> Self {
1170 self.add_geom_with(geom)
1171 }
1172
1173 pub fn geom_contour_filled(self) -> Self {
1176 self.add_geom(GeomPolygon {
1177 line_width: 0.0,
1178 alpha: 1.0,
1179 ..GeomPolygon::default()
1180 })
1181 .stat(crate::stat::contour_filled::StatContourFilled::default())
1182 }
1183
1184 pub fn geom_density2d(self) -> Self {
1185 self.add_geom(GeomDensity2d::default())
1186 }
1187
1188 pub fn geom_density2d_with(self, geom: GeomDensity2d) -> Self {
1189 self.add_geom_with(geom)
1190 }
1191
1192 pub fn geom_waterfall(self) -> Self {
1198 self.default_styled(|p| {
1199 p.geom_waterfall_with(crate::geom::waterfall::GeomWaterfall::default())
1200 })
1201 }
1202
1203 pub fn geom_waterfall_with(self, geom: crate::geom::waterfall::GeomWaterfall) -> Self {
1210 use crate::scale::color::RGBAColor;
1211 use crate::stat::waterfall::{WATERFALL_DECREASE, WATERFALL_INCREASE, WATERFALL_TOTAL};
1212 let rgba = |(r, g, b): (u8, u8, u8)| RGBAColor::new(r, g, b);
1213 let mut values = vec![
1214 (WATERFALL_INCREASE, rgba(geom.up)),
1215 (WATERFALL_DECREASE, rgba(geom.down)),
1216 ];
1217 if geom.has_totals() {
1218 values.push((WATERFALL_TOTAL, rgba(geom.total)));
1219 }
1220 let fill_mapped = self
1221 .mapping
1222 .get_mapping(&crate::aes::Aesthetic::Fill)
1223 .is_some();
1224 let has_fill_scale = self
1225 .scales
1226 .iter()
1227 .any(|s| s.aesthetic() == crate::aes::Aesthetic::Fill);
1228 let mut plot = self.add_geom_with(geom);
1229 if !fill_mapped {
1230 plot = plot.layer_aes(Aes::new().after_stat_fill("direction"));
1231 if !has_fill_scale {
1232 plot = plot.scale_fill_manual(values);
1233 }
1234 }
1235 plot
1236 }
1237
1238 pub fn geom_pareto(self) -> Self {
1242 self.add_pareto(crate::geom::pareto::GeomPareto::default(), false)
1243 }
1244
1245 pub fn geom_pareto_with(self, geom: crate::geom::pareto::GeomPareto) -> Self {
1251 self.add_pareto(geom, true)
1252 }
1253
1254 fn add_pareto(self, geom: crate::geom::pareto::GeomPareto, explicit: bool) -> Self {
1255 let has_y_scale = self
1256 .scales
1257 .iter()
1258 .any(|s| s.aesthetic() == crate::aes::Aesthetic::Y);
1259 let plot = if explicit {
1260 self.add_geom_with(geom)
1261 } else {
1262 self.add_geom(geom)
1263 };
1264 if has_y_scale {
1265 plot
1266 } else {
1267 plot.scale_y_continuous(ScaleContinuous::new().with_sec_axis(
1268 crate::scale::sec_axis::SecAxis::percent_of_max().with_name("Cumulative %"),
1269 ))
1270 }
1271 }
1272
1273 pub fn geom_sankey(self) -> Self {
1280 self.add_sankey(crate::geom::sankey::GeomSankey::default(), false)
1281 }
1282
1283 pub fn geom_sankey_with(self, geom: crate::geom::sankey::GeomSankey) -> Self {
1285 self.add_sankey(geom, true)
1286 }
1287
1288 fn add_sankey(self, geom: crate::geom::sankey::GeomSankey, explicit: bool) -> Self {
1289 let mut plot = if explicit {
1290 self.add_geom_with(geom)
1291 } else {
1292 self.add_geom(geom)
1293 };
1294 plot.hide_position_guides = true;
1295 plot.layer_aes(Aes::new().after_stat_fill("node"))
1296 .show_legend(false)
1297 }
1298
1299 pub fn geom_chord(self) -> Self {
1306 self.add_chord(crate::geom::chord::GeomChord::default(), false)
1307 }
1308
1309 pub fn geom_chord_with(self, geom: crate::geom::chord::GeomChord) -> Self {
1311 self.add_chord(geom, true)
1312 }
1313
1314 fn add_chord(self, geom: crate::geom::chord::GeomChord, explicit: bool) -> Self {
1315 let (ex, ey) = geom.extents();
1316 let mut plot = if explicit {
1317 self.add_geom_with(geom)
1318 } else {
1319 self.add_geom(geom)
1320 };
1321 plot.hide_position_guides = true;
1322 plot.default_aspect_ratio = Some(ey / ex);
1323 plot.layer_aes(Aes::new().after_stat_fill("node"))
1324 .show_legend(false)
1325 }
1326
1327 pub fn geom_arcdiagram(self) -> Self {
1332 self.add_arcdiagram(crate::geom::arcdiagram::GeomArcdiagram::default(), false)
1333 }
1334
1335 pub fn geom_arcdiagram_with(self, geom: crate::geom::arcdiagram::GeomArcdiagram) -> Self {
1338 self.add_arcdiagram(geom, true)
1339 }
1340
1341 fn add_arcdiagram(self, geom: crate::geom::arcdiagram::GeomArcdiagram, explicit: bool) -> Self {
1342 let mut plot = if explicit {
1343 self.add_geom_with(geom)
1344 } else {
1345 self.add_geom(geom)
1346 };
1347 plot.hide_position_guides = true;
1348 plot.layer_aes(Aes::new().after_stat_fill("node"))
1349 .show_legend(false)
1350 }
1351
1352 pub fn geom_treemap(self) -> Self {
1360 self.add_treemap(crate::geom::treemap::GeomTreemap::default(), false)
1361 }
1362
1363 pub fn geom_treemap_with(self, geom: crate::geom::treemap::GeomTreemap) -> Self {
1365 self.add_treemap(geom, true)
1366 }
1367
1368 fn add_treemap(self, geom: crate::geom::treemap::GeomTreemap, explicit: bool) -> Self {
1369 use crate::aes::Aesthetic;
1370 let aspect = geom.aspect;
1371 let has = |plot: &Self, aes: Aesthetic| plot.scales.iter().any(|s| s.aesthetic() == aes);
1372 let (has_x, has_y) = (has(&self, Aesthetic::X), has(&self, Aesthetic::Y));
1373 let fill_by = match (
1374 self.mapping.get_mapping(&Aesthetic::Fill),
1375 self.mapping.get_mapping(&Aesthetic::Subgroup),
1376 ) {
1377 (None, Some(sub)) => Some(sub.to_string()),
1378 _ => None,
1379 };
1380 let mut plot = if explicit {
1381 self.add_geom_with(geom)
1382 } else {
1383 self.add_geom(geom)
1384 };
1385 plot.hide_position_guides = true;
1386 plot.default_aspect_ratio = Some(1.0 / aspect.max(1e-6));
1387 if let Some(sub) = fill_by {
1388 plot = plot.layer_aes(Aes::new().fill(&sub));
1389 }
1390 if !has_x {
1391 plot = plot.scale_x_continuous(ScaleContinuous::new().with_expand(0.0, 0.0));
1392 }
1393 if !has_y {
1394 plot = plot.scale_y_continuous(ScaleContinuous::new().with_expand(0.0, 0.0));
1395 }
1396 plot
1397 }
1398
1399 pub fn geom_sunburst<S: Into<String>>(self, levels: impl IntoIterator<Item = S>) -> Self {
1406 let geom = crate::geom::partition::GeomPartition::sunburst(levels);
1407 let depth = geom.levels.len().max(1) as f64;
1409 let inner = geom.hole / (geom.hole + depth);
1410 let mut plot = self.default_styled(|p| p.geom_partition_with(geom));
1411 plot.coord = Box::new(CoordPolar::new().inner_radius(inner));
1412 plot
1413 }
1414
1415 pub fn geom_icicle<S: Into<String>>(self, levels: impl IntoIterator<Item = S>) -> Self {
1419 self.default_styled(|p| {
1420 p.geom_partition_with(crate::geom::partition::GeomPartition::icicle(levels))
1421 })
1422 }
1423
1424 pub fn geom_partition_with(self, geom: crate::geom::partition::GeomPartition) -> Self {
1428 use crate::aes::Aesthetic;
1429 let has = |plot: &Self, aes: Aesthetic| plot.scales.iter().any(|s| s.aesthetic() == aes);
1430 let (has_x, has_y) = (has(&self, Aesthetic::X), has(&self, Aesthetic::Y));
1431 let fill_mapped = self.mapping.get_mapping(&Aesthetic::Fill).is_some();
1432 let mut plot = self.add_geom_with(geom);
1433 plot.hide_position_guides = true;
1434 if !fill_mapped {
1435 plot = plot
1436 .layer_aes(Aes::new().after_stat_fill("root"))
1437 .show_legend(false);
1438 }
1439 if !has_x {
1440 plot = plot.scale_x_continuous(ScaleContinuous::new().with_expand(0.0, 0.0));
1441 }
1442 if !has_y {
1443 plot = plot.scale_y_continuous(ScaleContinuous::new().with_expand(0.0, 0.0));
1444 }
1445 plot
1446 }
1447
1448 pub fn geom_funnel(self) -> Self {
1456 self.default_styled(|p| p.geom_funnel_with(crate::geom::funnel::GeomFunnel::default()))
1457 }
1458
1459 pub fn geom_pyramid(self) -> Self {
1461 self.default_styled(|p| p.geom_funnel_with(crate::geom::funnel::GeomFunnel::pyramid()))
1462 }
1463
1464 pub fn geom_funnel_with(self, geom: crate::geom::funnel::GeomFunnel) -> Self {
1466 let fill_mapped = self
1467 .mapping
1468 .get_mapping(&crate::aes::Aesthetic::Fill)
1469 .is_some();
1470 let mut plot = self.add_geom_with(geom);
1471 plot.hide_position_guides = true;
1472 if !fill_mapped {
1473 plot = plot
1474 .layer_aes(Aes::new().after_stat_fill("stage"))
1475 .show_legend(false);
1476 }
1477 plot
1478 }
1479
1480 pub fn geom_stream(self) -> Self {
1486 self.geom_area().position(
1487 crate::position::stack::position_stack()
1488 .with_offset(crate::position::stack::StackOffset::Wiggle),
1489 )
1490 }
1491
1492 pub fn geom_lollipop(self) -> Self {
1495 self.add_geom(crate::geom::lollipop::GeomLollipop::default())
1496 }
1497
1498 pub fn geom_lollipop_with(self, geom: crate::geom::lollipop::GeomLollipop) -> Self {
1499 self.add_geom_with(geom)
1500 }
1501
1502 pub fn geom_dumbbell(self) -> Self {
1506 self.add_geom(crate::geom::lollipop::GeomDumbbell::default())
1507 }
1508
1509 pub fn geom_dumbbell_with(self, geom: crate::geom::lollipop::GeomDumbbell) -> Self {
1510 self.add_geom_with(geom)
1511 }
1512
1513 pub fn geom_bullet(self, geom: crate::geom::bullet::GeomBullet) -> Self {
1519 self.add_geom_with(geom).coord_flip()
1520 }
1521
1522 pub fn geom_bullet_vertical(self, geom: crate::geom::bullet::GeomBullet) -> Self {
1524 self.add_geom_with(geom)
1525 }
1526
1527 pub fn geom_waffle(self, rows: usize) -> Self {
1531 self.default_styled(|p| p.geom_waffle_with(crate::geom::waffle::GeomWaffle::waffle(rows)))
1532 }
1533
1534 pub fn geom_parliament(self, rows: usize) -> Self {
1538 self.default_styled(|p| {
1539 p.geom_waffle_with(crate::geom::waffle::GeomWaffle::parliament(rows))
1540 })
1541 }
1542
1543 pub fn geom_waffle_with(self, geom: crate::geom::waffle::GeomWaffle) -> Self {
1545 let mut plot = self.add_geom_with(geom);
1546 plot.hide_position_guides = true;
1547 plot
1548 }
1549
1550 pub fn geom_packed_bubble(self) -> Self {
1555 self.default_styled(|p| {
1556 p.geom_packed_bubble_with(crate::geom::pack::GeomPackedBubble::default())
1557 })
1558 }
1559
1560 pub fn geom_packed_bubble_with(self, geom: crate::geom::pack::GeomPackedBubble) -> Self {
1562 use crate::aes::Aesthetic;
1563 let fill_by = match (
1564 self.mapping.get_mapping(&Aesthetic::Fill),
1565 self.mapping.get_mapping(&Aesthetic::Subgroup),
1566 ) {
1567 (None, Some(sub)) => Some(sub.to_string()),
1568 _ => None,
1569 };
1570 let mut plot = self.add_geom_with(geom);
1571 plot.hide_position_guides = true;
1572 plot.default_aspect_ratio = Some(1.0);
1573 if let Some(sub) = fill_by {
1574 plot = plot.layer_aes(Aes::new().fill(&sub));
1575 }
1576 plot
1577 }
1578
1579 pub fn geom_network(self) -> Self {
1585 self.add_network(crate::geom::network::GeomNetwork::default(), false)
1586 }
1587
1588 pub fn geom_network_with(self, geom: crate::geom::network::GeomNetwork) -> Self {
1590 self.add_network(geom, true)
1591 }
1592
1593 fn add_network(self, geom: crate::geom::network::GeomNetwork, explicit: bool) -> Self {
1594 let by_component = geom.color_components;
1595 let mut plot = if explicit {
1596 self.add_geom_with(geom)
1597 } else {
1598 self.add_geom(geom)
1599 };
1600 plot.hide_position_guides = true;
1601 plot.default_aspect_ratio = Some(1.0);
1602 if by_component {
1603 plot = plot
1604 .layer_aes(Aes::new().after_stat_fill("component"))
1605 .show_legend(false);
1606 }
1607 plot
1608 }
1609
1610 pub fn geom_tree(self) -> Self {
1617 self.default_styled(|p| p.geom_tree_with(crate::geom::tree::GeomTree::default()))
1618 }
1619
1620 pub fn geom_dendrogram(self) -> Self {
1624 self.default_styled(|p| p.geom_tree_with(crate::geom::tree::GeomTree::dendrogram()))
1625 }
1626
1627 pub fn geom_tree_with(self, geom: crate::geom::tree::GeomTree) -> Self {
1629 let radial = geom.orientation == crate::stat::tree::TreeOrientation::Radial;
1630 let mut plot = self.add_geom_with(geom);
1631 plot.hide_position_guides = true;
1632 if radial {
1633 plot.default_aspect_ratio = Some(1.0);
1634 }
1635 plot
1636 }
1637
1638 pub fn geom_venn(self) -> Self {
1644 self.default_styled(|p| p.geom_venn_with(crate::geom::venn::GeomVenn::default()))
1645 }
1646
1647 pub fn geom_venn_with(self, geom: crate::geom::venn::GeomVenn) -> Self {
1649 let mut plot = self.add_geom_with(geom);
1650 plot.hide_position_guides = true;
1651 plot.default_aspect_ratio = Some(1.0);
1652 plot.layer_aes(Aes::new().after_stat_fill("set"))
1653 .show_legend(false)
1654 }
1655
1656 pub fn geom_wordcloud(self) -> Self {
1661 self.default_styled(|p| {
1662 p.geom_wordcloud_with(crate::geom::wordcloud::GeomWordcloud::default())
1663 })
1664 }
1665
1666 pub fn geom_wordcloud_with(self, geom: crate::geom::wordcloud::GeomWordcloud) -> Self {
1669 let mut plot = self.add_geom_with(geom);
1670 plot.hide_position_guides = true;
1671 plot
1672 }
1673
1674 pub fn geom_variwide(self) -> Self {
1679 self.default_styled(|p| {
1680 p.geom_marimekko_with(crate::geom::marimekko::GeomMarimekko::variwide())
1681 })
1682 }
1683
1684 pub fn geom_marimekko(self) -> Self {
1688 self.default_styled(|p| {
1689 p.geom_marimekko_with(crate::geom::marimekko::GeomMarimekko::marimekko())
1690 })
1691 }
1692
1693 pub fn geom_marimekko_with(self, geom: crate::geom::marimekko::GeomMarimekko) -> Self {
1695 use crate::aes::Aesthetic;
1696 let has = |plot: &Self, aes: Aesthetic| plot.scales.iter().any(|s| s.aesthetic() == aes);
1697 let (has_x, has_y) = (has(&self, Aesthetic::X), has(&self, Aesthetic::Y));
1698 let axis = self.mapping.get_mapping(&Aesthetic::X).and_then(|xc| {
1700 let x = self.data.column(xc)?;
1701 let w = self
1702 .mapping
1703 .get_mapping(&Aesthetic::Weight)
1704 .and_then(|wc| self.data.column(wc));
1705 let totals = crate::stat::marimekko::column_totals(x, w);
1706 let widths: Vec<f64> = totals.iter().map(|t| t.1).collect();
1707 let spans = crate::stat::marimekko::column_spans(&widths, geom.gap);
1708 Some((
1709 spans
1710 .iter()
1711 .map(|s| (s.0 + s.1) / 2.0)
1712 .collect::<Vec<f64>>(),
1713 totals.into_iter().map(|t| t.0).collect::<Vec<String>>(),
1714 ))
1715 });
1716 let mosaic = geom.mosaic;
1717 let mut plot = self.add_geom_with(geom);
1718 if !has_x {
1719 let mut sx = ScaleContinuous::new().with_expand(0.0, 0.0);
1720 if let Some((breaks, labels)) = axis {
1721 sx = sx.with_breaks(breaks).with_labels(labels);
1722 }
1723 plot = plot.scale_x_continuous(sx);
1724 }
1725 if mosaic && !has_y {
1726 plot = plot.scale_y_continuous(
1727 ScaleContinuous::new()
1728 .with_expand(0.0, 0.0)
1729 .with_label_formatter(|v| format!("{}%", (v * 100.0).round())),
1730 );
1731 }
1732 plot
1733 }
1734
1735 pub fn geom_timeline(self) -> Self {
1740 let mut plot = self.add_geom(crate::geom::timeline::GeomTimeline::default());
1741 plot.hide_y_guides = true;
1742 plot
1743 }
1744
1745 pub fn geom_timeline_with(self, geom: crate::geom::timeline::GeomTimeline) -> Self {
1747 let mut plot = self.add_geom_with(geom);
1748 plot.hide_y_guides = true;
1749 plot
1750 }
1751
1752 pub fn geom_xrange(self) -> Self {
1759 self.add_xrange(crate::geom::xrange::GeomXrange::default(), false)
1760 }
1761
1762 pub fn geom_xrange_with(self, geom: crate::geom::xrange::GeomXrange) -> Self {
1764 self.add_xrange(geom, true)
1765 }
1766
1767 fn add_xrange(self, geom: crate::geom::xrange::GeomXrange, explicit: bool) -> Self {
1768 use crate::aes::Aesthetic;
1769 let has_y = self.scales.iter().any(|s| s.aesthetic() == Aesthetic::Y);
1770 let levels: Option<Vec<String>> = self
1772 .mapping
1773 .get_mapping(&Aesthetic::Y)
1774 .and_then(|c| self.data.column(c))
1775 .map(|col| {
1776 let mut seen: indexmap::IndexSet<String> = indexmap::IndexSet::new();
1777 for v in col.iter().filter(|v| !v.is_na()) {
1778 seen.insert(v.key_str().into_owned());
1779 }
1780 seen.into_iter().rev().collect()
1781 });
1782 let mut plot = if explicit {
1783 self.add_geom_with(geom)
1784 } else {
1785 self.add_geom(geom)
1786 };
1787 if let (false, Some(levels)) = (has_y, levels) {
1788 let refs: Vec<&str> = levels.iter().map(String::as_str).collect();
1789 plot = plot
1790 .scale_y_discrete(crate::scale::discrete::ScaleDiscrete::new().with_limits(refs));
1791 }
1792 plot
1793 }
1794
1795 pub fn geom_tilemap(self, shape: crate::geom::tilemap::TileShape) -> Self {
1800 self.default_styled(|p| {
1801 p.geom_tilemap_with(crate::geom::tilemap::GeomTilemap {
1802 shape,
1803 ..Default::default()
1804 })
1805 })
1806 }
1807
1808 pub fn geom_tilemap_with(self, geom: crate::geom::tilemap::GeomTilemap) -> Self {
1810 let mut plot = self.add_geom_with(geom);
1811 plot.hide_position_guides = true;
1812 plot
1813 }
1814
1815 pub fn geom_windbarb(self, geom: crate::geom::windbarb::GeomWindbarb) -> Self {
1820 self.add_geom(geom)
1821 }
1822
1823 pub fn geom_variable_pie(self) -> Self {
1827 let mut plot = self.add_geom(crate::geom::variablepie::GeomVariablePie::default());
1828 plot.hide_position_guides = true;
1829 plot.default_aspect_ratio = Some(1.0);
1830 plot
1831 }
1832
1833 pub fn geom_variable_pie_with(self, geom: crate::geom::variablepie::GeomVariablePie) -> Self {
1836 let mut plot = self.add_geom_with(geom);
1837 plot.hide_position_guides = true;
1838 plot.default_aspect_ratio = Some(1.0);
1839 plot
1840 }
1841
1842 pub fn geom_hlc(self) -> Self {
1845 self.add_geom(crate::geom::candlestick::GeomOhlc::hlc())
1846 }
1847
1848 pub fn geom_heikin_ashi(self) -> Self {
1852 self.add_geom(crate::geom::candlestick::GeomCandlestick::default())
1853 .stat(crate::stat::heikin_ashi::StatHeikinAshi)
1854 }
1855
1856 pub fn geom_renko(self, box_size: f64) -> Self {
1860 self.add_geom(crate::geom::renko::GeomRenko::renko(box_size))
1861 .xlab("Brick")
1862 }
1863
1864 pub fn geom_point_figure(self, box_size: f64, reversal: usize) -> Self {
1868 self.add_geom(crate::geom::renko::GeomRenko::point_figure(
1869 box_size, reversal,
1870 ))
1871 .xlab("Column")
1872 }
1873
1874 pub fn geom_flags(self) -> Self {
1879 self.add_geom(crate::geom::flags::GeomFlags::default())
1880 }
1881
1882 pub fn geom_flags_with(self, geom: crate::geom::flags::GeomFlags) -> Self {
1883 self.add_geom_with(geom)
1884 }
1885
1886 #[cfg(feature = "sf")]
1891 pub fn geom_flow(self, geom: crate::geom::flow::GeomFlow) -> Self {
1892 self.add_geom(geom)
1893 }
1894
1895 pub fn geom_candlestick(self) -> Self {
1898 self.add_geom(crate::geom::candlestick::GeomCandlestick::default())
1899 }
1900
1901 pub fn geom_candlestick_with(self, geom: crate::geom::candlestick::GeomCandlestick) -> Self {
1902 self.add_geom_with(geom)
1903 }
1904
1905 pub fn geom_ohlc(self) -> Self {
1908 self.add_geom(crate::geom::candlestick::GeomOhlc::default())
1909 }
1910
1911 pub fn geom_ohlc_with(self, geom: crate::geom::candlestick::GeomOhlc) -> Self {
1912 self.add_geom_with(geom)
1913 }
1914
1915 pub fn geom_calendar(self) -> Self {
1926 self.geom_calendar_with(
1927 GeomTile {
1928 color: (255, 255, 255),
1929 line_width: 1.5,
1930 ..Default::default()
1931 },
1932 false,
1933 )
1934 }
1935
1936 pub fn geom_calendar_with(mut self, tile: GeomTile, monday_first: bool) -> Self {
1939 use crate::stat::calendar::{
1940 day_number, month_boundaries, month_breaks, month_breaks_localized, weekday_labels,
1941 CalendarGrid, StatCalendar, MAX_CALENDAR_YEARS,
1942 };
1943 let grid = self
1944 .mapping
1945 .get_mapping(&crate::aes::Aesthetic::X)
1946 .and_then(|c| self.data.column(c))
1947 .and_then(|col| {
1948 CalendarGrid::from_days(col.iter().filter_map(day_number), monday_first)
1949 });
1950 let Some((grid, clipped)) = grid else {
1951 return self.add_geom_with(tile).stat(StatCalendar {
1953 grid: None,
1954 monday_first,
1955 });
1956 };
1957 if clipped {
1958 self.warnings.push(format!(
1959 "geom_calendar: dates more than {MAX_CALENDAR_YEARS} years before the newest were dropped"
1960 ));
1961 }
1962 let (xb, _) = month_breaks(&grid);
1963 let yb = if monday_first {
1965 vec![6.0, 4.0, 2.0]
1966 } else {
1967 vec![5.0, 3.0, 1.0]
1968 };
1969 let segs = month_boundaries(&grid);
1970 let col = |f: fn(&(f64, f64, f64, f64)) -> f64| -> Vec<Value> {
1971 segs.iter().map(|s| Value::Float(f(s))).collect()
1972 };
1973 let boundaries = vec![
1974 ("x".to_string(), col(|s| s.0)),
1975 ("y".to_string(), col(|s| s.1)),
1976 ("xend".to_string(), col(|s| s.2)),
1977 ("yend".to_string(), col(|s| s.3)),
1978 ];
1979 self.default_aspect_ratio = Some(7.0 / grid.n_weeks().max(1) as f64);
1980 let plot = self
1981 .add_geom_with(tile)
1982 .stat(StatCalendar {
1983 grid: Some(grid),
1984 monday_first,
1985 })
1986 .scale_x_continuous(
1987 ScaleContinuous::new()
1988 .with_breaks(xb)
1989 .with_localized_labels(move |l| month_breaks_localized(&grid, l).1)
1991 .with_expand(0.0, 0.0),
1992 )
1993 .scale_y_continuous(
1994 ScaleContinuous::new()
1995 .with_breaks(yb)
1996 .with_localized_labels(weekday_labels)
1997 .with_expand(0.0, 0.0),
1998 );
1999 if segs.is_empty() {
2000 return plot;
2001 }
2002 plot.add_geom_with(crate::geom::segment::GeomCalendarBorder)
2004 .layer_data(boundaries)
2005 .layer_aes(Aes::new().x("x").y("y").xend("xend").yend("yend"))
2006 .show_legend(false)
2007 }
2008
2009 pub fn geom_blank(self) -> Self {
2010 self.add_geom(GeomBlank)
2011 }
2012
2013 fn default_styled(self, build: impl FnOnce(Self) -> Self) -> Self {
2020 let i = self.layers.len();
2021 let mut plot = build(self);
2022 if let Some(layer) = plot.layers.get_mut(i) {
2023 layer.explicit_style = false;
2024 }
2025 plot
2026 }
2027
2028 fn add_geom_with(self, geom: impl Geom + 'static) -> Self {
2029 let mut plot = self.add_geom(geom);
2030 if let Some(layer) = plot.layers.last_mut() {
2031 layer.explicit_style = true;
2032 }
2033 plot
2034 }
2035
2036 fn add_geom(mut self, geom: impl Geom + 'static) -> Self {
2037 let stat = geom.default_stat();
2038 let position = geom.default_position();
2039 let params = geom.default_params();
2040 self.layers.push(Layer {
2041 data: None,
2042 mapping: Aes::default(),
2043 geom: Box::new(geom),
2044 stat,
2045 position,
2046 params,
2047 show_legend: None,
2048 explicit_style: false,
2049 tooltip_template: None,
2050 key_glyph: None,
2051 show_legend_aes: Vec::new(),
2052 });
2053 self
2054 }
2055
2056 pub fn stat(mut self, stat: impl Stat + 'static) -> Self {
2060 if let Some(layer) = self.layers.last_mut() {
2061 layer.stat = Box::new(stat);
2062 }
2063 self
2064 }
2065
2066 pub fn position(mut self, pos: impl Position + 'static) -> Self {
2068 if let Some(layer) = self.layers.last_mut() {
2069 layer.position = Box::new(pos);
2070 }
2071 self
2072 }
2073
2074 pub fn layer_data(mut self, data: impl GGData) -> Self {
2076 if let Some(layer) = self.layers.last_mut() {
2077 layer.data = Some(data.into_dataframe());
2078 }
2079 self
2080 }
2081
2082 pub fn layer_aes(mut self, mapping: Aes) -> Self {
2084 self.warnings.extend(mapping.warnings.iter().cloned());
2085 if let Some(layer) = self.layers.last_mut() {
2086 layer.mapping = mapping;
2087 }
2088 self
2089 }
2090
2091 pub fn tooltip(mut self, template: &str) -> Self {
2102 if let Some(layer) = self.layers.last_mut() {
2103 layer.tooltip_template = Some(template.to_string());
2104 }
2105 self
2106 }
2107
2108 pub fn show_legend(mut self, show: bool) -> Self {
2111 if let Some(layer) = self.layers.last_mut() {
2112 layer.show_legend = Some(show);
2113 }
2114 self
2115 }
2116
2117 pub fn guide_none(mut self, aes: crate::aes::Aesthetic) -> Self {
2119 if !self.guide_legend.hidden.contains(&aes) {
2120 self.guide_legend.hidden.push(aes);
2121 }
2122 self
2123 }
2124
2125 pub fn guide_title(mut self, aes: crate::aes::Aesthetic, title: &str) -> Self {
2128 self.guide_legend.titles.retain(|(a, _)| *a != aes);
2129 self.guide_legend.titles.push((aes, title.to_string()));
2130 self
2131 }
2132
2133 pub fn guide_colourbar(
2140 mut self,
2141 aes: crate::aes::Aesthetic,
2142 bar: crate::guide::config::GuideColourbar,
2143 ) -> Self {
2144 self.guide_legend.colourbars.retain(|(a, _)| *a != aes);
2145 self.guide_legend.colourbars.push((aes, bar));
2146 self
2147 }
2148
2149 pub fn guide_bins(
2154 mut self,
2155 aes: crate::aes::Aesthetic,
2156 bins: crate::guide::config::GuideBins,
2157 ) -> Self {
2158 self.guide_legend.plain_keys.retain(|a| *a != aes);
2159 self.guide_legend.bins.retain(|(a, _)| *a != aes);
2160 self.guide_legend.bins.push((aes, bins));
2161 self
2162 }
2163
2164 pub fn guide_position(
2168 mut self,
2169 aes: crate::aes::Aesthetic,
2170 position: crate::theme::LegendPosition,
2171 ) -> Self {
2172 self.guide_legend.positions.retain(|(a, _)| *a != aes);
2173 self.guide_legend.positions.push((aes, position));
2174 self
2175 }
2176
2177 pub fn guide_custom(mut self, guide: crate::guide::config::GuideCustom) -> Self {
2180 self.guide_legend.custom.push(guide);
2181 self
2182 }
2183
2184 pub fn guide_legend_keys(mut self, aes: crate::aes::Aesthetic) -> Self {
2187 self.guide_legend.bins.retain(|(a, _)| *a != aes);
2188 if !self.guide_legend.plain_keys.contains(&aes) {
2189 self.guide_legend.plain_keys.push(aes);
2190 }
2191 self
2192 }
2193
2194 pub fn guide_coloursteps(self, aes: crate::aes::Aesthetic) -> Self {
2197 self.guide_colourbar(aes, crate::guide::config::GuideColourbar::steps())
2198 }
2199
2200 pub fn guide_reverse(mut self, aes: crate::aes::Aesthetic, reverse: bool) -> Self {
2203 self.guide_legend.reversed.retain(|a| *a != aes);
2204 if reverse {
2205 self.guide_legend.reversed.push(aes);
2206 }
2207 self
2208 }
2209
2210 pub fn guide_override(
2213 mut self,
2214 aes: crate::aes::Aesthetic,
2215 keys: crate::guide::config::KeyOverride,
2216 ) -> Self {
2217 self.guide_legend.overrides.retain(|(a, _)| *a != aes);
2218 self.guide_legend.overrides.push((aes, keys));
2219 self
2220 }
2221
2222 pub fn guide_axis_logticks(mut self, aes: crate::aes::Aesthetic) -> Self {
2226 for s in self.scales.iter_mut().filter(|s| s.aesthetic() == aes) {
2227 s.set_log_ticks(true);
2228 }
2229 self
2230 }
2231
2232 pub fn show_legend_for(mut self, aes: crate::aes::Aesthetic, show: bool) -> Self {
2235 if let Some(layer) = self.layers.last_mut() {
2236 layer.show_legend_aes.retain(|(a, _)| *a != aes);
2237 layer.show_legend_aes.push((aes, show));
2238 }
2239 self
2240 }
2241
2242 pub fn key_glyph(mut self, glyph: crate::guide::key::KeyGlyph) -> Self {
2245 if let Some(layer) = self.layers.last_mut() {
2246 layer.key_glyph = Some(glyph);
2247 }
2248 self
2249 }
2250
2251 pub fn decorative(mut self) -> Self {
2278 if let Some(layer) = self.layers.last_mut() {
2279 let geom = std::mem::replace(&mut layer.geom, Box::new(GeomBlank));
2280 layer.geom = Box::new(crate::geom::decorative::Decorative(geom));
2281 if layer.show_legend.is_none() {
2282 layer.show_legend = Some(false);
2283 }
2284 }
2285 self
2286 }
2287
2288 pub fn layer_svg_attr(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
2322 let (name, value) = (name.into(), value.into());
2323 let Some(idx) = self.layers.len().checked_sub(1) else {
2324 self.warnings.push(format!(
2325 "layer_svg_attr(\"{name}\") called before any layer was added — ignored"
2326 ));
2327 return self;
2328 };
2329 if let Some((n, v)) =
2330 crate::render::svg_backend::validate_layer_svg_attr(&name, &value, &mut self.warnings)
2331 {
2332 self.layer_svg_attrs
2333 .retain(|(i, k, _)| !(*i == idx && *k == n));
2334 self.layer_svg_attrs.push((idx, n, v));
2335 }
2336 self
2337 }
2338
2339 pub fn layer_svg_attrs<N: Into<String>, V: Into<String>>(
2341 self,
2342 attrs: impl IntoIterator<Item = (N, V)>,
2343 ) -> Self {
2344 attrs
2345 .into_iter()
2346 .fold(self, |p, (n, v)| p.layer_svg_attr(n, v))
2347 }
2348
2349 pub fn scale_x_continuous(mut self, s: ScaleContinuous) -> Self {
2352 let s = s.for_aesthetic(crate::aes::Aesthetic::X);
2353 self.scales.push(Box::new(s));
2354 self
2355 }
2356
2357 pub fn scale_y_continuous(mut self, s: ScaleContinuous) -> Self {
2358 let s = s.for_aesthetic(crate::aes::Aesthetic::Y);
2359 self.scales.push(Box::new(s));
2360 self
2361 }
2362
2363 pub fn scale_x_discrete(mut self, s: crate::scale::discrete::ScaleDiscrete) -> Self {
2364 let s = s.for_aesthetic(crate::aes::Aesthetic::X);
2365 self.scales.push(Box::new(s));
2366 self
2367 }
2368
2369 pub fn scale_y_discrete(mut self, s: crate::scale::discrete::ScaleDiscrete) -> Self {
2370 let s = s.for_aesthetic(crate::aes::Aesthetic::Y);
2371 self.scales.push(Box::new(s));
2372 self
2373 }
2374
2375 pub fn scale_color(mut self, s: impl Scale + 'static) -> Self {
2376 self.scales.push(Box::new(s));
2377 self
2378 }
2379
2380 pub fn scale_fill(mut self, s: impl Scale + 'static) -> Self {
2381 self.scales.push(Box::new(s));
2382 self
2383 }
2384
2385 pub fn scale_color_manual(self, values: Vec<(&str, crate::scale::color::RGBAColor)>) -> Self {
2386 let s = crate::scale::manual::ScaleManual::new(crate::aes::Aesthetic::Color, values);
2387 self.scale_color(s)
2388 }
2389
2390 pub fn scale_fill_manual(self, values: Vec<(&str, crate::scale::color::RGBAColor)>) -> Self {
2391 let s = crate::scale::manual::ScaleManual::new(crate::aes::Aesthetic::Fill, values);
2392 self.scale_fill(s)
2393 }
2394
2395 pub fn scale_colour_identity(self) -> Self {
2398 let s = crate::scale::identity::ScaleColorIdentity::new(crate::aes::Aesthetic::Color);
2399 self.scale_color(s)
2400 }
2401
2402 pub fn scale_color_identity(self) -> Self {
2404 self.scale_colour_identity()
2405 }
2406
2407 pub fn scale_fill_identity(self) -> Self {
2410 let s = crate::scale::identity::ScaleColorIdentity::new(crate::aes::Aesthetic::Fill);
2411 self.scale_fill(s)
2412 }
2413
2414 pub fn scale_color_viridis(self) -> Self {
2415 use crate::scale::color::ScaleColorDiscrete;
2416 use crate::scale::palettes::PaletteName;
2417 let s = ScaleColorDiscrete::new(crate::aes::Aesthetic::Color)
2418 .with_named_palette(&PaletteName::Viridis);
2419 self.scale_color(s)
2420 }
2421
2422 pub fn scale_color_brewer(self, name: crate::scale::palettes::PaletteName) -> Self {
2423 use crate::scale::color::ScaleColorDiscrete;
2424 let s = ScaleColorDiscrete::new(crate::aes::Aesthetic::Color).with_named_palette(&name);
2425 self.scale_color(s)
2426 }
2427
2428 pub fn scale_color_gradient(
2429 self,
2430 low: crate::scale::color::RGBAColor,
2431 high: crate::scale::color::RGBAColor,
2432 ) -> Self {
2433 use crate::scale::color::ScaleColorContinuous;
2434 let s = ScaleColorContinuous::new(crate::aes::Aesthetic::Color).with_colors(low, high);
2435 self.scale_color(s)
2436 }
2437
2438 pub fn scale_fill_gradient(
2439 self,
2440 low: crate::scale::color::RGBAColor,
2441 high: crate::scale::color::RGBAColor,
2442 ) -> Self {
2443 use crate::scale::color::ScaleColorContinuous;
2444 let s = ScaleColorContinuous::new(crate::aes::Aesthetic::Fill).with_colors(low, high);
2445 self.scale_fill(s)
2446 }
2447
2448 pub fn scale_color_gradient2(
2449 self,
2450 low: crate::scale::color::RGBAColor,
2451 mid: crate::scale::color::RGBAColor,
2452 high: crate::scale::color::RGBAColor,
2453 ) -> Self {
2454 use crate::scale::gradient::ScaleColorGradient2;
2455 let s = ScaleColorGradient2::new(crate::aes::Aesthetic::Color).with_colors(low, mid, high);
2456 self.scale_color(s)
2457 }
2458
2459 pub fn scale_fill_gradient2(
2460 self,
2461 low: crate::scale::color::RGBAColor,
2462 mid: crate::scale::color::RGBAColor,
2463 high: crate::scale::color::RGBAColor,
2464 ) -> Self {
2465 use crate::scale::gradient::ScaleColorGradient2;
2466 let s = ScaleColorGradient2::new(crate::aes::Aesthetic::Fill).with_colors(low, mid, high);
2467 self.scale_fill(s)
2468 }
2469
2470 pub fn scale_fill_viridis(self) -> Self {
2471 use crate::scale::color::ScaleColorDiscrete;
2472 use crate::scale::palettes::PaletteName;
2473 let s = ScaleColorDiscrete::new(crate::aes::Aesthetic::Fill)
2474 .with_named_palette(&PaletteName::Viridis);
2475 self.scale_fill(s)
2476 }
2477
2478 pub fn scale_color_viridis_c(self) -> Self {
2480 use crate::scale::gradient_n::ScaleColorGradientN;
2481 let s = ScaleColorGradientN::viridis(crate::aes::Aesthetic::Color);
2482 self.scale_color(s)
2483 }
2484
2485 pub fn scale_fill_viridis_c(self) -> Self {
2487 use crate::scale::gradient_n::ScaleColorGradientN;
2488 let s = ScaleColorGradientN::viridis(crate::aes::Aesthetic::Fill);
2489 self.scale_fill(s)
2490 }
2491
2492 pub fn scale_color_gradientn(self, stops: Vec<(f64, crate::scale::color::RGBAColor)>) -> Self {
2494 use crate::scale::gradient_n::ScaleColorGradientN;
2495 let s = ScaleColorGradientN::new(crate::aes::Aesthetic::Color, stops);
2496 self.scale_color(s)
2497 }
2498
2499 pub fn scale_fill_gradientn(self, stops: Vec<(f64, crate::scale::color::RGBAColor)>) -> Self {
2501 use crate::scale::gradient_n::ScaleColorGradientN;
2502 let s = ScaleColorGradientN::new(crate::aes::Aesthetic::Fill, stops);
2503 self.scale_fill(s)
2504 }
2505
2506 pub fn scale_color_steps(
2509 self,
2510 low: crate::scale::color::RGBAColor,
2511 high: crate::scale::color::RGBAColor,
2512 n_bins: usize,
2513 ) -> Self {
2514 let s = crate::scale::steps::ScaleColorSteps::two(
2515 crate::aes::Aesthetic::Color,
2516 (low.r, low.g, low.b),
2517 (high.r, high.g, high.b),
2518 n_bins,
2519 );
2520 self.scale_color(s)
2521 }
2522
2523 pub fn scale_color_stepsn(
2525 self,
2526 stops: Vec<crate::scale::color::RGBAColor>,
2527 n_bins: usize,
2528 ) -> Self {
2529 let s = crate::scale::steps::ScaleColorSteps::new(
2530 crate::aes::Aesthetic::Color,
2531 stops.iter().map(|c| (c.r, c.g, c.b)).collect(),
2532 n_bins,
2533 );
2534 self.scale_color(s)
2535 }
2536
2537 pub fn scale_color_fermenter(
2539 self,
2540 name: crate::scale::palettes::PaletteName,
2541 n_bins: usize,
2542 ) -> Self {
2543 let stops = crate::scale::palettes::palette(&name)
2544 .iter()
2545 .map(|c| (c.r, c.g, c.b))
2546 .collect();
2547 let s =
2548 crate::scale::steps::ScaleColorSteps::new(crate::aes::Aesthetic::Color, stops, n_bins);
2549 self.scale_color(s)
2550 }
2551
2552 pub fn scale_color_steps2(
2556 self,
2557 low: crate::scale::color::RGBAColor,
2558 mid: crate::scale::color::RGBAColor,
2559 high: crate::scale::color::RGBAColor,
2560 midpoint: f64,
2561 n_bins: usize,
2562 ) -> Self {
2563 self.scale_color(crate::scale::steps::ScaleColorSteps::diverging(
2564 crate::aes::Aesthetic::Color,
2565 (low.r, low.g, low.b),
2566 (mid.r, mid.g, mid.b),
2567 (high.r, high.g, high.b),
2568 midpoint,
2569 n_bins,
2570 ))
2571 }
2572
2573 pub fn scale_fill_steps2(
2576 self,
2577 low: crate::scale::color::RGBAColor,
2578 mid: crate::scale::color::RGBAColor,
2579 high: crate::scale::color::RGBAColor,
2580 midpoint: f64,
2581 n_bins: usize,
2582 ) -> Self {
2583 self.scale_fill(crate::scale::steps::ScaleColorSteps::diverging(
2584 crate::aes::Aesthetic::Fill,
2585 (low.r, low.g, low.b),
2586 (mid.r, mid.g, mid.b),
2587 (high.r, high.g, high.b),
2588 midpoint,
2589 n_bins,
2590 ))
2591 }
2592
2593 pub fn scale_color_viridis_b(self, option: char, n_bins: usize) -> Self {
2596 self.scale_color(crate::scale::steps::ScaleColorSteps::viridis(
2597 crate::aes::Aesthetic::Color,
2598 option,
2599 n_bins,
2600 ))
2601 }
2602
2603 pub fn scale_fill_viridis_b(self, option: char, n_bins: usize) -> Self {
2606 self.scale_fill(crate::scale::steps::ScaleColorSteps::viridis(
2607 crate::aes::Aesthetic::Fill,
2608 option,
2609 n_bins,
2610 ))
2611 }
2612
2613 pub fn scale_fill_steps(
2614 self,
2615 low: crate::scale::color::RGBAColor,
2616 high: crate::scale::color::RGBAColor,
2617 n_bins: usize,
2618 ) -> Self {
2619 let s = crate::scale::steps::ScaleColorSteps::two(
2620 crate::aes::Aesthetic::Fill,
2621 (low.r, low.g, low.b),
2622 (high.r, high.g, high.b),
2623 n_bins,
2624 );
2625 self.scale_fill(s)
2626 }
2627
2628 pub fn scale_fill_binned(
2639 self,
2640 breaks: Vec<f64>,
2641 low: crate::scale::color::RGBAColor,
2642 high: crate::scale::color::RGBAColor,
2643 ) -> Self {
2644 let s = crate::scale::binned::ScaleFillBinned::two(
2645 crate::aes::Aesthetic::Fill,
2646 breaks,
2647 (low.r, low.g, low.b),
2648 (high.r, high.g, high.b),
2649 );
2650 self.scale_fill(s)
2651 }
2652
2653 pub fn scale_fill_binned_with(
2657 self,
2658 breaks: Vec<f64>,
2659 colors: Vec<crate::scale::color::RGBAColor>,
2660 ) -> Self {
2661 let s = crate::scale::binned::ScaleFillBinned::new(
2662 crate::aes::Aesthetic::Fill,
2663 breaks,
2664 colors.iter().map(|c| (c.r, c.g, c.b)).collect(),
2665 );
2666 self.scale_fill(s)
2667 }
2668
2669 pub fn scale_fill_fermenter(
2671 self,
2672 name: crate::scale::palettes::PaletteName,
2673 n_bins: usize,
2674 ) -> Self {
2675 let stops = crate::scale::palettes::palette(&name)
2676 .iter()
2677 .map(|c| (c.r, c.g, c.b))
2678 .collect();
2679 let s =
2680 crate::scale::steps::ScaleColorSteps::new(crate::aes::Aesthetic::Fill, stops, n_bins);
2681 self.scale_fill(s)
2682 }
2683
2684 pub fn scale_fill_discrete_sorted(self) -> Self {
2689 use crate::scale::color::ScaleColorDiscrete;
2690 self.scale_fill(ScaleColorDiscrete::new(crate::aes::Aesthetic::Fill).sorted())
2691 }
2692
2693 pub fn scale_color_discrete_sorted(self) -> Self {
2696 use crate::scale::color::ScaleColorDiscrete;
2697 self.scale_color(ScaleColorDiscrete::new(crate::aes::Aesthetic::Color).sorted())
2698 }
2699
2700 pub fn scale_color_hue(self, p: crate::scale::color::HuePalette) -> Self {
2704 self.scale_color(
2705 crate::scale::color::ScaleColorDiscrete::new(crate::aes::Aesthetic::Color)
2706 .with_generated(crate::scale::color::GeneratedPalette::Hue(p)),
2707 )
2708 }
2709
2710 pub fn scale_fill_hue(self, p: crate::scale::color::HuePalette) -> Self {
2712 self.scale_fill(
2713 crate::scale::color::ScaleColorDiscrete::new(crate::aes::Aesthetic::Fill)
2714 .with_generated(crate::scale::color::GeneratedPalette::Hue(p)),
2715 )
2716 }
2717
2718 pub fn scale_color_viridis_d(self, option: char, begin: f64, end: f64, direction: i32) -> Self {
2721 self.scale_color(
2722 crate::scale::color::ScaleColorDiscrete::new(crate::aes::Aesthetic::Color)
2723 .with_generated(crate::scale::color::GeneratedPalette::Viridis {
2724 option,
2725 begin,
2726 end,
2727 direction,
2728 }),
2729 )
2730 }
2731
2732 pub fn scale_fill_viridis_d(self, option: char, begin: f64, end: f64, direction: i32) -> Self {
2734 self.scale_fill(
2735 crate::scale::color::ScaleColorDiscrete::new(crate::aes::Aesthetic::Fill)
2736 .with_generated(crate::scale::color::GeneratedPalette::Viridis {
2737 option,
2738 begin,
2739 end,
2740 direction,
2741 }),
2742 )
2743 }
2744
2745 pub fn scale_color_distiller(
2749 self,
2750 palette: crate::scale::palettes::PaletteName,
2751 direction: i32,
2752 ) -> Self {
2753 self.scale_color(distiller(crate::aes::Aesthetic::Color, &palette, direction))
2754 }
2755
2756 pub fn scale_fill_distiller(
2758 self,
2759 palette: crate::scale::palettes::PaletteName,
2760 direction: i32,
2761 ) -> Self {
2762 self.scale_fill(distiller(crate::aes::Aesthetic::Fill, &palette, direction))
2763 }
2764
2765 pub fn expand_limits(self, x: &[f64], y: &[f64]) -> Self {
2769 let n = x.len().max(y.len());
2770 if n == 0 {
2771 return self;
2772 }
2773 let col =
2774 |v: &[f64]| -> Vec<Value> { (0..n).map(|i| Value::Float(v[i % v.len()])).collect() };
2775 let mut data = Vec::new();
2776 let mut aes = Aes::new();
2777 if !x.is_empty() {
2778 data.push(("x".to_string(), col(x)));
2779 aes = aes.x("x");
2780 }
2781 if !y.is_empty() {
2782 data.push(("y".to_string(), col(y)));
2783 aes = aes.y("y");
2784 }
2785 self.geom_blank().layer_data(data).layer_aes(aes)
2786 }
2787
2788 pub fn scale_fill_brewer(self, name: crate::scale::palettes::PaletteName) -> Self {
2789 use crate::scale::color::ScaleColorDiscrete;
2790 let s = ScaleColorDiscrete::new(crate::aes::Aesthetic::Fill).with_named_palette(&name);
2791 self.scale_fill(s)
2792 }
2793
2794 pub fn scale_linetype_manual(
2795 self,
2796 values: Vec<(&str, crate::render::backend::Linetype)>,
2797 ) -> Self {
2798 let s = crate::scale::linetype_manual::ScaleLinetypeManual::new(values);
2799 self.scale_color(s)
2800 }
2801
2802 pub fn scale_shape_manual(
2803 self,
2804 values: Vec<(&str, crate::render::backend::PointShape)>,
2805 ) -> Self {
2806 let s = crate::scale::shape_manual::ScaleShapeManual::new(values);
2807 self.scale_color(s)
2808 }
2809
2810 pub fn scale_color_grey(self) -> Self {
2811 let s = crate::scale::grey::ScaleColorGrey::new(crate::aes::Aesthetic::Color);
2812 self.scale_color(s)
2813 }
2814
2815 pub fn scale_fill_grey(self) -> Self {
2816 let s = crate::scale::grey::ScaleColorGrey::new(crate::aes::Aesthetic::Fill);
2817 self.scale_fill(s)
2818 }
2819
2820 pub fn scale_color_grey_with(self, s: crate::scale::grey::ScaleColorGrey) -> Self {
2821 self.scale_color(s)
2822 }
2823
2824 pub fn scale_fill_grey_with(self, s: crate::scale::grey::ScaleColorGrey) -> Self {
2825 self.scale_fill(s)
2826 }
2827
2828 pub fn scale_x_reverse(self) -> Self {
2829 self.scale_x_continuous(ScaleContinuous::new().with_transform(ScaleTransform::Reverse))
2830 }
2831
2832 pub fn scale_y_reverse(self) -> Self {
2833 self.scale_y_continuous(ScaleContinuous::new().with_transform(ScaleTransform::Reverse))
2834 }
2835
2836 pub fn scale_x_datetime(mut self, s: crate::scale::datetime::ScaleDateTime) -> Self {
2837 let s = s.for_aesthetic(crate::aes::Aesthetic::X);
2838 self.scales.push(Box::new(s));
2839 self
2840 }
2841
2842 pub fn scale_y_datetime(mut self, s: crate::scale::datetime::ScaleDateTime) -> Self {
2843 let s = s.for_aesthetic(crate::aes::Aesthetic::Y);
2844 self.scales.push(Box::new(s));
2845 self
2846 }
2847
2848 pub fn scale_size(mut self, s: crate::scale::size::ScaleSizeContinuous) -> Self {
2849 self.scales.push(Box::new(s));
2850 self
2851 }
2852
2853 pub fn scale_size_area(mut self, max_size: f64) -> Self {
2857 self.scales.push(Box::new(
2858 crate::scale::size::ScaleSizeContinuous::new().area(max_size),
2859 ));
2860 self
2861 }
2862
2863 pub fn scale_radius(self, min: f64, max: f64) -> Self {
2866 self.scale_size(crate::scale::size::ScaleSizeContinuous::new().with_range(min, max))
2867 }
2868
2869 pub fn scale_size_binned(self, n: usize) -> Self {
2871 self.scale_color(crate::scale::values::ScaleValueBinned::new(
2872 crate::aes::Aesthetic::Size,
2873 n,
2874 ))
2875 }
2876
2877 pub fn scale_alpha_binned(self, n: usize) -> Self {
2879 self.scale_color(crate::scale::values::ScaleValueBinned::new(
2880 crate::aes::Aesthetic::Alpha,
2881 n,
2882 ))
2883 }
2884
2885 pub fn scale_linewidth_binned(self, n: usize) -> Self {
2887 self.scale_color(crate::scale::values::ScaleValueBinned::new(
2888 crate::aes::Aesthetic::Linewidth,
2889 n,
2890 ))
2891 }
2892
2893 pub fn scale_shape_binned(self, n: usize) -> Self {
2895 self.scale_color(crate::scale::values::ScaleValueBinned::new(
2896 crate::aes::Aesthetic::Shape,
2897 n,
2898 ))
2899 }
2900
2901 pub fn scale_linetype_binned(self, n: usize) -> Self {
2903 self.scale_color(crate::scale::values::ScaleValueBinned::new(
2904 crate::aes::Aesthetic::Linetype,
2905 n,
2906 ))
2907 }
2908
2909 pub fn scale_size_manual(self, values: Vec<(&str, f64)>) -> Self {
2911 self.scale_color(crate::scale::values::ScaleValueManual::new(
2912 crate::aes::Aesthetic::Size,
2913 values,
2914 ))
2915 }
2916
2917 pub fn scale_alpha_manual(self, values: Vec<(&str, f64)>) -> Self {
2919 self.scale_color(crate::scale::values::ScaleValueManual::new(
2920 crate::aes::Aesthetic::Alpha,
2921 values,
2922 ))
2923 }
2924
2925 pub fn scale_linewidth_manual(self, values: Vec<(&str, f64)>) -> Self {
2927 self.scale_color(crate::scale::values::ScaleValueManual::new(
2928 crate::aes::Aesthetic::Linewidth,
2929 values,
2930 ))
2931 }
2932
2933 pub fn scale_size_identity(self) -> Self {
2935 self.scale_color(crate::scale::values::ScaleValueIdentity::new(
2936 crate::aes::Aesthetic::Size,
2937 ))
2938 }
2939
2940 pub fn scale_alpha_identity(self) -> Self {
2942 self.scale_color(crate::scale::values::ScaleValueIdentity::new(
2943 crate::aes::Aesthetic::Alpha,
2944 ))
2945 }
2946
2947 pub fn scale_linewidth_identity(self) -> Self {
2950 self.scale_color(crate::scale::values::ScaleValueIdentity::new(
2951 crate::aes::Aesthetic::Linewidth,
2952 ))
2953 }
2954
2955 pub fn scale_shape_identity(self) -> Self {
2958 self.scale_color(crate::scale::values::ScaleValueIdentity::new(
2959 crate::aes::Aesthetic::Shape,
2960 ))
2961 }
2962
2963 pub fn scale_alpha(mut self, s: crate::scale::alpha::ScaleAlphaContinuous) -> Self {
2964 self.scales.push(Box::new(s));
2965 self
2966 }
2967
2968 pub fn scale_linewidth(mut self, s: crate::scale::linewidth::ScaleLinewidthContinuous) -> Self {
2972 self.scales.push(Box::new(s));
2973 self
2974 }
2975
2976 pub fn xlim(self, min: f64, max: f64) -> Self {
2977 self.scale_x_continuous(ScaleContinuous::new().with_limits(min, max))
2978 }
2979
2980 pub fn ylim(self, min: f64, max: f64) -> Self {
2981 self.scale_y_continuous(ScaleContinuous::new().with_limits(min, max))
2982 }
2983
2984 pub fn scale_x_log10(self) -> Self {
2985 self.scale_x_continuous(ScaleContinuous::new().with_transform(ScaleTransform::Log10))
2986 }
2987
2988 pub fn scale_y_log10(self) -> Self {
2989 self.scale_y_continuous(ScaleContinuous::new().with_transform(ScaleTransform::Log10))
2990 }
2991
2992 pub fn scale_x_sqrt(self) -> Self {
2993 self.scale_x_continuous(ScaleContinuous::new().with_transform(ScaleTransform::Sqrt))
2994 }
2995
2996 pub fn scale_y_sqrt(self) -> Self {
2997 self.scale_y_continuous(ScaleContinuous::new().with_transform(ScaleTransform::Sqrt))
2998 }
2999
3000 pub fn scale_x_log2(self) -> Self {
3001 self.scale_x_continuous(ScaleContinuous::new().with_transform(ScaleTransform::Log2))
3002 }
3003
3004 pub fn scale_y_log2(self) -> Self {
3005 self.scale_y_continuous(ScaleContinuous::new().with_transform(ScaleTransform::Log2))
3006 }
3007
3008 pub fn scale_x_ln(self) -> Self {
3009 self.scale_x_continuous(ScaleContinuous::new().with_transform(ScaleTransform::Ln))
3010 }
3011
3012 pub fn scale_y_ln(self) -> Self {
3013 self.scale_y_continuous(ScaleContinuous::new().with_transform(ScaleTransform::Ln))
3014 }
3015
3016 pub fn scale_x_logit(self) -> Self {
3018 self.scale_x_continuous(ScaleContinuous::new().with_transform(ScaleTransform::Logit))
3019 }
3020
3021 pub fn scale_y_logit(self) -> Self {
3022 self.scale_y_continuous(ScaleContinuous::new().with_transform(ScaleTransform::Logit))
3023 }
3024
3025 pub fn scale_x_probit(self) -> Self {
3027 self.scale_x_continuous(ScaleContinuous::new().with_transform(ScaleTransform::Probit))
3028 }
3029
3030 pub fn scale_y_probit(self) -> Self {
3031 self.scale_y_continuous(ScaleContinuous::new().with_transform(ScaleTransform::Probit))
3032 }
3033
3034 pub fn scale_x_pseudo_log(self) -> Self {
3036 self.scale_x_continuous(ScaleContinuous::new().with_transform(ScaleTransform::PseudoLog))
3037 }
3038
3039 pub fn scale_y_pseudo_log(self) -> Self {
3040 self.scale_y_continuous(ScaleContinuous::new().with_transform(ScaleTransform::PseudoLog))
3041 }
3042
3043 pub fn scale_x_reciprocal(self) -> Self {
3045 self.scale_x_continuous(ScaleContinuous::new().with_transform(ScaleTransform::Reciprocal))
3046 }
3047
3048 pub fn scale_y_reciprocal(self) -> Self {
3049 self.scale_y_continuous(ScaleContinuous::new().with_transform(ScaleTransform::Reciprocal))
3050 }
3051
3052 pub fn scale_x_exp(self) -> Self {
3054 self.scale_x_continuous(ScaleContinuous::new().with_transform(ScaleTransform::Exp))
3055 }
3056
3057 pub fn scale_y_exp(self) -> Self {
3058 self.scale_y_continuous(ScaleContinuous::new().with_transform(ScaleTransform::Exp))
3059 }
3060
3061 pub fn scale_x_time(self) -> Self {
3065 self.scale_x_continuous(ScaleContinuous::time())
3066 }
3067
3068 pub fn scale_y_time(self) -> Self {
3070 self.scale_y_continuous(ScaleContinuous::time())
3071 }
3072
3073 pub fn scale_x_binned(self, n: usize) -> Self {
3077 self.scale_x_continuous(ScaleContinuous::binned(n))
3078 }
3079
3080 pub fn scale_y_binned(self, n: usize) -> Self {
3082 self.scale_y_continuous(ScaleContinuous::binned(n))
3083 }
3084
3085 pub fn scale_x_boxcox(self, lambda: f64) -> Self {
3086 self.scale_x_continuous(
3087 ScaleContinuous::new().with_transform(ScaleTransform::BoxCox(lambda)),
3088 )
3089 }
3090
3091 pub fn scale_y_boxcox(self, lambda: f64) -> Self {
3092 self.scale_y_continuous(
3093 ScaleContinuous::new().with_transform(ScaleTransform::BoxCox(lambda)),
3094 )
3095 }
3096
3097 pub fn facet_wrap(mut self, var: &str, ncol: Option<usize>) -> Self {
3100 self.facet = Facet::Wrap {
3101 var: var.to_string(),
3102 ncol,
3103 scales: FacetScales::Fixed,
3104 labeller: FacetLabeller::default(),
3105 levels: None,
3106 vertical: false,
3107 as_table: true,
3108 strip_position: crate::facet::StripPosition::Top,
3109 space: FacetSpace::Fixed,
3110 };
3111 self
3112 }
3113
3114 pub fn facet_wrap_free(mut self, var: &str, ncol: Option<usize>, scales: FacetScales) -> Self {
3115 self.facet = Facet::Wrap {
3116 var: var.to_string(),
3117 ncol,
3118 scales,
3119 labeller: FacetLabeller::default(),
3120 levels: None,
3121 vertical: false,
3122 as_table: true,
3123 strip_position: crate::facet::StripPosition::Top,
3124 space: FacetSpace::Fixed,
3125 };
3126 self
3127 }
3128
3129 pub fn facet_wrap_labeller(
3130 mut self,
3131 var: &str,
3132 ncol: Option<usize>,
3133 labeller: FacetLabeller,
3134 ) -> Self {
3135 self.facet = Facet::Wrap {
3136 var: var.to_string(),
3137 ncol,
3138 scales: FacetScales::Fixed,
3139 labeller,
3140 levels: None,
3141 vertical: false,
3142 as_table: true,
3143 strip_position: crate::facet::StripPosition::Top,
3144 space: FacetSpace::Fixed,
3145 };
3146 self
3147 }
3148
3149 pub fn facet_wrap_dir(mut self, vertical: bool, as_table: bool) -> Self {
3153 if let Facet::Wrap {
3154 vertical: v,
3155 as_table: a,
3156 ..
3157 } = &mut self.facet
3158 {
3159 *v = vertical;
3160 *a = as_table;
3161 }
3162 self
3163 }
3164
3165 pub fn facet_axes(mut self, axes: crate::facet::FacetAxes) -> Self {
3168 self.facet_axes = axes;
3169 self
3170 }
3171
3172 pub fn facet_labeller(mut self, l: FacetLabeller) -> Self {
3176 match &mut self.facet {
3177 Facet::Wrap { labeller, .. } | Facet::Grid { labeller, .. } => *labeller = l,
3178 Facet::None => {}
3179 }
3180 self
3181 }
3182
3183 pub fn facet_wrap_space(mut self, space: FacetSpace) -> Self {
3187 if let Facet::Wrap { space: s, .. } = &mut self.facet {
3188 *s = space;
3189 }
3190 self
3191 }
3192
3193 pub fn facet_strip_position(mut self, position: crate::facet::StripPosition) -> Self {
3197 if let Facet::Wrap { strip_position, .. } = &mut self.facet {
3198 *strip_position = position;
3199 }
3200 self
3201 }
3202
3203 pub fn facet_grid_levels<S: AsRef<str>>(
3207 mut self,
3208 rows: Option<&[S]>,
3209 cols: Option<&[S]>,
3210 ) -> Self {
3211 let dedup = |l: &[S]| {
3212 let mut seen = Vec::<String>::new();
3213 for s in l {
3214 if !seen.iter().any(|x| x == s.as_ref()) {
3215 seen.push(s.as_ref().to_string());
3216 }
3217 }
3218 seen
3219 };
3220 if let Facet::Grid {
3221 row_levels,
3222 col_levels,
3223 ..
3224 } = &mut self.facet
3225 {
3226 *row_levels = rows.map(dedup);
3227 *col_levels = cols.map(dedup);
3228 }
3229 self
3230 }
3231
3232 pub fn facet_margins(mut self, on: bool) -> Self {
3236 if let Facet::Grid { margins, .. } = &mut self.facet {
3237 *margins = on;
3238 }
3239 self
3240 }
3241
3242 pub fn facet_switch(mut self, switch: crate::facet::FacetSwitch) -> Self {
3246 if let Facet::Grid { switch: s, .. } = &mut self.facet {
3247 *s = switch;
3248 }
3249 self
3250 }
3251
3252 pub fn facet_levels<S: AsRef<str>>(mut self, levels: &[S]) -> Self {
3259 if let Facet::Wrap { levels: l, .. } = &mut self.facet {
3260 let mut seen = Vec::<String>::new();
3261 for s in levels {
3262 if !seen.iter().any(|x| x == s.as_ref()) {
3263 seen.push(s.as_ref().to_string());
3264 }
3265 }
3266 *l = Some(seen);
3267 }
3268 self
3269 }
3270
3271 pub fn facet_grid(mut self, row: Option<&str>, col: Option<&str>) -> Self {
3272 self.facet = Facet::Grid {
3273 row_var: row.map(String::from),
3274 col_var: col.map(String::from),
3275 scales: FacetScales::Fixed,
3276 labeller: FacetLabeller::default(),
3277 space: FacetSpace::Fixed,
3278 switch: crate::facet::FacetSwitch::None,
3279 row_levels: None,
3280 col_levels: None,
3281 margins: false,
3282 };
3283 self
3284 }
3285
3286 pub fn facet_grid_free(
3287 mut self,
3288 row: Option<&str>,
3289 col: Option<&str>,
3290 scales: FacetScales,
3291 ) -> Self {
3292 self.facet = Facet::Grid {
3293 row_var: row.map(String::from),
3294 col_var: col.map(String::from),
3295 scales,
3296 labeller: FacetLabeller::default(),
3297 space: FacetSpace::Fixed,
3298 switch: crate::facet::FacetSwitch::None,
3299 row_levels: None,
3300 col_levels: None,
3301 margins: false,
3302 };
3303 self
3304 }
3305
3306 pub fn facet_grid_multi(
3310 mut self,
3311 row: Option<&str>,
3312 cols: &[&str],
3313 scales: FacetScales,
3314 space: FacetSpace,
3315 ) -> Self {
3316 let col_var = if cols.len() > 1 {
3317 let n = self.data.nrows();
3319 let mut combined = Vec::with_capacity(n);
3320 for i in 0..n {
3321 let parts: Vec<String> = cols
3322 .iter()
3323 .map(|c| {
3324 self.data
3325 .column(c)
3326 .and_then(|col| col.get(i))
3327 .map(|v| v.to_group_key())
3328 .unwrap_or_default()
3329 })
3330 .collect();
3331 combined.push(crate::data::Value::Str(parts.join(" . ")));
3332 }
3333 let name = "__facet_cols__".to_string();
3334 self.data.add_column(name.clone(), combined);
3335 Some(name)
3336 } else {
3337 cols.first().map(|s| s.to_string())
3338 };
3339 self.facet = Facet::Grid {
3340 row_var: row.map(String::from),
3341 col_var,
3342 scales,
3343 labeller: FacetLabeller::default(),
3344 space,
3345 switch: crate::facet::FacetSwitch::None,
3346 row_levels: None,
3347 col_levels: None,
3348 margins: false,
3349 };
3350 self
3351 }
3352
3353 pub fn facet_grid_space(
3356 mut self,
3357 row: Option<&str>,
3358 col: Option<&str>,
3359 scales: FacetScales,
3360 space: FacetSpace,
3361 ) -> Self {
3362 self.facet = Facet::Grid {
3363 row_var: row.map(String::from),
3364 col_var: col.map(String::from),
3365 scales,
3366 labeller: FacetLabeller::default(),
3367 space,
3368 switch: crate::facet::FacetSwitch::None,
3369 row_levels: None,
3370 col_levels: None,
3371 margins: false,
3372 };
3373 self
3374 }
3375
3376 pub fn facet_grid_labeller(
3377 mut self,
3378 row: Option<&str>,
3379 col: Option<&str>,
3380 labeller: FacetLabeller,
3381 ) -> Self {
3382 self.facet = Facet::Grid {
3383 row_var: row.map(String::from),
3384 col_var: col.map(String::from),
3385 scales: FacetScales::Fixed,
3386 labeller,
3387 space: FacetSpace::Fixed,
3388 switch: crate::facet::FacetSwitch::None,
3389 row_levels: None,
3390 col_levels: None,
3391 margins: false,
3392 };
3393 self
3394 }
3395
3396 pub fn coord_flip(mut self) -> Self {
3399 self.coord = Box::new(CoordFlip);
3400 self
3401 }
3402
3403 pub fn coord_fixed(mut self, ratio: f64) -> Self {
3404 self.coord = Box::new(CoordFixed::new(ratio));
3405 self
3406 }
3407
3408 #[cfg(feature = "sf")]
3412 pub fn coord_sf(mut self) -> Self {
3413 self.coord = Box::new(crate::coord::sf::CoordSf::new());
3414 self
3415 }
3416
3417 #[cfg(feature = "sf")]
3422 pub fn coord_sf_with(mut self, coord: crate::coord::sf::CoordSf) -> Self {
3423 self.coord = Box::new(coord);
3424 self
3425 }
3426
3427 pub fn svg_root_data(mut self, on: bool) -> Self {
3434 self.svg_root_data = on;
3435 self
3436 }
3437
3438 pub fn svg_attr(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
3448 self.root_attrs.push((name.into(), value.into()));
3449 self
3450 }
3451
3452 pub fn svg_attrs(mut self, attrs: impl IntoIterator<Item = (String, String)>) -> Self {
3454 self.root_attrs.extend(attrs);
3455 self
3456 }
3457
3458 pub fn svg_warnings_attr(mut self, on: bool) -> Self {
3463 self.svg_warnings_attr = on;
3464 self
3465 }
3466
3467 pub fn svg_semantic_classes(mut self, on: bool) -> Self {
3486 self.svg_classes = on;
3487 self
3488 }
3489
3490 pub fn svg_formatted_values(mut self, on: bool) -> Self {
3491 self.svg_formatted_values = on;
3492 self
3493 }
3494
3495 pub fn svg_title(mut self, title: impl Into<String>) -> Self {
3505 self.svg_title = Some(title.into());
3506 self
3507 }
3508
3509 pub fn svg_desc(mut self, desc: impl Into<String>) -> Self {
3517 self.svg_desc = Some(desc.into());
3518 self
3519 }
3520
3521 pub fn coord_trans(mut self, x: Option<ScaleTransform>, y: Option<ScaleTransform>) -> Self {
3526 self.coord = Box::new(crate::coord::trans::CoordTrans::new(x, y));
3527 self
3528 }
3529
3530 pub fn coord_transform(self, x: Option<ScaleTransform>, y: Option<ScaleTransform>) -> Self {
3532 self.coord_trans(x, y)
3533 }
3534
3535 pub fn coord_quickmap(mut self) -> Self {
3538 self.coord = Box::new(crate::coord::map::CoordMap::new(
3539 crate::coord::map::MapProjection::Quick,
3540 ));
3541 self
3542 }
3543
3544 pub fn coord_map(mut self) -> Self {
3548 self.coord = Box::new(crate::coord::map::CoordMap::new(
3549 crate::coord::map::MapProjection::Mercator,
3550 ));
3551 self
3552 }
3553
3554 pub fn coord_cartesian_with(mut self, coord: CoordCartesian) -> Self {
3556 self.coord = Box::new(coord);
3557 self
3558 }
3559
3560 pub fn direct_labels(mut self) -> Self {
3571 self.direct_labels = true;
3572 self
3573 }
3574
3575 pub fn coord_clip(mut self, on: bool) -> Self {
3579 self.clip = on;
3580 self
3581 }
3582
3583 pub fn coord_reverse(mut self, x: bool, y: bool) -> Self {
3585 self.coord = Box::new(CoordCartesian::new().reverse(x, y));
3586 self
3587 }
3588
3589 pub fn coord_radial(mut self, start: f64, end: f64, inner_radius: f64) -> Self {
3594 let mut c = CoordPolar::new();
3595 c.start = start;
3596 c.span = end - start;
3597 c.inner_radius = inner_radius.clamp(0.0, 0.99);
3598 self.coord = Box::new(c);
3599 self
3600 }
3601
3602 pub fn coord_trans_y(self, y: ScaleTransform) -> Self {
3604 self.coord_trans(None, Some(y))
3605 }
3606
3607 pub fn coord_trans_x(self, x: ScaleTransform) -> Self {
3609 self.coord_trans(Some(x), None)
3610 }
3611
3612 pub fn coord_cartesian_zoom(
3614 mut self,
3615 xlim: Option<(f64, f64)>,
3616 ylim: Option<(f64, f64)>,
3617 ) -> Self {
3618 let mut c = CoordCartesian::new();
3619 if let Some((min, max)) = xlim {
3620 c = c.xlim(min, max);
3621 }
3622 if let Some((min, max)) = ylim {
3623 c = c.ylim(min, max);
3624 }
3625 self.coord = Box::new(c);
3626 self
3627 }
3628
3629 pub fn coord_polar(mut self) -> Self {
3630 self.coord = Box::new(CoordPolar::new());
3631 self
3632 }
3633
3634 pub fn coord_radar(mut self) -> Self {
3638 self.coord = Box::new(crate::coord::radar::CoordRadar::new());
3639 self
3640 }
3641
3642 pub fn coord_radar_with(mut self, coord: crate::coord::radar::CoordRadar) -> Self {
3643 self.coord = Box::new(coord);
3644 self
3645 }
3646
3647 pub fn coord_polar_with(mut self, coord: CoordPolar) -> Self {
3648 self.coord = Box::new(coord);
3649 self
3650 }
3651
3652 pub fn theme(mut self, theme: Theme) -> Self {
3657 self.apply_preset(theme);
3658 self
3659 }
3660
3661 fn apply_preset(&mut self, theme: Theme) {
3662 let primary = self.theme.primary;
3663 self.theme = theme;
3664 if self.theme.primary.is_none() {
3665 self.theme.primary = primary;
3666 }
3667 }
3668
3669 pub fn axis_text_x_angle(mut self, degrees: f64) -> Self {
3673 self.theme.axis_text_x.angle = degrees;
3674 self
3675 }
3676
3677 pub fn axis_text_y_angle(mut self, degrees: f64) -> Self {
3679 self.theme.axis_text_y.angle = degrees;
3680 self
3681 }
3682
3683 pub fn axis_text_x_dodge(mut self, n: usize) -> Self {
3686 self.theme.axis_text_x_dodge = n.max(1);
3687 self
3688 }
3689
3690 pub fn aspect_ratio(mut self, ratio: f64) -> Self {
3693 self.theme.aspect_ratio = Some(ratio);
3694 self
3695 }
3696
3697 pub fn panel_ontop(mut self) -> Self {
3699 self.theme.panel_ontop = true;
3700 self
3701 }
3702
3703 pub fn axis_minor_ticks(mut self) -> Self {
3705 self.theme.axis_minor_ticks = true;
3706 self
3707 }
3708
3709 pub fn axis_text_x_fit(mut self, fit: crate::theme::AxisLabelFit) -> Self {
3714 self.theme.axis_text_x_fit = fit;
3715 self
3716 }
3717
3718 pub fn axis_text_x_check_overlap(mut self, on: bool) -> Self {
3721 self.theme.axis_text_x_check_overlap = on;
3722 self
3723 }
3724
3725 pub fn title_position(mut self, pos: crate::theme::TitlePosition) -> Self {
3728 self.theme.title_position = pos;
3729 self
3730 }
3731
3732 pub fn tag_position(mut self, pos: crate::theme::TagPosition) -> Self {
3734 self.theme.tag_position = pos;
3735 self
3736 }
3737
3738 pub fn legend_direction(mut self, dir: crate::theme::LegendDirection) -> Self {
3740 self.theme.legend_direction = Some(dir);
3741 self
3742 }
3743
3744 pub fn legend_position_inside(mut self, x: f64, y: f64) -> Self {
3751 self.theme.legend_position = crate::theme::LegendPosition::Inside(x, y);
3752 self
3753 }
3754
3755 pub fn legend_position(mut self, pos: crate::theme::LegendPosition) -> Self {
3757 self.theme.legend_position = pos;
3758 self
3759 }
3760
3761 pub fn legend_bottom_when_narrow(mut self, share: f64) -> Self {
3768 self.legend_bottom_share = Some(share);
3769 self
3770 }
3771
3772 pub fn legend_inside_auto(self) -> Self {
3783 self.legend_inside_auto_with(&crate::theme::LegendCorner::ALL, None)
3784 }
3785
3786 pub fn legend_inside_auto_with(
3791 mut self,
3792 corners: &[crate::theme::LegendCorner],
3793 fallback: Option<crate::theme::LegendPosition>,
3794 ) -> Self {
3795 use crate::theme::LegendPosition as P;
3796 let mut c = [None; 4];
3797 for (slot, corner) in c.iter_mut().zip(corners) {
3798 *slot = Some(*corner);
3799 }
3800 let fallback = match fallback {
3801 Some(P::Top) => Some(LegendSide::Top),
3802 Some(P::Right) => Some(LegendSide::Right),
3803 Some(P::Bottom) => Some(LegendSide::Bottom),
3804 Some(P::Left) => Some(LegendSide::Left),
3805 _ => None,
3806 };
3807 self.legend_auto = Some(LegendAuto {
3808 corners: c,
3809 fallback,
3810 });
3811 self
3812 }
3813
3814 pub fn primary_color(mut self, color: (u8, u8, u8)) -> Self {
3815 self.theme.primary = Some(color);
3816 self
3817 }
3818
3819 pub fn theme_minimal(mut self) -> Self {
3820 self.apply_preset(crate::theme::presets::theme_minimal());
3821 self
3822 }
3823
3824 pub fn theme_test(mut self) -> Self {
3826 self.apply_preset(crate::theme::presets::theme_test());
3827 self
3828 }
3829
3830 pub fn theme_bw(mut self) -> Self {
3831 self.apply_preset(crate::theme::presets::theme_bw());
3832 self
3833 }
3834
3835 pub fn theme_gray(mut self) -> Self {
3836 self.apply_preset(crate::theme::presets::theme_gray());
3837 self
3838 }
3839
3840 pub fn theme_classic(mut self) -> Self {
3841 self.apply_preset(crate::theme::presets::theme_classic());
3842 self
3843 }
3844
3845 pub fn theme_pubr(mut self) -> Self {
3847 self.apply_preset(crate::theme::presets::theme_pubr());
3848 self
3849 }
3850
3851 pub fn theme_linedraw(mut self) -> Self {
3852 self.apply_preset(crate::theme::presets::theme_linedraw());
3853 self
3854 }
3855
3856 pub fn theme_light(mut self) -> Self {
3857 self.apply_preset(crate::theme::presets::theme_light());
3858 self
3859 }
3860
3861 pub fn theme_dark(mut self) -> Self {
3862 self.apply_preset(crate::theme::presets::theme_dark());
3863 self
3864 }
3865
3866 pub fn theme_void(mut self) -> Self {
3867 self.apply_preset(crate::theme::presets::theme_void());
3868 self
3869 }
3870
3871 pub fn theme_update(mut self, update: crate::theme::ThemeUpdate) -> Self {
3874 self.theme = self.theme.update(update);
3875 self
3876 }
3877
3878 pub fn theme_replace(self, update: crate::theme::ThemeUpdate) -> Self {
3883 self.theme_update(update)
3884 }
3885
3886 pub fn theme_with(mut self, f: impl FnOnce(&mut Theme)) -> Self {
3890 f(&mut self.theme);
3891 self
3892 }
3893
3894 pub fn guides(mut self, mut guide: crate::guide::config::GuideLegend) -> Self {
3898 if guide.hidden.is_empty() {
3902 guide.hidden = std::mem::take(&mut self.guide_legend.hidden);
3903 }
3904 if guide.titles.is_empty() {
3905 guide.titles = std::mem::take(&mut self.guide_legend.titles);
3906 }
3907 if guide.reversed.is_empty() {
3908 guide.reversed = std::mem::take(&mut self.guide_legend.reversed);
3909 }
3910 if guide.colourbars.is_empty() {
3911 guide.colourbars = std::mem::take(&mut self.guide_legend.colourbars);
3912 }
3913 if guide.overrides.is_empty() {
3914 guide.overrides = std::mem::take(&mut self.guide_legend.overrides);
3915 }
3916 if guide.bins.is_empty() {
3917 guide.bins = std::mem::take(&mut self.guide_legend.bins);
3918 }
3919 if guide.plain_keys.is_empty() {
3920 guide.plain_keys = std::mem::take(&mut self.guide_legend.plain_keys);
3921 }
3922 if guide.custom.is_empty() {
3923 guide.custom = std::mem::take(&mut self.guide_legend.custom);
3924 }
3925 if guide.positions.is_empty() {
3926 guide.positions = std::mem::take(&mut self.guide_legend.positions);
3927 }
3928 self.guide_legend = guide;
3929 self
3930 }
3931
3932 pub fn labs(mut self, labels: Labels) -> Self {
3935 if labels.title.is_some() {
3936 self.labels.title = labels.title;
3937 }
3938 if labels.subtitle.is_some() {
3939 self.labels.subtitle = labels.subtitle;
3940 }
3941 if labels.x.is_some() {
3942 self.labels.x = labels.x;
3943 }
3944 if labels.y.is_some() {
3945 self.labels.y = labels.y;
3946 }
3947 if labels.caption.is_some() {
3948 self.labels.caption = labels.caption;
3949 }
3950 if labels.tag.is_some() {
3951 self.labels.tag = labels.tag;
3952 }
3953 self
3954 }
3955
3956 pub fn title(mut self, title: &str) -> Self {
3957 self.labels.title = Some(title.to_string());
3958 self
3959 }
3960
3961 pub fn tag(mut self, tag: &str) -> Self {
3964 self.labels.tag = Some(tag.to_string());
3965 self
3966 }
3967
3968 pub fn subtitle(mut self, subtitle: &str) -> Self {
3969 self.labels.subtitle = Some(subtitle.to_string());
3970 self
3971 }
3972
3973 pub fn xlab(mut self, label: &str) -> Self {
3974 self.labels.x = Some(label.to_string());
3975 self
3976 }
3977
3978 pub fn ylab(mut self, label: &str) -> Self {
3979 self.labels.y = Some(label.to_string());
3980 self
3981 }
3982
3983 pub fn caption(mut self, caption: &str) -> Self {
3984 self.labels.caption = Some(caption.to_string());
3985 self
3986 }
3987
3988 pub fn annotate(mut self, annotation: Annotation) -> Self {
3992 self.annotations.push(annotation);
3993 self
3994 }
3995
3996 pub fn annotate_text(self, label: &str, x: f64, y: f64) -> Self {
3998 self.annotate(Annotation::text(label, x, y))
3999 }
4000
4001 pub fn annotate_rect(self, xmin: f64, xmax: f64, ymin: f64, ymax: f64) -> Self {
4003 self.annotate(Annotation::rect(xmin, xmax, ymin, ymax))
4004 }
4005
4006 pub fn annotate_segment(self, x: f64, y: f64, xend: f64, yend: f64) -> Self {
4008 self.annotate(Annotation::segment(x, y, xend, yend))
4009 }
4010
4011 pub fn annotation_logticks(self, sides: &str) -> Self {
4014 self.annotate(Annotation::logticks(sides))
4015 }
4016
4017 pub fn annotation_raster(
4020 self,
4021 image: Vec<u8>,
4022 xmin: f64,
4023 xmax: f64,
4024 ymin: f64,
4025 ymax: f64,
4026 ) -> Self {
4027 self.annotate(Annotation::raster(image, xmin, xmax, ymin, ymax))
4028 }
4029
4030 #[cfg(feature = "png")]
4033 pub fn annotation_raster_rgba(
4034 self,
4035 (width, height): (u32, u32),
4036 rgba: &[u8],
4037 (xmin, xmax, ymin, ymax): (f64, f64, f64, f64),
4038 ) -> Self {
4039 use image::ImageEncoder;
4040 let mut png = Vec::new();
4041 let ok = image::codecs::png::PngEncoder::new(&mut png)
4042 .write_image(rgba, width, height, image::ColorType::Rgba8)
4043 .is_ok();
4044 if !ok {
4045 return self;
4046 }
4047 self.annotation_raster(png, xmin, xmax, ymin, ymax)
4048 }
4049
4050 pub fn annotation_custom(
4054 self,
4055 inset: GGPlot,
4056 xmin: f64,
4057 xmax: f64,
4058 ymin: f64,
4059 ymax: f64,
4060 ) -> Self {
4061 self.annotate(Annotation::inset(inset, xmin, xmax, ymin, ymax))
4062 }
4063
4064 pub fn locale(mut self, locale: crate::locale::Locale) -> Self {
4087 self.locale = Some(locale);
4088 self
4089 }
4090
4091 pub fn try_build(self) -> Result<crate::build::BuiltPlot, GGError> {
4095 PlotBuilder::build(self)
4096 }
4097
4098 pub fn build(self) -> crate::build::BuiltPlot {
4102 self.try_build().expect("plot build failed")
4103 }
4104
4105 #[cfg(all(feature = "plotters", not(target_arch = "wasm32")))]
4109 pub fn save(self, path: &str) -> Result<(), GGError> {
4110 self.save_with_size(path, 800, 600)
4111 }
4112
4113 #[cfg(all(feature = "plotters", not(target_arch = "wasm32")))]
4115 pub fn save_with_size(self, path: &str, w: u32, h: u32) -> Result<(), GGError> {
4116 let ext = path.rsplit('.').next().unwrap_or("svg").to_lowercase();
4118 #[cfg(feature = "pdf")]
4119 if ext == "pdf" {
4120 let bytes = self.render_pdf_with_size(w, h)?;
4121 return std::fs::write(path, bytes).map_err(|e| GGError::Render(e.into()));
4122 }
4123 let (built, layout) = self.prepare(w, h)?;
4124
4125 match ext.as_str() {
4126 "svg" => {
4127 let backend = plotters::prelude::SVGBackend::new(path, (w, h));
4128 Self::render_into(backend.into_drawing_area(), &built, &layout)?;
4129 }
4130 "png" | "bmp" | "gif" | "jpeg" | "jpg" | "tiff" => {
4131 let backend = plotters::prelude::BitMapBackend::new(path, (w, h));
4132 Self::render_into(backend.into_drawing_area(), &built, &layout)?;
4133 }
4134 _ => {
4135 return Err(GGError::UnsupportedFormat(ext));
4136 }
4137 }
4138
4139 Ok(())
4140 }
4141
4142 #[cfg(all(feature = "plotters", not(target_arch = "wasm32")))]
4148 pub fn render_svg(self) -> Result<String, GGError> {
4149 self.render_svg_with_size(800, 600)
4150 }
4151
4152 #[cfg(all(feature = "plotters", not(target_arch = "wasm32")))]
4156 pub fn render_svg_with_size(self, w: u32, h: u32) -> Result<String, GGError> {
4157 let (built, layout) = self.prepare(w, h)?;
4158 let mut buf = String::new();
4159 {
4160 let backend = plotters::prelude::SVGBackend::with_string(&mut buf, (w, h));
4161 Self::render_into(backend.into_drawing_area(), &built, &layout)?;
4162 }
4163 Ok(buf)
4164 }
4165
4166 pub fn render_svg_native(self) -> Result<String, GGError> {
4170 self.render_svg_native_with_size(800, 600)
4171 }
4172
4173 pub fn render_svg_native_with_size(self, w: u32, h: u32) -> Result<String, GGError> {
4181 Ok(self.render_native(w, h)?.0.finish())
4182 }
4183
4184 pub fn render_svg_sized(self, size: &crate::size::PhysicalSize) -> Result<String, GGError> {
4190 let (w, h) = size.canvas().map_err(GGError::ValidationError)?;
4191 let mut backend = self.render_native(w, h)?.0;
4192 if size.width.is_physical() {
4193 backend.set_physical_size(size.width.to_string(), size.height.to_string());
4194 }
4195 Ok(backend.finish())
4196 }
4197
4198 pub fn render_svg_native_with_warnings(
4203 self,
4204 w: u32,
4205 h: u32,
4206 ) -> Result<(String, Vec<String>), GGError> {
4207 let (backend, warnings, _) = self.render_native(w, h)?;
4208 Ok((backend.finish(), warnings))
4209 }
4210
4211 pub fn render_svg_native_at(self, x: f64, y: f64, w: u32, h: u32) -> Result<String, GGError> {
4223 Ok(self.render_native(w, h)?.0.finish_fragment(x, y))
4224 }
4225
4226 pub fn render_svg_area_with_size(self, w: u32, h: u32) -> Result<(String, [f64; 4]), GGError> {
4230 let (backend, _, pa) = self.render_native(w, h)?;
4231 Ok((backend.finish(), [pa.x, pa.y, pa.width, pa.height]))
4232 }
4233
4234 fn render_native(
4238 self,
4239 w: u32,
4240 h: u32,
4241 ) -> Result<
4242 (
4243 crate::render::svg_backend::SvgBackend,
4244 Vec<String>,
4245 crate::render::Rect,
4246 ),
4247 GGError,
4248 > {
4249 let svg_root_data = self.svg_root_data;
4250 let root_attrs = self.root_attrs.clone();
4251 let svg_warnings_attr = self.svg_warnings_attr;
4252 let svg_formatted_values = self.svg_formatted_values;
4253 let svg_title = self.svg_title.clone();
4254 let svg_desc = self.svg_desc.clone();
4255 let (built, layout) = self.prepare(w, h)?;
4256 let pa = layout.plot_area.clone();
4257 let mut backend = crate::render::svg_backend::SvgBackend::new(w, h, pa.clone());
4258 backend.set_formatted_values(svg_formatted_values);
4259 backend.set_svg_title(svg_title.clone());
4260 backend.set_svg_desc(svg_desc.clone());
4261 let existing_root_attrs = if svg_root_data {
4262 let attrs = crate::render::svg_backend::root_data_attrs(&built);
4263 backend.set_root_attrs(attrs.clone());
4264 let mut reserved = attrs;
4268 for name in ["data-plot", "data-viewport", "data-panels"] {
4271 reserved.push((name.to_string(), String::new()));
4272 }
4273 reserved
4274 } else {
4275 backend.without_plot_attr();
4276 Vec::new()
4277 };
4278 PlotRenderer::render(&built, &mut backend).map_err(GGError::Render)?;
4279 let mut warnings = built.warnings;
4280 warnings.extend(backend.take_warnings());
4281
4282 let mut reserved = existing_root_attrs;
4283 if svg_warnings_attr {
4284 reserved.push(("data-warnings".to_string(), String::new()));
4285 }
4286 if svg_title.is_some() || svg_desc.is_some() {
4291 reserved.push(("role".to_string(), String::new()));
4292 }
4293 if svg_title.is_some() {
4294 reserved.push(("aria-labelledby".to_string(), String::new()));
4295 }
4296 if svg_desc.is_some() {
4297 reserved.push(("aria-describedby".to_string(), String::new()));
4298 }
4299 let extra = crate::render::svg_backend::validate_root_attrs(
4300 &root_attrs,
4301 &reserved,
4302 "plot",
4303 &mut warnings,
4304 );
4305 backend.extend_root_attrs(extra);
4306 if svg_warnings_attr {
4307 backend.extend_root_attrs(vec![(
4308 "data-warnings".to_string(),
4309 crate::render::svg_backend::warnings_json(&warnings),
4310 )]);
4311 }
4312 Ok((backend, warnings, pa))
4313 }
4314
4315 #[cfg(feature = "canvas")]
4320 pub fn render_rgba_with_size(self, w: u32, h: u32) -> Result<(u32, u32, Vec<u8>), GGError> {
4321 let (built, layout) = self.prepare(w, h)?;
4322 let mut backend =
4323 crate::render::pixel_backend::PixelBackend::new(w, h, layout.plot_area.clone());
4324 PlotRenderer::render(&built, &mut backend).map_err(GGError::Render)?;
4325 let (ow, oh) = backend.dimensions();
4326 Ok((ow, oh, backend.into_rgba()))
4327 }
4328
4329 #[cfg(feature = "pdf")]
4333 pub fn render_pdf_with_size(self, w: u32, h: u32) -> Result<Vec<u8>, GGError> {
4334 let (built, layout) = self.prepare(w, h)?;
4335 let mut backend =
4336 crate::render::pdf_backend::PdfBackend::new(w, h, layout.plot_area.clone());
4337 PlotRenderer::render(&built, &mut backend).map_err(GGError::Render)?;
4338 backend.finish().map_err(GGError::Render)
4339 }
4340
4341 #[cfg(feature = "pdf")]
4344 pub fn render_pdf_sized(self, size: &crate::size::PhysicalSize) -> Result<Vec<u8>, GGError> {
4345 let (w, h) = size.canvas().map_err(GGError::ValidationError)?;
4346 self.render_pdf_with_size(w, h)
4347 }
4348
4349 #[cfg(feature = "pdf")]
4351 pub fn render_pdf(self) -> Result<Vec<u8>, GGError> {
4352 self.render_pdf_with_size(800, 600)
4353 }
4354
4355 #[cfg(feature = "canvas")]
4359 pub fn render_rgba_area_with_size(
4360 self,
4361 w: u32,
4362 h: u32,
4363 ) -> Result<(Vec<u8>, [f64; 4]), GGError> {
4364 let (built, layout) = self.prepare(w, h)?;
4365 let pa = layout.plot_area.clone();
4366 let mut backend = crate::render::pixel_backend::PixelBackend::new(w, h, pa.clone());
4367 PlotRenderer::render(&built, &mut backend).map_err(GGError::Render)?;
4368 Ok((backend.into_rgba(), [pa.x, pa.y, pa.width, pa.height]))
4369 }
4370
4371 #[cfg(feature = "canvas")]
4377 pub fn render_png_sized(self, size: &crate::size::PhysicalSize) -> Result<Vec<u8>, GGError> {
4378 let (w, h) = size.canvas().map_err(GGError::ValidationError)?;
4379 let (built, layout) = self.prepare(w, h)?;
4380 let mut backend = crate::render::pixel_backend::PixelBackend::with_scale(
4381 w as f64,
4382 h as f64,
4383 layout.plot_area.clone(),
4384 size.raster_scale(),
4385 );
4386 PlotRenderer::render(&built, &mut backend).map_err(GGError::Render)?;
4387 backend.into_png().map_err(GGError::Render)
4388 }
4389
4390 #[cfg(feature = "canvas")]
4394 pub fn render_png_raster_with_size(self, w: u32, h: u32) -> Result<Vec<u8>, GGError> {
4395 let (built, layout) = self.prepare(w, h)?;
4396 let mut backend =
4397 crate::render::pixel_backend::PixelBackend::new(w, h, layout.plot_area.clone());
4398 PlotRenderer::render(&built, &mut backend).map_err(GGError::Render)?;
4399 backend.into_png().map_err(GGError::Render)
4400 }
4401
4402 #[cfg(all(feature = "plotters", not(target_arch = "wasm32")))]
4409 pub fn render_png(self) -> Result<Vec<u8>, GGError> {
4410 self.render_png_with_size(800, 600)
4411 }
4412
4413 #[cfg(all(feature = "plotters", not(target_arch = "wasm32")))]
4416 pub fn render_png_with_size(self, w: u32, h: u32) -> Result<Vec<u8>, GGError> {
4417 let (built, layout) = self.prepare(w, h)?;
4418
4419 let mut rgb = vec![0u8; (w as usize) * (h as usize) * 3];
4422 {
4423 let backend = plotters::prelude::BitMapBackend::with_buffer(&mut rgb, (w, h));
4424 Self::render_into(backend.into_drawing_area(), &built, &layout)?;
4425 }
4426
4427 let img = image::RgbImage::from_raw(w, h, rgb).ok_or_else(|| {
4428 GGError::Render(RenderError::BackendError(
4429 "PNG buffer size mismatch".to_string(),
4430 ))
4431 })?;
4432 let mut out = std::io::Cursor::new(Vec::new());
4433 img.write_to(&mut out, image::ImageOutputFormat::Png)
4434 .map_err(|e| GGError::Render(RenderError::BackendError(format!("{:?}", e))))?;
4435 Ok(out.into_inner())
4436 }
4437
4438 pub(crate) fn prepare(
4440 self,
4441 w: u32,
4442 h: u32,
4443 ) -> Result<(crate::build::BuiltPlot, PlotLayout), GGError> {
4444 let (mut built, meta) = self.build_for_render()?;
4445 let layout = Self::layout_built(&mut built, &meta, w, h);
4446 Ok((built, layout))
4447 }
4448
4449 pub(crate) fn build_for_render(self) -> Result<(crate::build::BuiltPlot, RenderMeta), GGError> {
4452 let plot = self;
4453
4454 let has_title = plot.labels.title.is_some();
4455 let has_subtitle = plot.labels.subtitle.is_some();
4456 let has_caption = plot.labels.caption.is_some();
4457 let has_legend = plot.has_legend_mapping();
4458 let legend_bottom_share = plot
4462 .legend_bottom_share
4463 .or(plot.direct_labels.then_some(DIRECT_LABELS_MAX_SHARE));
4464 let legend_auto = plot.legend_auto;
4465 let x_label = plot.labels.x.clone();
4466 let y_label = plot.labels.y.clone();
4467 let guide_titles = plot.guide_legend.titles.clone();
4468
4469 let mut built = PlotBuilder::build(plot)?;
4470
4471 for (aes, title) in &guide_titles {
4473 if let Some(s) = built.scales.get_mut(aes) {
4474 s.set_name(title);
4475 }
4476 }
4477
4478 built.theme.resolve_inheritance();
4480
4481 if built.facet.is_none() && built.theme.aspect_ratio.is_none() {
4486 if let Some(a) = built
4487 .coord
4488 .fixed_aspect()
4489 .filter(|a| a.is_finite() && *a > 0.0)
4490 {
4491 built.theme.aspect_ratio = Some(a);
4492 }
4493 }
4494
4495 if let Some(ref label) = x_label {
4497 if let Some(s) = built.scales.get_mut(&crate::aes::Aesthetic::X) {
4498 s.set_name(label);
4499 }
4500 }
4501 if let Some(ref label) = y_label {
4502 if let Some(s) = built.scales.get_mut(&crate::aes::Aesthetic::Y) {
4503 s.set_name(label);
4504 }
4505 }
4506
4507 Ok((
4508 built,
4509 RenderMeta {
4510 has_title,
4511 has_subtitle,
4512 has_caption,
4513 has_legend,
4514 legend_bottom_share,
4515 legend_auto,
4516 },
4517 ))
4518 }
4519
4520 pub(crate) fn layout_built(
4523 built: &mut crate::build::BuiltPlot,
4524 meta: &RenderMeta,
4525 w: u32,
4526 h: u32,
4527 ) -> PlotLayout {
4528 match meta.legend_auto {
4529 Some(auto) if meta.has_legend && built.panels.is_empty() => {
4530 Self::layout_legend_auto(built, meta, auto, w, h)
4531 }
4532 _ => Self::layout_built_inner(built, meta, w, h),
4533 }
4534 }
4535
4536 fn layout_legend_auto(
4539 built: &mut crate::build::BuiltPlot,
4540 meta: &RenderMeta,
4541 auto: LegendAuto,
4542 w: u32,
4543 h: u32,
4544 ) -> PlotLayout {
4545 use crate::render::probe::Probe;
4546 use crate::theme::LegendPosition as P;
4547 let total = crate::render::Rect {
4548 x: 0.0,
4549 y: 0.0,
4550 width: w as f64,
4551 height: h as f64,
4552 };
4553 let (theme0, n_warnings) = (built.theme.clone(), built.warnings.len());
4556 let reset = |built: &mut crate::build::BuiltPlot, pos: P| {
4557 built.theme = theme0.clone();
4558 built.theme.legend_position = pos;
4559 built.warnings.truncate(n_warnings);
4560 };
4561
4562 reset(built, P::Inside(1.0, 0.0));
4563 let layout = Self::layout_built_inner(built, meta, w, h);
4564 let pa = layout.plot_area.clone();
4565 let mut marks = Probe::new(pa.clone(), total.clone());
4566 for layer in built.layers.iter().filter(|l| l.data.nrows() > 0) {
4567 let _ = layer.geom.draw(
4568 &layer.data,
4569 built.coord.as_ref(),
4570 &built.scales,
4571 &built.theme,
4572 &mut marks,
4573 );
4574 }
4575 for corner in auto.corners.iter().flatten() {
4576 built.theme.legend_position = corner.inside();
4577 let mut legend = Probe::new(pa.clone(), total.clone());
4578 let drawn = crate::guide::legend::draw_legend_planned(
4579 &built.scales,
4580 &built.theme,
4581 &pa,
4582 pa.width,
4583 &mut legend,
4584 &built.guide_legend,
4585 &built.suppressed_aes,
4586 &built.legend_plans,
4587 );
4588 let Some((x0, y0, x1, y1)) = legend.extent().filter(|_| drawn.is_ok()) else {
4589 continue;
4590 };
4591 const PAD: f64 = 2.0;
4592 if !marks.hits((x0 - PAD, y0 - PAD, x1 + PAD, y1 + PAD)) {
4593 built.legend_at = Some(format!("inside-{}", corner.name()));
4594 return layout;
4595 }
4596 }
4597
4598 let sides = match auto.fallback {
4601 Some(side) => vec![side],
4602 None => vec![LegendSide::Top, LegendSide::Right],
4603 };
4604 let data_area = |built: &crate::build::BuiltPlot, layout: &PlotLayout| {
4605 let r = built
4606 .coord
4607 .data_rect(&layout.plot_area)
4608 .unwrap_or_else(|| layout.plot_area.clone());
4609 r.width.max(0.0) * r.height.max(0.0)
4610 };
4611 let mut best = (sides[0], f64::MIN);
4612 for &side in &sides {
4613 reset(built, side.position());
4614 let trial = Self::layout_built_inner(built, meta, w, h);
4615 let area = data_area(built, &trial);
4616 if area > best.1 {
4617 best = (side, area);
4618 }
4619 }
4620 reset(built, best.0.position());
4621 let layout = Self::layout_built_inner(built, meta, w, h);
4622 built.legend_at = Some(
4623 match built.theme.legend_position {
4624 P::Top => "top",
4625 P::Right => "right",
4626 P::Bottom => "bottom",
4627 _ => "left",
4628 }
4629 .to_string(),
4630 );
4631 layout
4632 }
4633
4634 fn layout_built_inner(
4635 built: &mut crate::build::BuiltPlot,
4636 meta: &RenderMeta,
4637 w: u32,
4638 h: u32,
4639 ) -> PlotLayout {
4640 let RenderMeta {
4641 has_title,
4642 has_subtitle,
4643 has_caption,
4644 has_legend,
4645 legend_bottom_share,
4646 legend_auto: _,
4647 } = *meta;
4648 let x_axis_top = built
4649 .scales
4650 .get(&crate::aes::Aesthetic::X)
4651 .map(|s| s.axis_position_opposite())
4652 .unwrap_or(false);
4653
4654 if let Some(share) = legend_bottom_share {
4657 if has_legend
4658 && matches!(
4659 built.theme.legend_position,
4660 crate::theme::LegendPosition::Right
4661 )
4662 {
4663 let panel_width = |pos| {
4664 let mut theme = built.theme.clone();
4665 theme.legend_position = pos;
4666 PlotLayout::compute_with_extras(
4667 w as f64,
4668 h as f64,
4669 &theme,
4670 has_title,
4671 has_subtitle,
4672 has_caption,
4673 has_legend,
4674 x_axis_top,
4675 None,
4676 None,
4677 crate::render::layout::LayoutExtras::default(),
4678 )
4679 .plot_area
4680 .width
4681 };
4682 let free = panel_width(crate::theme::LegendPosition::None);
4685 if panel_width(crate::theme::LegendPosition::Right) < (1.0 - share) * free {
4686 built.theme.legend_position = crate::theme::LegendPosition::Bottom;
4687 }
4688 }
4689 }
4690
4691 let flipped = built.coord.is_flipped();
4695 let h_aes = if flipped {
4696 crate::aes::Aesthetic::Y
4697 } else {
4698 crate::aes::Aesthetic::X
4699 };
4700 let v_aes = if flipped {
4701 crate::aes::Aesthetic::X
4702 } else {
4703 crate::aes::Aesthetic::Y
4704 };
4705
4706 let drawn_x_labels: Vec<(f64, String)> = built
4714 .scales
4715 .get(&h_aes)
4716 .map(|hs| {
4717 hs.breaks()
4718 .into_iter()
4719 .filter(|(_, label)| !label.is_empty())
4720 .collect()
4721 })
4722 .unwrap_or_default();
4723 let h_is_discrete = built
4724 .scales
4725 .get(&h_aes)
4726 .map(|hs| hs.is_discrete())
4727 .unwrap_or(false);
4728
4729 if built.theme.axis_text_x.visible
4742 && built.theme.axis_text_x.angle.abs() < 1.0
4743 && h_is_discrete
4744 && !drawn_x_labels.is_empty()
4745 {
4746 let font = built.theme.axis_text_x.size;
4747 let max_w = drawn_x_labels
4748 .iter()
4749 .map(|(_, l)| crate::render::text::text_width(l, font))
4750 .fold(0.0_f64, f64::max);
4751 let n = drawn_x_labels.len() as f64;
4752 let spacing = 0.9 * w as f64 / n; if max_w > spacing {
4754 let vertical = max_w * std::f64::consts::FRAC_1_SQRT_2 > spacing;
4758 built.theme.axis_text_x.angle = if vertical { 270.0 } else { -45.0 };
4759 }
4760 }
4761
4762 let x_label_height = if built.theme.axis_text_x.visible
4777 && built.theme.axis_text_x.angle.abs() > 10.0
4778 && !drawn_x_labels.is_empty()
4779 {
4780 let font = built.theme.axis_text_x.size;
4781 let angle = built.theme.axis_text_x.angle;
4782 let dir = if x_axis_top { -1.0 } else { 1.0 };
4783 let (rise, fall) = crate::render::text::rotated_label_rise_fall(
4784 drawn_x_labels.iter().map(|(_, l)| l.as_str()),
4785 font,
4786 angle,
4787 crate::render::text::rotated_anchor_frac(angle, dir),
4788 );
4789 Some(built.theme.legend_spacing / 2.0 + font / 2.0 + rise + fall)
4790 } else {
4791 None
4792 };
4793
4794 let y_label_width = if built.theme.axis_text_y.visible {
4798 built.scales.get(&v_aes).map(|vs| {
4799 crate::guide::axis::y_label_reserve(&built.theme, &vs.breaks()).min(0.35 * w as f64)
4800 })
4801 } else {
4802 None
4803 };
4804
4805 let mut extras = crate::render::layout::LayoutExtras {
4818 extra_legend_sides: crate::guide::legend::extra_legend_sides(
4819 &built.scales,
4820 &built.suppressed_aes,
4821 &built.guide_legend,
4822 &built.theme.legend_position,
4823 ),
4824 ..Default::default()
4825 };
4826 if let (Some(vs), Some(sec)) = (
4830 built.scales.get(&crate::aes::Aesthetic::Y),
4831 built.scales.sec_axis(&crate::aes::Aesthetic::Y),
4832 ) {
4833 let theme = &built.theme;
4834 let max_ch = match sec.own_ticks(vs) {
4835 Some(t) => t.iter().map(|(_, l)| l.chars().count()).max(),
4836 None => vs.breaks().iter().map(|(_, l)| l.chars().count() + 2).max(),
4837 }
4838 .unwrap_or(0);
4839 let text = if theme.axis_text_y.visible {
4840 (max_ch as f64 * theme.axis_text_y.size * 0.6).max(theme.axis_text_y.size * 3.5)
4841 } else {
4842 0.0
4843 };
4844 let title = if !sec.name.is_empty() && theme.axis_title_y.visible {
4845 theme.axis_title_y.size * 1.5
4846 } else {
4847 0.0
4848 };
4849 extras.right += theme.axis_ticks_length + theme.legend_spacing + text + title;
4850 }
4851 if let Some(sec) = built
4853 .scales
4854 .get(&h_aes)
4855 .filter(|s| !s.axis_position_opposite())
4856 .and_then(|s| s.sec_axis())
4857 {
4858 extras.top += crate::guide::axis::sec_x_axis_height(&built.theme, sec);
4859 }
4860 let can_reserve = built.facet.is_none()
4861 && built.theme.axis_text_x.visible
4862 && built.theme.axis_text_x_fit == crate::theme::AxisLabelFit::Reserve
4863 && !built.coord.is_polar()
4864 && built.coord.supports_axis_reserve();
4865 if can_reserve {
4866 if let Some(hs) = built.scales.get(&h_aes) {
4867 let breaks = hs.breaks();
4868 if let (Some(first), Some(last)) = (breaks.first(), breaks.last()) {
4869 let angle = built.theme.axis_text_x.angle;
4870 let anchor = if angle.abs() > 10.0 {
4871 let dir = if x_axis_top { -1.0 } else { 1.0 };
4872 crate::render::text::rotated_anchor_frac(angle, dir)
4873 } else {
4874 0.5
4875 };
4876 let size = built.theme.axis_text_x.size;
4877 const EDGE: f64 = 1.0;
4878 for _ in 0..2 {
4879 let layout = PlotLayout::compute_with_extras(
4880 w as f64,
4881 h as f64,
4882 &built.theme,
4883 has_title,
4884 has_subtitle,
4885 has_caption,
4886 has_legend,
4887 x_axis_top,
4888 y_label_width,
4889 x_label_height,
4890 extras,
4891 );
4892 let area = &layout.plot_area;
4893 let edge_y = area.y + area.height;
4894 let to_point = |pos: f64| if flipped { (0.0, pos) } else { (pos, 0.0) };
4895 let px_first = built.coord.transform(to_point(first.0), area).0;
4896 let px_last = built.coord.transform(to_point(last.0), area).0;
4897 let bbox_first = crate::render::text::label_bbox(
4898 &first.1, size, px_first, edge_y, angle, anchor,
4899 );
4900 let bbox_last = crate::render::text::label_bbox(
4901 &last.1, size, px_last, edge_y, angle, anchor,
4902 );
4903 let deficit_left = (EDGE - bbox_first[0]).max(0.0);
4904 let deficit_right = (bbox_last[2] - (w as f64 - EDGE)).max(0.0);
4905 if deficit_left <= 0.0 && deficit_right <= 0.0 {
4906 break;
4907 }
4908 let (p_first, p_last) = (first.0, last.0);
4917 if deficit_left > 0.0 && deficit_right > 0.0 {
4918 let (a, b, c, d) = (1.0 - p_first, p_first, 1.0 - p_last, p_last);
4923 let det = a * d - b * c;
4924 if det.abs() > 0.01 {
4925 extras.left +=
4926 ((deficit_left * d + deficit_right * b) / det).max(0.0);
4927 extras.right +=
4928 ((deficit_right * a + deficit_left * c) / det).max(0.0);
4929 } else {
4930 extras.left += deficit_left / (1.0 - p_first).max(0.05);
4934 extras.right += deficit_right / p_last.max(0.05);
4935 }
4936 } else if deficit_left > 0.0 {
4937 extras.left += deficit_left / (1.0 - p_first).max(0.05);
4938 } else if deficit_right > 0.0 {
4939 extras.right += deficit_right / p_last.max(0.05);
4940 }
4941 const MIN_PANEL_WIDTH: f64 = 50.0;
4956 let cap = (w as f64 - MIN_PANEL_WIDTH).max(0.0);
4957 if extras.left + extras.right > cap {
4958 let scale = if extras.left + extras.right > 0.0 {
4959 cap / (extras.left + extras.right)
4960 } else {
4961 0.0
4962 };
4963 extras.left *= scale;
4964 extras.right *= scale;
4965 }
4966 }
4967 }
4968 }
4969 }
4970
4971 if has_legend
4978 && !matches!(
4979 built.theme.legend_position,
4980 crate::theme::LegendPosition::None
4981 )
4982 {
4983 let legend_aes =
4984 crate::guide::legend::legend_scales_for(&built.scales, &built.suppressed_aes);
4985 extras.legend_max_key_size = legend_aes
4989 .iter()
4990 .filter_map(|aes| {
4991 let scale = built.scales.get(aes)?;
4992 let breaks = scale.breaks();
4993 Some(crate::guide::legend::size_key_diameter(
4994 aes,
4995 &built.scales,
4996 scale,
4997 &breaks,
4998 ))
4999 })
5000 .fold(0.0_f64, f64::max);
5001 let has_wrap_guide = legend_aes.iter().any(|a| {
5012 let is_discrete = built
5013 .scales
5014 .get(a)
5015 .map(|s| s.is_discrete())
5016 .unwrap_or(false);
5017 is_discrete || !crate::guide::legend::is_colorbar_aesthetic(a)
5018 });
5019 if has_wrap_guide {
5020 let layout0 = PlotLayout::compute_with_extras(
5021 w as f64,
5022 h as f64,
5023 &built.theme,
5024 has_title,
5025 has_subtitle,
5026 has_caption,
5027 has_legend,
5028 x_axis_top,
5029 y_label_width,
5030 x_label_height,
5031 extras,
5032 );
5033 let (legend_x0, _, mut is_horizontal) = crate::guide::legend::legend_position(
5043 &built.theme,
5044 &layout0.plot_area,
5045 extras.legend_extra_rows,
5046 (0.0, 0.0),
5047 0.0,
5048 &layout0.total,
5049 );
5050 if let Some(dir) = built.theme.legend_direction {
5051 is_horizontal = matches!(dir, crate::theme::LegendDirection::Horizontal);
5052 }
5053 let avail_width =
5054 (layout0.plot_area.x + layout0.plot_area.width - legend_x0).max(0.0);
5055 let mut legend_warnings = Vec::new();
5056 let mut plans = crate::guide::legend::plan_all_legends(
5057 &built.scales,
5058 &built.guide_legend,
5059 &built.theme,
5060 &built.suppressed_aes,
5061 avail_width,
5062 layout0.plot_area.height,
5063 is_horizontal,
5064 &mut legend_warnings,
5065 );
5066 built.warnings.extend(legend_warnings);
5067
5068 if !plans.is_empty() {
5069 extras.legend_extra_rows = if is_horizontal {
5075 plans
5076 .values()
5077 .map(|p| p.rows.saturating_sub(1))
5078 .max()
5079 .unwrap_or(0)
5080 } else {
5081 plans.values().map(|p| p.rows.saturating_sub(1)).sum()
5082 };
5083 extras.legend_extra_width = plans
5090 .values()
5091 .map(|p| p.cols.saturating_sub(1) as f64 * p.col_pitch)
5092 .fold(0.0_f64, f64::max);
5093
5094 if !is_horizontal {
5106 let final_layout = PlotLayout::compute_with_extras(
5107 w as f64,
5108 h as f64,
5109 &built.theme,
5110 has_title,
5111 has_subtitle,
5112 has_caption,
5113 has_legend,
5114 x_axis_top,
5115 y_label_width,
5116 x_label_height,
5117 extras,
5118 );
5119 let (legend_x_final, _, _) = crate::guide::legend::legend_position(
5125 &built.theme,
5126 &final_layout.plot_area,
5127 extras.legend_extra_rows,
5128 (0.0, 0.0),
5129 0.0,
5130 &final_layout.total,
5131 );
5132 let swatch_and_gap =
5133 built.theme.legend_key_width + built.theme.legend_spacing;
5134 let text_size = built.theme.legend_text.size;
5135 fn right_edge_of(
5141 legend_x: f64,
5142 swatch_and_gap: f64,
5143 text_size: f64,
5144 plan: &crate::guide::legend::LegendPlan,
5145 breaks: &[(f64, String)],
5146 ) -> f64 {
5147 plan.entries
5148 .iter()
5149 .filter_map(|e| breaks.get(e.break_idx).map(|(_, l)| (e, l)))
5150 .map(|(e, label)| {
5151 let text =
5152 e.label_override.as_deref().unwrap_or(label.as_str());
5153 legend_x
5154 + e.x_offset
5155 + swatch_and_gap
5156 + crate::render::text::text_width(text, text_size)
5157 })
5158 .fold(0.0_f64, f64::max)
5159 }
5160
5161 let mut updates: Vec<(
5162 crate::aes::Aesthetic,
5163 crate::guide::legend::LegendPlan,
5164 )> = Vec::new();
5165 let mut reduced_aes: Vec<crate::aes::Aesthetic> = Vec::new();
5172 for (aes, plan) in &plans {
5173 if plan.cols <= 1 {
5174 continue;
5175 }
5176 let Some(scale) = built.scales.get(aes) else {
5177 continue;
5178 };
5179 let breaks = scale.breaks();
5180 if right_edge_of(
5181 legend_x_final,
5182 swatch_and_gap,
5183 text_size,
5184 plan,
5185 &breaks,
5186 ) <= w as f64
5187 {
5188 continue; }
5190
5191 let n = breaks.len();
5194 let mut reduced: Vec<crate::guide::legend::LegendPlan> = Vec::new();
5195 for c in (1..plan.cols).rev() {
5196 let mut candidate_guide = built.guide_legend.clone();
5197 candidate_guide.ncol = Some(c);
5198 candidate_guide.nrow = None;
5199 let mut tmp_warnings = Vec::new();
5200 let candidate_guide =
5201 candidate_guide.validated(n, &mut tmp_warnings);
5202 if let Some(cand) = crate::guide::legend::plan_legend(
5203 &breaks,
5204 &candidate_guide,
5205 &built.theme,
5206 avail_width,
5207 layout0.plot_area.height,
5208 false,
5209 ) {
5210 reduced.push(cand);
5211 }
5212 }
5213 if let Some(fits) = reduced.iter().find(|c| {
5214 right_edge_of(legend_x_final, swatch_and_gap, text_size, c, &breaks)
5215 <= w as f64
5216 }) {
5217 extras.legend_extra_rows =
5218 extras.legend_extra_rows.max(fits.rows.saturating_sub(1));
5219 updates.push((aes.clone(), fits.clone()));
5220 reduced_aes.push(aes.clone());
5221 continue;
5222 }
5223
5224 let base = reduced.last().cloned().unwrap_or_else(|| plan.clone());
5229 extras.legend_extra_rows =
5230 extras.legend_extra_rows.max(base.rows.saturating_sub(1));
5231 let mut truncated = base.clone();
5232 for e in &mut truncated.entries {
5233 let Some((_, label)) = breaks.get(e.break_idx) else {
5234 continue;
5235 };
5236 let avail = (w as f64
5237 - (legend_x_final + e.x_offset + swatch_and_gap))
5238 .max(0.0);
5239 if let Some(short) =
5240 crate::render::text::truncate_to_width(label, avail, text_size)
5241 {
5242 e.label_override = Some(short);
5243 }
5244 }
5245
5246 let truncated_edge = right_edge_of(
5250 legend_x_final,
5251 swatch_and_gap,
5252 text_size,
5253 &truncated,
5254 &breaks,
5255 );
5256 if truncated_edge > w as f64 {
5257 built.warnings.push(format!(
5258 "legend: the {}-column grid still doesn't fit the {w}px chart (needs about {} px)",
5259 truncated.cols,
5260 truncated_edge.ceil() as i64
5261 ));
5262 }
5263 updates.push((aes.clone(), truncated));
5264 }
5265 for (aes, new_plan) in &updates {
5266 plans.insert(aes.clone(), new_plan.clone());
5267 }
5268
5269 if !reduced_aes.is_empty() {
5310 let original_reserve = extras.legend_extra_width;
5311 let tighter_reserve = plans
5312 .values()
5313 .map(|p| p.cols.saturating_sub(1) as f64 * p.col_pitch)
5314 .fold(0.0_f64, f64::max);
5315 if tighter_reserve < original_reserve {
5316 let mut retry_extras = extras;
5317 retry_extras.legend_extra_width = tighter_reserve;
5318 let retry_layout = PlotLayout::compute_with_extras(
5319 w as f64,
5320 h as f64,
5321 &built.theme,
5322 has_title,
5323 has_subtitle,
5324 has_caption,
5325 has_legend,
5326 x_axis_top,
5327 y_label_width,
5328 x_label_height,
5329 retry_extras,
5330 );
5331 let (retry_x, _, _) = crate::guide::legend::legend_position(
5337 &built.theme,
5338 &retry_layout.plot_area,
5339 retry_extras.legend_extra_rows,
5340 (0.0, 0.0),
5341 0.0,
5342 &retry_layout.total,
5343 );
5344 let all_still_fit = plans.iter().all(|(aes, plan)| {
5345 let Some(scale) = built.scales.get(aes) else {
5346 return true;
5347 };
5348 let breaks = scale.breaks();
5349 right_edge_of(retry_x, swatch_and_gap, text_size, plan, &breaks)
5350 <= w as f64
5351 });
5352 if all_still_fit {
5353 extras.legend_extra_width = tighter_reserve;
5354 }
5355 }
5356 }
5357 }
5358 for (aes, plan) in &plans {
5359 if let Some(ov) = &plan.overflow {
5360 let n = built
5361 .scales
5362 .get(aes)
5363 .map(|s| s.breaks().len())
5364 .unwrap_or(ov.dropped);
5365 let shown = n.saturating_sub(ov.dropped);
5366 built.warnings.push(format!(
5367 "legend: {} of {n} entries don't fit the chart; the legend shows {shown} and \"+{} more\"",
5368 ov.dropped, ov.dropped
5369 ));
5370 }
5371 }
5372 }
5373 built.legend_plans = plans;
5379 }
5380 }
5381
5382 if has_legend
5385 && matches!(
5386 built.theme.legend_position,
5387 crate::theme::LegendPosition::Left | crate::theme::LegendPosition::Right
5388 )
5389 && !matches!(
5390 built.theme.legend_direction,
5391 Some(crate::theme::LegendDirection::Horizontal)
5392 )
5393 {
5394 let key_w = built.theme.legend_key_width.max(extras.legend_max_key_size);
5395 let extra =
5396 crate::guide::legend::legend_scales_for(&built.scales, &built.suppressed_aes)
5397 .iter()
5398 .filter(|aes| {
5399 crate::guide::legend::is_colorbar_aesthetic(aes)
5400 && built.scales.get(aes).is_some_and(|s| !s.is_discrete())
5401 })
5402 .filter_map(|aes| built.guide_legend.colourbar_for(aes).bar_width)
5403 .map(|w| (w - key_w).max(0.0))
5404 .fold(0.0_f64, f64::max);
5405 extras.legend_extra_width = extras.legend_extra_width.max(extra);
5406 let text_col = key_w + built.theme.legend_spacing + built.theme.legend_text.size * 6.0;
5408 let custom = built
5409 .guide_legend
5410 .custom
5411 .iter()
5412 .map(|g| (g.width - text_col).max(0.0))
5413 .fold(0.0_f64, f64::max);
5414 extras.legend_extra_width = extras.legend_extra_width.max(custom);
5415 }
5416
5417 if has_legend
5428 && !matches!(
5429 built.theme.legend_position,
5430 crate::theme::LegendPosition::None
5431 )
5432 {
5433 let is_horizontal = match built.theme.legend_direction {
5434 Some(dir) => matches!(dir, crate::theme::LegendDirection::Horizontal),
5435 None => matches!(
5436 built.theme.legend_position,
5437 crate::theme::LegendPosition::Top | crate::theme::LegendPosition::Bottom
5438 ),
5439 };
5440 if is_horizontal {
5441 let legend_aes =
5442 crate::guide::legend::legend_scales_for(&built.scales, &built.suppressed_aes);
5443 let continuous_colourbar = legend_aes.iter().find_map(|aes| {
5444 if !matches!(
5445 aes,
5446 crate::aes::Aesthetic::Color | crate::aes::Aesthetic::Fill
5447 ) {
5448 return None;
5449 }
5450 let scale = built.scales.get(aes)?;
5451 if scale.is_discrete() {
5452 return None;
5453 }
5454 Some(scale)
5455 });
5456 if let Some(scale) = continuous_colourbar {
5457 let title = built
5458 .guide_legend
5459 .title
5460 .as_deref()
5461 .unwrap_or_else(|| scale.name());
5462 let bar_height = crate::guide::legend::continuous_horizontal_bar_height(
5463 &built.theme,
5464 !title.is_empty(),
5465 &built.guide_legend.colourbar_for(&scale.aesthetic()),
5466 );
5467 let key_h = built
5468 .theme
5469 .legend_key_height
5470 .max(extras.legend_max_key_size);
5471 extras.continuous_horizontal_legend_extra_height =
5472 (bar_height - key_h).max(0.0);
5473 }
5474 let key_h = built
5476 .theme
5477 .legend_key_height
5478 .max(extras.legend_max_key_size);
5479 let custom = built
5480 .guide_legend
5481 .custom
5482 .iter()
5483 .map(|g| (g.title_offset(&built.theme) + g.height - key_h).max(0.0))
5484 .fold(0.0_f64, f64::max);
5485 extras.continuous_horizontal_legend_extra_height =
5486 extras.continuous_horizontal_legend_extra_height.max(custom);
5487 }
5488 }
5489
5490 PlotLayout::compute_with_extras(
5491 w as f64,
5492 h as f64,
5493 &built.theme,
5494 has_title,
5495 has_subtitle,
5496 has_caption,
5497 has_legend,
5498 x_axis_top,
5499 y_label_width,
5500 x_label_height,
5501 extras,
5502 )
5503 }
5504
5505 #[cfg(all(feature = "plotters", not(target_arch = "wasm32")))]
5508 fn render_into<DB>(
5509 area: plotters::drawing::DrawingArea<DB, plotters::coord::Shift>,
5510 built: &crate::build::BuiltPlot,
5511 layout: &PlotLayout,
5512 ) -> Result<(), GGError>
5513 where
5514 DB: plotters::prelude::DrawingBackend,
5515 DB::ErrorType: 'static,
5516 {
5517 area.fill(&plotters::prelude::WHITE)
5518 .map_err(|e| GGError::Render(RenderError::BackendError(format!("{:?}", e))))?;
5519 let mut adapter = PlottersAdapter::new(&area, layout.plot_area.clone());
5520 PlotRenderer::render(built, &mut adapter).map_err(GGError::Render)?;
5521 area.present()
5522 .map_err(|e| GGError::Render(RenderError::BackendError(format!("{:?}", e))))?;
5523 Ok(())
5524 }
5525
5526 #[cfg(all(feature = "plotters", not(target_arch = "wasm32")))]
5530 pub fn ggsave(
5531 self,
5532 path: &str,
5533 width_inches: f64,
5534 height_inches: f64,
5535 dpi: f64,
5536 ) -> Result<(), GGError> {
5537 use crate::size::{Length, PhysicalSize};
5538 let size = PhysicalSize::new(Length::inches(width_inches), Length::inches(height_inches))
5539 .with_dpi(dpi);
5540 self.save_sized(path, &size)
5541 }
5542
5543 #[cfg(all(feature = "plotters", not(target_arch = "wasm32")))]
5551 pub fn save_sized(self, path: &str, size: &crate::size::PhysicalSize) -> Result<(), GGError> {
5552 let (w, h) = size.canvas().map_err(GGError::ValidationError)?;
5553 if !size.width.is_physical() {
5554 return self.save_with_size(path, w, h);
5555 }
5556 let ext = path.rsplit('.').next().unwrap_or("svg").to_lowercase();
5557 let bytes = match ext.as_str() {
5558 "svg" => self.render_svg_sized(size)?.into_bytes(),
5559 #[cfg(feature = "pdf")]
5560 "pdf" => self.render_pdf_sized(size)?,
5561 "png" => self.render_png_sized(size)?,
5562 _ => return Err(GGError::UnsupportedFormat(ext)),
5563 };
5564 std::fs::write(path, bytes).map_err(|e| GGError::Render(e.into()))
5565 }
5566
5567 fn has_legend_mapping(&self) -> bool {
5582 use crate::guide::legend::is_legend_aesthetic;
5587 let plot_level = self
5588 .mapping
5589 .mappings
5590 .iter()
5591 .any(|m| is_legend_aesthetic(&m.aesthetic));
5592 !self.guide_legend.custom.is_empty()
5594 || plot_level
5595 || self.layers.iter().any(|layer| {
5596 if layer.show_legend == Some(false) {
5597 return false;
5598 }
5599 let effective = if layer.geom.inherit_aes() {
5600 self.mapping.merge(&layer.mapping)
5601 } else {
5602 layer.mapping.clone()
5603 };
5604 effective
5605 .mappings
5606 .iter()
5607 .any(|m| is_legend_aesthetic(&m.aesthetic))
5608 })
5609 }
5610}
5611
5612const DIRECT_LABELS_MAX_SHARE: f64 = 0.3;
5615
5616#[derive(Clone, Copy, Debug)]
5618pub(crate) struct RenderMeta {
5619 pub(crate) has_title: bool,
5620 pub(crate) has_subtitle: bool,
5621 pub(crate) has_caption: bool,
5622 pub(crate) has_legend: bool,
5623 pub(crate) legend_bottom_share: Option<f64>,
5624 pub(crate) legend_auto: Option<LegendAuto>,
5625}
5626
5627#[derive(Clone, Copy, Debug)]
5629pub(crate) struct LegendAuto {
5630 corners: [Option<crate::theme::LegendCorner>; 4],
5631 fallback: Option<LegendSide>,
5632}
5633
5634#[derive(Clone, Copy, Debug)]
5636enum LegendSide {
5637 Top,
5638 Right,
5639 Bottom,
5640 Left,
5641}
5642
5643impl LegendSide {
5644 fn position(self) -> crate::theme::LegendPosition {
5645 use crate::theme::LegendPosition as P;
5646 match self {
5647 LegendSide::Top => P::Top,
5648 LegendSide::Right => P::Right,
5649 LegendSide::Bottom => P::Bottom,
5650 LegendSide::Left => P::Left,
5651 }
5652 }
5653}
5654
5655#[derive(Debug)]
5657#[non_exhaustive]
5658pub enum GGError {
5659 Render(RenderError),
5660 UnsupportedFormat(String),
5661 Io(std::io::Error),
5662 ValidationError(String),
5663}
5664
5665impl std::fmt::Display for GGError {
5666 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
5667 match self {
5668 GGError::Render(e) => write!(f, "Render error: {e}"),
5669 GGError::UnsupportedFormat(ext) => write!(f, "Unsupported output format: {ext}"),
5670 GGError::Io(e) => write!(f, "IO error: {e}"),
5671 GGError::ValidationError(msg) => write!(f, "Validation error: {msg}"),
5672 }
5673 }
5674}
5675
5676impl std::error::Error for GGError {}
5677
5678fn distiller(
5680 aes: crate::aes::Aesthetic,
5681 palette: &crate::scale::palettes::PaletteName,
5682 direction: i32,
5683) -> crate::scale::gradient_n::ScaleColorGradientN {
5684 let mut colors = crate::scale::palettes::palette(palette).to_vec();
5685 if direction < 0 {
5686 colors.reverse();
5687 }
5688 let n = colors.len().max(2) - 1;
5689 let stops = colors
5690 .into_iter()
5691 .enumerate()
5692 .map(|(i, c)| (i as f64 / n as f64, c))
5693 .collect();
5694 crate::scale::gradient_n::ScaleColorGradientN::new(aes, stops)
5695}