forked from emilk/egui_plot
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathplot.rs
More file actions
2209 lines (1971 loc) · 75.8 KB
/
Copy pathplot.rs
File metadata and controls
2209 lines (1971 loc) · 75.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use std::ops::RangeInclusive;
use std::sync::Arc;
use egui::Color32;
use egui::CursorIcon;
use egui::Id;
use egui::Layout;
use egui::Painter;
use egui::PointerButton;
use egui::Response;
use egui::Sense;
use egui::Shape;
use egui::Stroke;
use egui::TextStyle;
use egui::Ui;
use egui::WidgetText;
use egui::ecolor::Hsva;
use egui::epaint;
use emath::Align2;
use emath::NumExt as _;
use emath::Pos2;
use emath::Rangef;
use emath::Rect;
use emath::Vec2;
use emath::Vec2b;
use emath::remap_clamp;
use emath::vec2;
use crate::axis::Axis;
use crate::axis::AxisHints;
use crate::axis::AxisWidget;
use crate::axis::PlotTransform;
use crate::bounds::BoundsLinkGroups;
use crate::bounds::BoundsModification;
use crate::bounds::LinkedBounds;
use crate::bounds::PlotBounds;
use crate::bounds::PlotPoint;
use crate::colors::rulers_color;
use crate::cursor::Cursor;
use crate::cursor::CursorLinkGroups;
use crate::cursor::PlotFrameCursors;
use crate::grid::GridInput;
use crate::grid::GridMark;
use crate::grid::GridSpacer;
use crate::items;
use crate::items::PlotItem;
use crate::items::Span;
use crate::items::horizontal_line;
use crate::items::vertical_line;
use crate::label::LabelFormatter;
use crate::memory::PlotMemory;
use crate::overlays::CoordinatesFormatter;
use crate::overlays::Legend;
use crate::overlays::LegendWidget;
use crate::placement::Corner;
use crate::placement::HPlacement;
use crate::placement::VPlacement;
/// Combined axis widgets: `[x_axis_widgets, y_axis_widgets]`
type AxisWidgets<'a> = [Vec<crate::axis::AxisWidget<'a>>; 2];
/// Combined axis responses: `[x_axis_responses, y_axis_responses]`
type AxisResponses = [Vec<Response>; 2];
/// A 2D plot, e.g. a graph of a function.
///
/// [`Plot`] supports multiple lines and points.
///
/// ```
/// # egui::__run_test_ui(|ui| {
/// use egui_plot::Line;
/// use egui_plot::Plot;
/// use egui_plot::PlotPoints;
///
/// let sin: PlotPoints = (0..1000)
/// .map(|i| {
/// let x = i as f64 * 0.01;
/// [x, x.sin()]
/// })
/// .collect();
/// let line = Line::new("sin", sin);
/// Plot::new("my_plot")
/// .view_aspect(2.0)
/// .show(ui, |plot_ui| plot_ui.line(line));
/// # });
/// ```
pub struct Plot<'a> {
id_source: Id,
id: Option<Id>,
center_axis: Vec2b,
allow_zoom: Vec2b,
allow_drag: Vec2b,
allow_axis_zoom_drag: Vec2b,
allow_scroll: Vec2b,
allow_double_click_reset: bool,
allow_boxed_zoom: bool,
default_auto_bounds: Vec2b,
min_auto_bounds: PlotBounds,
margin_fraction: Vec2,
pan_pointer_button: PointerButton,
boxed_zoom_pointer_button: PointerButton,
linked_axes: Option<(Id, Vec2b)>,
linked_cursors: Option<(Id, Vec2b)>,
min_size: Vec2,
width: Option<f32>,
height: Option<f32>,
data_aspect: Option<f32>,
view_aspect: Option<f32>,
invert_x: bool,
invert_y: bool,
reset: bool,
show_x: bool,
show_y: bool,
show_crosshair: bool,
label_formatter: Option<LabelFormatter<'a>>,
coordinates_formatter: Option<(Corner, CoordinatesFormatter<'a>)>,
x_axes: Vec<AxisHints<'a>>, // default x axes
y_axes: Vec<AxisHints<'a>>, // default y axes
legend_config: Option<Legend>,
cursor_color: Option<Color32>,
show_background: bool,
show_axes: Vec2b,
show_grid: Vec2b,
grid_spacing: Rangef,
grid_spacers: [GridSpacer<'a>; 2],
grid_color: Option<Color32>,
grid_strength_exponent: f32,
clamp_grid: bool,
sense: Sense,
}
impl<'a> Plot<'a> {
/// Give a unique id for each plot within the same [`Ui`].
pub fn new(id_source: impl std::hash::Hash) -> Self {
Self {
id_source: Id::new(id_source),
id: None,
center_axis: false.into(),
allow_zoom: true.into(),
allow_drag: true.into(),
allow_axis_zoom_drag: true.into(),
allow_scroll: true.into(),
allow_double_click_reset: true,
allow_boxed_zoom: true,
default_auto_bounds: true.into(),
min_auto_bounds: PlotBounds::NOTHING,
margin_fraction: Vec2::splat(0.05),
pan_pointer_button: PointerButton::Primary,
boxed_zoom_pointer_button: PointerButton::Secondary,
linked_axes: None,
linked_cursors: None,
min_size: Vec2::splat(64.0),
width: None,
height: None,
data_aspect: None,
view_aspect: None,
invert_x: false,
invert_y: false,
reset: false,
show_x: true,
show_y: true,
show_crosshair: true,
label_formatter: None,
coordinates_formatter: None,
x_axes: vec![AxisHints::new(Axis::X)],
y_axes: vec![AxisHints::new(Axis::Y)],
legend_config: None,
cursor_color: None,
show_background: true,
show_axes: true.into(),
show_grid: true.into(),
grid_spacing: Rangef::new(8.0, 300.0),
grid_spacers: [crate::grid::log_grid_spacer(10), crate::grid::log_grid_spacer(10)],
grid_color: None,
grid_strength_exponent: 0.5,
clamp_grid: false,
sense: egui::Sense::click_and_drag(),
}
}
/// Set an explicit (global) id for the plot.
///
/// This will override the id set by [`Self::new`].
///
/// This is the same `Id` that can be used for [`PlotMemory::load`].
#[inline]
pub fn id(mut self, id: Id) -> Self {
self.id = Some(id);
self
}
/// width / height ratio of the data.
/// For instance, it can be useful to set this to `1.0` for when the two
/// axes show the same unit.
/// By default the plot window's aspect ratio is used.
#[inline]
pub fn data_aspect(mut self, data_aspect: f32) -> Self {
self.data_aspect = Some(data_aspect);
self
}
/// width / height ratio of the plot region.
/// By default no fixed aspect ratio is set (and width/height will fill the
/// ui it is in).
#[inline]
pub fn view_aspect(mut self, view_aspect: f32) -> Self {
self.view_aspect = Some(view_aspect);
self
}
/// Set whether to invert the x-axis (i.e. positive values go to the left).
/// By default the x-axis is not inverted (i.e. positive values go to the
/// right).
#[inline]
pub fn invert_x(mut self, invert: bool) -> Self {
self.invert_x = invert;
self
}
/// Set whether to invert the y-axis (i.e. positive values go down).
/// By default the y-axis is not inverted (i.e. positive values go up).
#[inline]
pub fn invert_y(mut self, invert: bool) -> Self {
self.invert_y = invert;
self
}
/// Width of plot. By default a plot will fill the ui it is in.
/// If you set [`Self::view_aspect`], the width can be calculated from the
/// height.
#[inline]
pub fn width(mut self, width: f32) -> Self {
self.min_size.x = width;
self.width = Some(width);
self
}
/// Height of plot. By default a plot will fill the ui it is in.
/// If you set [`Self::view_aspect`], the height can be calculated from the
/// width.
#[inline]
pub fn height(mut self, height: f32) -> Self {
self.min_size.y = height;
self.height = Some(height);
self
}
/// Minimum size of the plot view.
#[inline]
pub fn min_size(mut self, min_size: Vec2) -> Self {
self.min_size = min_size;
self
}
/// Show the x-value (e.g. when hovering). Default: `true`.
#[inline]
pub fn show_x(mut self, show_x: bool) -> Self {
self.show_x = show_x;
self
}
/// Show the y-value (e.g. when hovering). Default: `true`.
#[inline]
pub fn show_y(mut self, show_y: bool) -> Self {
self.show_y = show_y;
self
}
/// Show the crosshair when hovering. Default: `true`.
#[inline]
pub fn show_crosshair(mut self, show: bool) -> Self {
self.show_crosshair = show;
self
}
/// Always keep the X-axis centered. Default: `false`.
#[inline]
pub fn center_x_axis(mut self, on: bool) -> Self {
self.center_axis.x = on;
self
}
/// Always keep the Y-axis centered. Default: `false`.
#[inline]
pub fn center_y_axis(mut self, on: bool) -> Self {
self.center_axis.y = on;
self
}
/// Whether to allow zooming in the plot. Default: `true`.
///
/// Note: Allowing zoom in one axis but not the other may lead to unexpected
/// results if used in combination with `data_aspect`.
#[inline]
pub fn allow_zoom<T>(mut self, on: T) -> Self
where
T: Into<Vec2b>,
{
self.allow_zoom = on.into();
self
}
/// Whether to allow scrolling in the plot. Default: `true`.
#[inline]
pub fn allow_scroll<T>(mut self, on: T) -> Self
where
T: Into<Vec2b>,
{
self.allow_scroll = on.into();
self
}
/// Whether to allow double clicking to reset the view.
/// Default: `true`.
#[inline]
pub fn allow_double_click_reset(mut self, on: bool) -> Self {
self.allow_double_click_reset = on;
self
}
/// Set the side margin as a fraction of the plot size. Only used for auto
/// bounds.
///
/// For instance, a value of `0.1` will add 10% space on both sides.
#[inline]
pub fn set_margin_fraction(mut self, margin_fraction: Vec2) -> Self {
self.margin_fraction = margin_fraction;
self
}
/// Whether to allow zooming in the plot by dragging out a box with the
/// secondary mouse button.
///
/// Default: `true`.
///
/// The button to use is specified by [`Self::boxed_zoom_pointer_button`].
#[inline]
pub fn allow_boxed_zoom(mut self, on: bool) -> Self {
self.allow_boxed_zoom = on;
self
}
/// Config the button pointer to use for drag-to-pan. Default:
/// [`Secondary`](PointerButton::Primary)
#[inline]
pub fn pan_pointer_button(mut self, pan_pointer_button: PointerButton) -> Self {
self.pan_pointer_button = pan_pointer_button;
self
}
/// Config the button pointer to use for boxed zooming. Default:
/// [`Secondary`](PointerButton::Secondary)
#[inline]
pub fn boxed_zoom_pointer_button(mut self, boxed_zoom_pointer_button: PointerButton) -> Self {
self.boxed_zoom_pointer_button = boxed_zoom_pointer_button;
self
}
/// Whether to allow dragging in the plot to move the bounds. Default:
/// `true`.
///
/// The button to use is specified by [`Self::pan_pointer_button`].
#[inline]
pub fn allow_drag<T>(mut self, on: T) -> Self
where
T: Into<Vec2b>,
{
self.allow_drag = on.into();
self
}
/// Whether to allow dragging in the axis areas to zoom the plot. Default:
/// `true`.
#[inline]
pub fn allow_axis_zoom_drag<T>(mut self, on: T) -> Self
where
T: Into<Vec2b>,
{
self.allow_axis_zoom_drag = on.into();
self
}
/// Provide a function to customize the on-hover label for the x and y axis
///
/// ```
/// # egui::__run_test_ui(|ui| {
/// use egui_plot::Line;
/// use egui_plot::Plot;
/// use egui_plot::PlotPoints;
/// let sin: PlotPoints = (0..1000)
/// .map(|i| {
/// let x = i as f64 * 0.01;
/// [x, x.sin()]
/// })
/// .collect();
/// let line = Line::new("sin", sin);
/// Plot::new("my_plot")
/// .view_aspect(2.0)
/// .label_formatter(|name, value| {
/// if !name.is_empty() {
/// format!("{}: {:.*}%", name, 1, value.y)
/// } else {
/// "".to_owned()
/// }
/// })
/// .show(ui, |plot_ui| plot_ui.line(line));
/// # });
/// ```
#[inline]
pub fn label_formatter(mut self, label_formatter: impl Fn(&str, &PlotPoint) -> String + 'a) -> Self {
self.label_formatter = Some(Box::new(label_formatter));
self
}
/// Show the pointer coordinates in the plot.
#[inline]
pub fn coordinates_formatter(mut self, position: Corner, formatter: CoordinatesFormatter<'a>) -> Self {
self.coordinates_formatter = Some((position, formatter));
self
}
/// Configure how the grid in the background is spaced apart along the X
/// axis.
///
/// Default is a log-10 grid, i.e. every plot unit is divided into 10 other
/// units.
///
/// The function has this signature:
/// ```ignore
/// fn step_sizes(input: GridInput) -> Vec<GridMark>;
/// ```
///
/// This function should return all marks along the visible range of the X
/// axis. `step_size` also determines how thick/faint each line is
/// drawn. For example, if x = 80..=230 is visible and you want big
/// marks at steps of 100 and small ones at 25, you can return:
/// ```no_run
/// # use egui_plot::GridMark;
/// vec![
/// // 100s
/// GridMark {
/// value: 100.0,
/// step_size: 100.0,
/// },
/// GridMark {
/// value: 200.0,
/// step_size: 100.0,
/// },
/// // 25s
/// GridMark {
/// value: 125.0,
/// step_size: 25.0,
/// },
/// GridMark {
/// value: 150.0,
/// step_size: 25.0,
/// },
/// GridMark {
/// value: 175.0,
/// step_size: 25.0,
/// },
/// GridMark {
/// value: 225.0,
/// step_size: 25.0,
/// },
/// ];
/// # ()
/// ```
///
/// There are helpers for common cases, see [`crate::grid::log_grid_spacer`]
/// and [`crate::grid::uniform_grid_spacer`].
#[inline]
pub fn x_grid_spacer(mut self, spacer: impl Fn(GridInput) -> Vec<GridMark> + 'a) -> Self {
self.grid_spacers[0] = Box::new(spacer);
self
}
/// Default is a log-10 grid, i.e. every plot unit is divided into 10 other
/// units.
///
/// See [`Self::x_grid_spacer`] for explanation.
#[inline]
pub fn y_grid_spacer(mut self, spacer: impl Fn(GridInput) -> Vec<GridMark> + 'a) -> Self {
self.grid_spacers[1] = Box::new(spacer);
self
}
/// Set when the grid starts showing.
///
/// When grid lines are closer than the given minimum, they will be hidden.
/// When they get further apart they will fade in, until the reaches the
/// given maximum, at which point they are fully opaque.
#[inline]
pub fn grid_spacing(mut self, grid_spacing: impl Into<Rangef>) -> Self {
self.grid_spacing = grid_spacing.into();
self
}
/// Clamp the grid to only be visible at the range of data where we have
/// values.
///
/// Default: `false`.
#[inline]
pub fn clamp_grid(mut self, clamp_grid: bool) -> Self {
self.clamp_grid = clamp_grid;
self
}
/// Set the sense for the plot rect.
///
/// Default: `Sense::click_and_drag()`.
#[inline]
pub fn sense(mut self, sense: Sense) -> Self {
self.sense = sense;
self
}
/// Overwrite the starting and reset bounds used for the x axis.
/// Set the `default_auto_bounds` of the x axis to `false`.
///
/// Panics in debug builds if `min >= max`.
#[inline]
pub fn default_x_bounds(mut self, min: f64, max: f64) -> Self {
debug_assert!(min < max, "`min` must be less than `max` in `default_x_bounds`");
self.default_auto_bounds.x = false;
self.min_auto_bounds.min[0] = min;
self.min_auto_bounds.max[0] = max;
self
}
/// Overwrite the starting and reset bounds used for the y axis.
/// Set the `default_auto_bounds` of the y axis to `false`.
///
/// Panics in debug builds if `min >= max`.
#[inline]
pub fn default_y_bounds(mut self, min: f64, max: f64) -> Self {
debug_assert!(min < max, "`min` must be less than `max` in `default_y_bounds`");
self.default_auto_bounds.y = false;
self.min_auto_bounds.min[1] = min;
self.min_auto_bounds.max[1] = max;
self
}
/// Expand bounds to include the given x value.
/// For instance, to always show the y axis, call `plot.include_x(0.0)`.
#[inline]
pub fn include_x(mut self, x: impl Into<f64>) -> Self {
self.min_auto_bounds.extend_with_x(x.into());
self
}
/// Expand bounds to include the given y value.
/// For instance, to always show the x axis, call `plot.include_y(0.0)`.
#[inline]
pub fn include_y(mut self, y: impl Into<f64>) -> Self {
self.min_auto_bounds.extend_with_y(y.into());
self
}
/// Set whether the bounds should be automatically set based on data by
/// default.
///
/// This is enabled by default.
#[inline]
pub fn auto_bounds(mut self, auto_bounds: impl Into<Vec2b>) -> Self {
self.default_auto_bounds = auto_bounds.into();
self
}
/// Expand bounds to fit all items across the x axis, including values given
/// by `include_x`.
#[deprecated = "Use `auto_bounds` instead"]
#[inline]
pub fn auto_bounds_x(mut self) -> Self {
self.default_auto_bounds.x = true;
self
}
/// Expand bounds to fit all items across the y axis, including values given
/// by `include_y`.
#[deprecated = "Use `auto_bounds` instead"]
#[inline]
pub fn auto_bounds_y(mut self) -> Self {
self.default_auto_bounds.y = true;
self
}
/// Show a legend including all named items.
#[inline]
pub fn legend(mut self, legend: Legend) -> Self {
self.legend_config = Some(legend);
self
}
/// Whether or not to show the background [`Rect`].
///
/// Can be useful to disable if the plot is overlaid over existing content.
/// Default: `true`.
#[inline]
pub fn show_background(mut self, show: bool) -> Self {
self.show_background = show;
self
}
/// Show axis labels and grid tick values on the side of the plot.
///
/// Default: `true`.
#[inline]
pub fn show_axes(mut self, show: impl Into<Vec2b>) -> Self {
self.show_axes = show.into();
self
}
/// Show a grid overlay on the plot.
///
/// Default: `true`.
#[inline]
pub fn show_grid(mut self, show: impl Into<Vec2b>) -> Self {
self.show_grid = show.into();
self
}
/// Set the base color for grid lines.
///
/// By default, grid lines derive their color from [`egui::Visuals::text_color`].
/// This override lets you control the grid color independently of text styling.
/// The color is still modulated by line strength (fading for denser grid lines).
#[inline]
pub fn grid_color(mut self, color: Color32) -> Self {
self.grid_color = Some(color);
self
}
/// Controls the contrast between dense and sparse grid lines.
///
/// - `0.0`: all visible grid lines have the same opacity (uniform).
/// - `0.5`: default — moderate fade for denser lines.
/// - `1.0`: maximum fade — dense lines are much fainter than sparse ones.
///
/// The zoom-based density logic is always preserved; this only controls
/// how much the opacity varies between grid levels.
///
/// Default: `0.5`.
#[inline]
pub fn grid_fade(mut self, fade: f32) -> Self {
self.grid_strength_exponent = fade;
self
}
/// Add this plot to an axis link group so that this plot will share the
/// bounds with other plots in the same group. A plot cannot belong to
/// more than one axis group.
#[inline]
pub fn link_axis(mut self, group_id: impl Into<Id>, link: impl Into<Vec2b>) -> Self {
self.linked_axes = Some((group_id.into(), link.into()));
self
}
/// Add this plot to a cursor link group so that this plot will share the
/// cursor position with other plots in the same group. A plot cannot
/// belong to more than one cursor group.
#[inline]
pub fn link_cursor(mut self, group_id: impl Into<Id>, link: impl Into<Vec2b>) -> Self {
self.linked_cursors = Some((group_id.into(), link.into()));
self
}
/// Round grid positions to full pixels to avoid aliasing. Improves plot
/// appearance but might have an undesired effect when shifting the plot
/// bounds. Enabled by default.
#[inline]
#[deprecated = "This no longer has any effect and is always enabled."]
pub fn sharp_grid_lines(self, _enabled: bool) -> Self {
self
}
/// Resets the plot.
#[inline]
pub fn reset(mut self) -> Self {
self.reset = true;
self
}
/// Set the x axis label of the main X-axis.
///
/// Default: no label.
#[inline]
pub fn x_axis_label(mut self, label: impl Into<WidgetText>) -> Self {
if let Some(main) = self.x_axes.first_mut() {
main.label = label.into();
}
self
}
/// Set the y axis label of the main Y-axis.
///
/// Default: no label.
#[inline]
pub fn y_axis_label(mut self, label: impl Into<WidgetText>) -> Self {
if let Some(main) = self.y_axes.first_mut() {
main.label = label.into();
}
self
}
/// Set the position of the main X-axis.
#[inline]
pub fn x_axis_position(mut self, placement: crate::VPlacement) -> Self {
if let Some(main) = self.x_axes.first_mut() {
main.placement = placement.into();
}
self
}
/// Set the position of the main Y-axis.
#[inline]
pub fn y_axis_position(mut self, placement: crate::HPlacement) -> Self {
if let Some(main) = self.y_axes.first_mut() {
main.placement = placement.into();
}
self
}
/// Specify custom formatter for ticks on the main X-axis.
///
/// Arguments of `fmt`:
/// * the grid mark to format
/// * currently shown range on this axis.
#[inline]
pub fn x_axis_formatter(mut self, fmt: impl Fn(GridMark, &RangeInclusive<f64>) -> String + 'a) -> Self {
if let Some(main) = self.x_axes.first_mut() {
main.formatter = Arc::new(fmt);
}
self
}
/// Specify custom formatter for ticks on the main Y-axis.
///
/// Arguments of `fmt`:
/// * the grid mark to format
/// * currently shown range on this axis.
#[inline]
pub fn y_axis_formatter(mut self, fmt: impl Fn(GridMark, &RangeInclusive<f64>) -> String + 'a) -> Self {
if let Some(main) = self.y_axes.first_mut() {
main.formatter = Arc::new(fmt);
}
self
}
/// Set the minimum width of the main y-axis, in ui points.
///
/// The width will automatically expand if any tickmark text is wider than
/// this.
#[inline]
pub fn y_axis_min_width(mut self, min_width: f32) -> Self {
if let Some(main) = self.y_axes.first_mut() {
main.min_thickness = min_width;
}
self
}
/// Set the main Y-axis-width by number of digits
#[inline]
#[deprecated = "Use `y_axis_min_width` instead"]
pub fn y_axis_width(self, digits: usize) -> Self {
self.y_axis_min_width(12.0 * digits as f32)
}
/// Set custom configuration for X-axis
///
/// More than one axis may be specified. The first specified axis is
/// considered the main axis.
#[inline]
pub fn custom_x_axes(mut self, hints: Vec<AxisHints<'a>>) -> Self {
self.x_axes = hints;
self
}
/// Set custom configuration for left Y-axis
///
/// More than one axis may be specified. The first specified axis is
/// considered the main axis.
#[inline]
pub fn custom_y_axes(mut self, hints: Vec<AxisHints<'a>>) -> Self {
self.y_axes = hints;
self
}
/// Set custom cursor color.
///
/// You may set the color to [`Color32::TRANSPARENT`] to hide the cursors.
#[inline]
pub fn cursor_color(mut self, color: Color32) -> Self {
self.cursor_color = Some(color);
self
}
/// Interact with and add items to the plot and finally draw it.
pub fn show<R>(self, ui: &mut Ui, build_fn: impl FnOnce(&mut PlotUi<'a>) -> R + 'a) -> PlotResponse<R> {
self.show_dyn(ui, Box::new(build_fn))
}
/// Calculate the rect inside which everything will be drawn.
fn calculate_widget_complete_rect(&self, ui: &Ui) -> Rect {
// Determine position of widget.
let pos = ui.available_rect_before_wrap().min;
// Minimum values for screen protection
let mut min_size = self.min_size;
min_size.x = min_size.x.at_least(1.0);
min_size.y = min_size.y.at_least(1.0);
// Determine size of widget.
let size = {
let width = self
.width
.unwrap_or_else(|| {
if let (Some(height), Some(aspect)) = (self.height, self.view_aspect) {
height * aspect
} else {
ui.available_size_before_wrap().x
}
})
.at_least(min_size.x);
let height = self
.height
.unwrap_or_else(|| {
if let Some(aspect) = self.view_aspect {
width / aspect
} else {
ui.available_size_before_wrap().y
}
})
.at_least(min_size.y);
vec2(width, height)
};
// Determine complete rect of widget.
Rect {
min: pos,
max: pos + size,
}
}
fn allocate_axis_responses(&self, ui: &mut Ui, axis_widgets: &AxisWidgets<'_>) -> AxisResponses {
let x_axis_responses = axis_widgets[0]
.iter()
.map(|widget| {
let axis_response = ui.allocate_rect(widget.rect, Sense::drag());
if self.allow_axis_zoom_drag.x {
axis_response.on_hover_cursor(CursorIcon::ResizeHorizontal)
} else {
axis_response
}
})
.collect::<Vec<_>>();
let y_axis_responses = axis_widgets[1]
.iter()
.map(|widget| {
let axis_response = ui.allocate_rect(widget.rect, Sense::drag());
if self.allow_axis_zoom_drag.y {
axis_response.on_hover_cursor(CursorIcon::ResizeVertical)
} else {
axis_response
}
})
.collect::<Vec<_>>();
[x_axis_responses, y_axis_responses]
}
fn load_or_init_memory(&self, ui: &Ui, plot_id: Id, plot_rect: Rect) -> PlotMemory {
// Load or initialize the memory.
ui.ctx().check_for_id_clash(plot_id, plot_rect, "Plot");
if self.reset {
if let Some((name, _)) = self.linked_axes.as_ref() {
ui.ctx().data_mut(|data| {
let link_groups: &mut BoundsLinkGroups = data.get_temp_mut_or_default(Id::NULL);
link_groups.0.remove(name);
});
}
PlotMemory {
auto_bounds: self.default_auto_bounds,
hovered_legend_item: None,
hidden_items: Default::default(),
transform: PlotTransform::new_with_invert_axis(
plot_rect,
self.min_auto_bounds,
self.center_axis,
Vec2b::new(self.invert_x, self.invert_y),
),
last_click_pos_for_zoom: None,
x_axis_thickness: Default::default(),
y_axis_thickness: Default::default(),
}
} else {
PlotMemory::load(ui.ctx(), plot_id).unwrap_or_else(|| PlotMemory {
auto_bounds: self.default_auto_bounds,
hovered_legend_item: None,
hidden_items: Default::default(),
transform: PlotTransform::new_with_invert_axis(
plot_rect,
self.min_auto_bounds,
self.center_axis,
Vec2b::new(self.invert_x, self.invert_y),
),
last_click_pos_for_zoom: None,
x_axis_thickness: Default::default(),
y_axis_thickness: Default::default(),
})
}
}
fn paint_background(&self, ui: &Ui, plot_rect: Rect) {
if self.show_background {
ui.painter().with_clip_rect(plot_rect).add(epaint::RectShape::new(
plot_rect,
2,
ui.visuals().extreme_bg_color,
ui.visuals().widgets.noninteractive.bg_stroke,
egui::StrokeKind::Inside,
));
}
}
/// Process legend items, create legend widget, and determine show flags.
/// Returns `(legend_widget, show_x, show_y)`.
fn prepare_legend(
&self,
plot_ui: &mut PlotUi<'a>,
mem: &PlotMemory,
plot_rect: Rect,
) -> (Option<LegendWidget>, Vec2b) {
// Create legend widget if configured (needs all items, including hidden ones)
let legend = self
.legend_config
.as_ref()
.and_then(|config| LegendWidget::try_new(plot_rect, config.clone(), &plot_ui.items, &mem.hidden_items));
// Process legend items: filter hidden items, highlight hovered items
// Remove the deselected items.
plot_ui.items.retain(|item| !mem.hidden_items.contains(&item.id()));
// Highlight the hovered items.
if let Some(item_id) = &mem.hovered_legend_item {
plot_ui
.items
.iter_mut()
.filter(|entry| &entry.id() == item_id)
.for_each(|entry| entry.highlight());
}
// Move highlighted items to front.
plot_ui.items.sort_by_key(|item| item.highlighted());
// Determine show_x/show_y based on legend hover state (from previous frame)
let show_xy = Vec2b {
x: mem.hovered_legend_item.is_none() && self.show_x,
y: mem.hovered_legend_item.is_none() && self.show_y,
};
(legend, show_xy)
}
/// Show legend widget and update memory with legend state.
fn show_legend_and_update_memory(
legend: Option<LegendWidget>,
ui: &mut Ui,
mem: &mut PlotMemory,
hovered_plot_item: &mut Option<Id>,
) {
if let Some(mut legend) = legend {
ui.add(&mut legend);
mem.hidden_items = legend.hidden_items();
mem.hovered_legend_item = legend.hovered_item();
if let Some(item_id) = &mem.hovered_legend_item {
hovered_plot_item.get_or_insert(*item_id);
}
}
}
fn compute_bounds(&self, ui: &Ui, mem: &mut PlotMemory, plot_ui: &PlotUi<'a>, plot_rect: Rect) {
// Find the cursors from other plots we need to draw
let mut bounds = *plot_ui.last_plot_transform.bounds();
// Transfer the bounds from a link group.
if let Some((id, axes)) = self.linked_axes.as_ref() {
ui.ctx().data_mut(|data| {