1use crate::annotation::{draw_annotations, Annotation};
4use crate::axis::Axis;
5use crate::canvas::{Canvas, Marker};
6use crate::crosshair::{self, nearest_point, Crosshair, NearestPoint};
7use crate::heatmap::Gradient;
8use crate::interact;
9use crate::layout::{self, text_width};
10use crate::theme::{self, Theme};
11use crate::util::{format_compact, format_tick, nice_bounds};
12use crate::PALETTE;
13use ratatui::{
14 buffer::Buffer,
15 layout::Rect,
16 style::{Color, Style},
17 widgets::Block,
18};
19
20#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
22#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
23pub enum LineMode {
24 #[default]
26 Line,
27 Step,
29 Area,
31 Scatter,
33}
34
35#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
37#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
38pub enum LegendPosition {
39 None,
41 TopLeft,
43 #[default]
45 TopRight,
46 BottomLeft,
48 BottomRight,
50}
51
52#[derive(Debug, Clone, Default)]
54pub struct Series {
55 pub(crate) name: String,
56 pub(crate) data: Vec<(f64, f64)>,
57 pub(crate) color: Option<Color>,
58 pub(crate) mode: Option<LineMode>,
59 pub(crate) y_err: Vec<f64>,
60 pub(crate) band: Vec<(f64, f64)>,
61 pub(crate) smooth: bool,
62 pub(crate) secondary: bool,
63 pub(crate) fill_gradient: Option<Gradient>,
64}
65
66impl Series {
67 pub fn new(name: impl Into<String>) -> Self {
69 Self {
70 name: name.into(),
71 ..Default::default()
72 }
73 }
74
75 pub fn data(mut self, data: impl IntoIterator<Item = (f64, f64)>) -> Self {
77 self.data = data.into_iter().collect();
78 self
79 }
80
81 pub fn values(mut self, values: impl IntoIterator<Item = f64>) -> Self {
83 self.data = values
84 .into_iter()
85 .enumerate()
86 .map(|(i, v)| (i as f64, v))
87 .collect();
88 self
89 }
90
91 opt_setter!(
92 color: Color
94 );
95
96 opt_setter!(
97 fill_gradient: Gradient
99 );
100
101 opt_setter!(
102 mode: LineMode
104 );
105
106 pub fn y_err(mut self, err: impl IntoIterator<Item = f64>) -> Self {
108 self.y_err = err.into_iter().collect();
109 self
110 }
111
112 pub fn band(mut self, band: impl IntoIterator<Item = (f64, f64)>) -> Self {
114 self.band = band.into_iter().collect();
115 self
116 }
117
118 setter!(
119 smooth: bool
121 );
122
123 setter!(
124 secondary_axis => secondary: bool
126 );
127
128 pub fn name(&self) -> &str {
130 &self.name
131 }
132
133 pub fn len(&self) -> usize {
135 self.data.len()
136 }
137
138 pub fn is_empty(&self) -> bool {
140 self.data.is_empty()
141 }
142
143 fn y_values(&self) -> impl Iterator<Item = f64> + '_ {
145 self.data
146 .iter()
147 .enumerate()
148 .filter(|(_, (x, y))| x.is_finite() && y.is_finite())
149 .flat_map(|(i, &(_, y))| {
150 let mut v = vec![y];
151 if let Some(e) = self.y_err.get(i).filter(|e| e.is_finite()) {
152 v.push(y - e.abs());
153 v.push(y + e.abs());
154 }
155 if let Some(&(lo, hi)) = self.band.get(i) {
156 v.push(lo);
157 v.push(hi);
158 }
159 v
160 })
161 .filter(|v| v.is_finite())
162 }
163}
164
165#[derive(Debug, Clone, Copy)]
167struct Scale {
168 lo: f64,
169 hi: f64,
170 log: bool,
171}
172
173impl Scale {
174 fn frac(&self, v: f64) -> Option<f64> {
175 if !v.is_finite() {
176 return None;
177 }
178 if self.log {
179 if v <= 0.0 || self.lo <= 0.0 {
180 return None;
181 }
182 let (l0, l1) = (self.lo.log10(), self.hi.log10());
183 Some((v.log10() - l0) / (l1 - l0))
184 } else {
185 Some((v - self.lo) / (self.hi - self.lo))
186 }
187 }
188}
189
190fn log_bounds(raw: Option<(f64, f64)>) -> (f64, f64) {
192 match raw {
193 None => (1.0, 10.0),
194 Some((a, b)) => {
195 let lo = 10f64.powf(a.log10().floor());
196 let mut hi = 10f64.powf(b.log10().ceil());
197 if hi <= lo {
198 hi = lo * 10.0;
199 }
200 (lo, hi)
201 }
202 }
203}
204
205fn decade_label(k: i32) -> String {
206 if (0..=5).contains(&k) {
207 format!("{}", 10u64.pow(k as u32))
208 } else if (-3..0).contains(&k) {
209 let v = 10f64.powi(k);
210 format_tick(v, v)
211 } else {
212 format!("1e{k}")
213 }
214}
215
216#[derive(Debug, Clone, Default)]
230pub struct LineChart {
231 series: Vec<Series>,
232 x_axis: Axis,
233 y_axis: Axis,
234 y2_axis: Axis,
235 y_log: bool,
236 smooth: bool,
237 annotations: Vec<Annotation>,
238 crosshair: Option<Crosshair>,
239 block: Option<Block<'static>>,
240 marker: Marker,
241 mode: LineMode,
242 legend: LegendPosition,
243 legend_style: Option<Style>,
244 theme: Option<Theme>,
245 style: Option<Style>,
246 hidden: Vec<usize>,
247}
248
249impl LineChart {
250 pub fn new(series: Vec<Series>) -> Self {
252 Self {
253 series,
254 ..Default::default()
255 }
256 }
257
258 setter!(
259 series: Vec<Series>
261 );
262
263 pub fn x_axis(mut self, axis: Axis) -> Self {
265 self.x_axis = axis;
266 if let Some(t) = &self.theme {
267 self.x_axis.theme_in_place(t);
268 }
269 self
270 }
271
272 pub fn y_axis(mut self, axis: Axis) -> Self {
274 self.y_axis = axis;
275 if let Some(t) = &self.theme {
276 self.y_axis.theme_in_place(t);
277 }
278 self
279 }
280
281 pub fn y2_axis(mut self, axis: Axis) -> Self {
283 self.y2_axis = axis;
284 if let Some(t) = &self.theme {
285 self.y2_axis.theme_in_place(t);
286 }
287 self
288 }
289
290 setter!(
291 y_log: bool
294 );
295
296 setter!(
297 smooth: bool
299 );
300
301 pub fn annotation(mut self, annotation: Annotation) -> Self {
303 self.annotations.push(annotation);
304 self
305 }
306
307 setter!(
308 crosshair: Option<Crosshair>
310 );
311
312 block_setter!(block, 'static);
313
314 setter!(
315 marker: Marker
317 );
318
319 setter!(
320 mode: LineMode
322 );
323
324 #[cfg(feature = "theme")]
327 pub fn theme(mut self, theme: impl Into<Theme>) -> Self {
328 let t = theme.into();
329 self.x_axis.theme_in_place(&t);
330 self.y_axis.theme_in_place(&t);
331 self.y2_axis.theme_in_place(&t);
332 self.theme = Some(t);
333 self
334 }
335
336 base_style_setter!(style);
337
338 opt_setter!(
339 legend_style: Style
341 );
342
343 fn series_color(&self, i: usize, s: &Series) -> Color {
344 s.color.unwrap_or_else(|| match &self.theme {
345 Some(t) => t.color(i),
346 None => PALETTE[i % PALETTE.len()],
347 })
348 }
349
350 setter!(
351 legend: LegendPosition
353 );
354
355 #[must_use]
359 pub fn hidden(mut self, hidden: impl IntoIterator<Item = usize>) -> Self {
360 self.hidden = hidden.into_iter().collect();
361 self
362 }
363
364 fn is_hidden(&self, i: usize) -> bool {
365 self.hidden.contains(&i)
366 }
367
368 fn has_secondary(&self) -> bool {
369 self.series.iter().any(|s| s.secondary && !s.is_empty())
370 }
371
372 fn y_range(&self, secondary: bool, positive_only: bool) -> Option<(f64, f64)> {
374 let mut r: Option<(f64, f64)> = None;
375 for v in self
376 .series
377 .iter()
378 .enumerate()
379 .filter(|(i, s)| s.secondary == secondary && !self.is_hidden(*i))
380 .map(|(_, s)| s)
381 .flat_map(|s| s.y_values())
382 .filter(|v| !positive_only || *v > 0.0)
383 {
384 r = Some(r.map_or((v, v), |(a, b)| (a.min(v), b.max(v))));
385 }
386 r
387 }
388
389 pub fn bounds(&self) -> ((f64, f64), (f64, f64)) {
391 let mut xs = (f64::INFINITY, f64::NEG_INFINITY);
392 for &(x, _) in self
393 .series
394 .iter()
395 .enumerate()
396 .filter(|(i, _)| !self.is_hidden(*i))
397 .flat_map(|(_, s)| s.data.iter())
398 .filter(|(x, y)| x.is_finite() && y.is_finite())
399 {
400 xs = (xs.0.min(x), xs.1.max(x));
401 }
402 let x = self.x_axis.bounds.unwrap_or_else(|| {
403 if xs.0.is_finite() {
404 if xs.1 <= xs.0 {
405 (xs.0 - 1.0, xs.1 + 1.0)
406 } else {
407 xs
408 }
409 } else {
410 (0.0, 1.0)
411 }
412 });
413 let y = if self.y_log {
414 match self.y_axis.bounds {
415 Some((a, b)) if a > 0.0 && b > a => (a, b),
416 _ => log_bounds(self.y_range(false, true)),
417 }
418 } else {
419 self.y_axis.bounds.unwrap_or_else(|| {
420 self.y_range(false, false)
421 .map_or((0.0, 1.0), |(a, b)| nice_bounds(a, b, self.y_axis.ticks))
422 })
423 };
424 (x, y)
425 }
426
427 pub fn y2_bounds(&self) -> Option<(f64, f64)> {
429 if !self.has_secondary() {
430 return None;
431 }
432 Some(self.y2_axis.bounds.unwrap_or_else(|| {
433 self.y_range(true, false)
434 .map_or((0.0, 1.0), |(a, b)| nice_bounds(a, b, self.y2_axis.ticks))
435 }))
436 }
437
438 fn scales(&self) -> (Scale, Scale, Option<Scale>) {
439 let (xb, yb) = self.bounds();
440 (
441 Scale {
442 lo: xb.0,
443 hi: xb.1,
444 log: false,
445 },
446 Scale {
447 lo: yb.0,
448 hi: yb.1,
449 log: self.y_log,
450 },
451 self.y2_bounds().map(|b| Scale {
452 lo: b.0,
453 hi: b.1,
454 log: false,
455 }),
456 )
457 }
458
459 pub fn nearest(&self, x: f64, y: f64) -> Option<NearestPoint> {
463 let (sx, sy, sy2) = self.scales();
464 let target = (sx.frac(x)?, sy.frac(y)?);
465 let mut best: Option<(f64, NearestPoint)> = None;
466 for (si, s) in self.series.iter().enumerate() {
467 let ys = if s.secondary { sy2.unwrap_or(sy) } else { sy };
468 let pts = s
469 .data
470 .iter()
471 .map(|&(px, py)| match (sx.frac(px), ys.frac(py)) {
472 (Some(a), Some(b)) => (a, b),
473 _ => (f64::NAN, f64::NAN),
474 });
475 if let Some((i, d)) = nearest_point(pts, target, (1.0, 1.0)) {
476 if best.is_none_or(|(bd, _)| d < bd) {
477 let (px, py) = s.data[i];
478 best = Some((
479 d,
480 NearestPoint {
481 series: si,
482 index: i,
483 x: px,
484 y: py,
485 },
486 ));
487 }
488 }
489 }
490 best.map(|b| b.1)
491 }
492
493 fn y_marks(&self, b: (f64, f64)) -> Vec<(f64, String)> {
494 if !self.y_log || self.y_axis.labels.is_some() {
495 return self.y_axis.tick_marks(b);
496 }
497 let (l0, l1) = (b.0.log10(), b.1.log10());
498 if l1.is_nan() || l1 <= l0 {
499 return vec![];
500 }
501 let (k0, k1) = ((l0 - 1e-9).ceil() as i32, (l1 + 1e-9).floor() as i32);
502 let n = (i64::from(k1) - i64::from(k0) + 1).max(0) as usize;
503 let stride = n.div_ceil(self.y_axis.ticks.max(2)).max(1);
504 (k0..=k1)
505 .step_by(stride)
506 .map(|k| {
507 let label = match self.y_axis.format(10f64.powi(k)) {
508 Some(l) => l,
509 None => decade_label(k),
510 };
511 (f64::from(k) - l0, label)
512 })
513 .map(|(d, l)| (d / (l1 - l0), l))
514 .collect()
515 }
516
517 fn render_inner(&self, area: Rect, buf: &mut Buffer) {
518 let inner = theme::begin(&self.block, &self.theme, self.style, area, buf);
519 let (xb, yb) = self.bounds();
520 if xb.1 <= xb.0 || yb.1 <= yb.0 {
521 return;
522 }
523 let (sx, sy, sy2) = self.scales();
524 let y_marks = self.y_marks(yb);
525 let x_marks = self.x_axis.tick_marks(xb);
526 let y2_marks = match (&sy2, self.y2_bounds()) {
527 (Some(_), Some(b)) if b.1 > b.0 => self.y2_axis.tick_marks(b),
528 _ => vec![],
529 };
530 let y2_reserve = if sy2.is_some() {
531 y2_marks
532 .iter()
533 .map(|(_, l)| text_width(l))
534 .max()
535 .unwrap_or(0)
536 + 1
537 } else {
538 0
539 };
540 let inner = Rect {
541 width: inner.width.saturating_sub(y2_reserve),
542 ..inner
543 };
544 let yw = y_marks
545 .iter()
546 .map(|(_, l)| text_width(l))
547 .max()
548 .unwrap_or(0);
549 let Some(a) = layout::compute(
550 inner,
551 yw,
552 !x_marks.is_empty(),
553 self.x_axis.title.is_some(),
554 self.y_axis.title.is_some(),
555 ) else {
556 return;
557 };
558 let (rx, ry) = self.marker.resolution();
559 let plot = a.plot;
560 let y_ticks: Vec<(u16, String)> = y_marks
561 .iter()
562 .map(|(f, l)| (layout::frac_row(*f, plot.height, ry), l.clone()))
563 .collect();
564 let x_ticks: Vec<(u16, String)> = x_marks
565 .iter()
566 .map(|(f, l)| (layout::frac_col(*f, plot.width, rx), l.clone()))
567 .collect();
568
569 let grid_rows: Vec<u16> = if self.y_axis.grid {
570 y_ticks.iter().map(|t| t.0).collect()
571 } else {
572 vec![]
573 };
574 let grid_cols: Vec<u16> = if self.x_axis.grid {
575 x_ticks.iter().map(|t| t.0).collect()
576 } else {
577 vec![]
578 };
579 layout::draw_grid(
580 buf,
581 plot,
582 &grid_cols,
583 &grid_rows,
584 self.x_axis.grid_style,
585 self.x_axis.grid_kind,
586 );
587
588 let clampi = |v: f64| v.round().clamp(-20_000.0, 20_000.0) as i32;
590 let (nw, nh) = (
591 (plot.width as f64 * rx as f64 - 1.0).max(0.0),
592 (plot.height as f64 * ry as f64 - 1.0).max(0.0),
593 );
594 let x_cell = |x: f64| sx.frac(x).map(|f| clampi(f * nw).div_euclid(rx as i32));
595 let y_cell = |y: f64| {
596 sy.frac(y)
597 .map(|f| clampi((1.0 - f) * nh).div_euclid(ry as i32))
598 };
599 draw_annotations(buf, plot, &self.annotations, &x_cell, &y_cell);
600
601 let mut canvas = Canvas::new(plot.width, plot.height, self.marker);
602 let (pw, ph) = (canvas.px_w(), canvas.px_h());
603 let proj = |x: f64, y: f64, sec: bool| -> Option<(i32, i32)> {
604 let ys = if sec { sy2.as_ref()? } else { &sy };
605 let (fx, fy) = (sx.frac(x)?, ys.frac(y)?);
606 Some((
607 clampi(fx * (pw - 1) as f64),
608 clampi((1.0 - fy) * (ph - 1) as f64),
609 ))
610 };
611 for (i, s) in self.series.iter().enumerate() {
612 if self.is_hidden(i) {
613 continue;
614 }
615 let color = self.series_color(i, s);
616 let mode = s.mode.unwrap_or(self.mode);
617 let sec = s.secondary && sy2.is_some();
618 let mut pts: Vec<(i32, i32)> = Vec::with_capacity(s.data.len());
619 let mut band: Vec<(i32, i32, i32)> = Vec::new();
620 for (k, &(x, y)) in s.data.iter().enumerate() {
621 if !x.is_finite() || !y.is_finite() {
622 continue;
623 }
624 let Some(p) = proj(x, y, sec) else { continue };
625 pts.push(p);
626 if interact::recording() {
627 let cx = plot.x
628 + p.0
629 .div_euclid(rx as i32)
630 .clamp(0, i32::from(plot.width) - 1) as u16;
631 let cy = plot.y
632 + p.1
633 .div_euclid(ry as i32)
634 .clamp(0, i32::from(plot.height) - 1) as u16;
635 interact::record_point(Rect::new(cx, cy, 1, 1), i, k, || {
636 (
637 s.name.clone(),
638 vec![
639 format!("x {}", format_compact(x)),
640 format!("y {}", format_compact(y)),
641 ],
642 )
643 });
644 }
645 if let Some(&(lo, hi)) = s.band.get(k) {
646 let lo_p = proj(x, lo, sec).map_or(ph - 1, |q| q.1);
647 let hi_p = proj(x, hi, sec).map_or(ph - 1, |q| q.1);
648 band.push((p.0, lo_p, hi_p));
649 }
650 if let Some(e) = s.y_err.get(k).filter(|e| e.is_finite()) {
651 let e = e.abs();
652 let lo_p = proj(x, y - e, sec).map_or(ph - 1, |q| q.1);
653 let hi_p = proj(x, y + e, sec).map_or(ph - 1, |q| q.1);
654 canvas.line(p.0, lo_p, p.0, hi_p, color);
655 canvas.line(p.0 - 2, lo_p, p.0 + 2, lo_p, color);
656 canvas.line(p.0 - 2, hi_p, p.0 + 2, hi_p, color);
657 }
658 }
659 fill_band(&mut canvas, &band, color);
660 if (s.smooth || self.smooth) && matches!(mode, LineMode::Line | LineMode::Area) {
661 pts = catmull_rom(&pts);
662 }
663 if mode != LineMode::Scatter && pts.len() > canvas.px_w() as usize * 4 {
664 pts = decimate(&pts);
665 }
666 draw_series(&mut canvas, &pts, mode, color, s.fill_gradient.as_ref());
667 }
668 canvas.render(buf, plot);
669
670 if let Some(ch) = &self.crosshair {
671 if let (Some(c), Some(r)) = (x_cell(ch.x), y_cell(ch.y)) {
672 let themed = self.theme.as_ref().map(|t| ch.with_theme(t));
673 let ch = themed.as_ref().unwrap_or(ch);
674 crosshair::draw(buf, plot, ch, c, r, &self.tooltip_lines(ch));
675 }
676 }
677
678 layout::draw_axes(buf, &a, self.x_axis.style, self.y_axis.style);
679 layout::draw_y_labels(buf, a.y_labels, &y_ticks, self.y_axis.label_style);
680 layout::draw_x_labels(buf, a.x_labels, &x_ticks, self.x_axis.label_style);
681 if y2_reserve > 0 {
682 for y in plot.y..a.axis_row {
683 buf.set_string(plot.right(), y, "│", self.y2_axis.style);
684 }
685 buf.set_string(plot.right(), a.axis_row, "┘", self.x_axis.style);
686 let mut last: Option<u16> = None;
687 for (f, label) in &y2_marks {
688 let row = layout::frac_row(*f, plot.height, ry);
689 if last == Some(row) {
690 continue;
691 }
692 last = Some(row);
693 buf.set_stringn(
694 plot.right() + 1,
695 plot.y + row,
696 label,
697 (y2_reserve - 1) as usize,
698 self.y2_axis.label_style,
699 );
700 }
701 }
702 layout::draw_titles(
703 buf,
704 inner,
705 &a,
706 self.x_axis
707 .title
708 .as_deref()
709 .map(|t| (t, self.x_axis.label_style)),
710 self.y_axis
711 .title
712 .as_deref()
713 .map(|t| (t, self.y_axis.label_style)),
714 );
715 self.draw_legend(buf, plot);
716 }
717
718 fn tooltip_lines(&self, ch: &Crosshair) -> Vec<String> {
719 let mut lines = vec![
720 format!("x {}", format_compact(ch.x)),
721 format!("y {}", format_compact(ch.y)),
722 ];
723 for s in self.series.iter().filter(|s| !s.name.is_empty()) {
724 if let Some((i, _)) =
725 nearest_point(s.data.iter().copied(), (ch.x, 0.0), (1.0, f64::INFINITY))
726 {
727 lines.push(format!("{} {}", s.name, format_compact(s.data[i].1)));
728 }
729 }
730 lines
731 }
732
733 fn draw_legend(&self, buf: &mut Buffer, plot: Rect) {
734 if self.legend == LegendPosition::None {
735 return;
736 }
737 let entries: Vec<(&str, Color)> = self
738 .series
739 .iter()
740 .enumerate()
741 .filter(|(_, s)| !s.name.is_empty())
742 .map(|(i, s)| (s.name.as_str(), self.series_color(i, s)))
743 .collect();
744 let ids: Vec<usize> = self
745 .series
746 .iter()
747 .enumerate()
748 .filter(|(_, s)| !s.name.is_empty())
749 .map(|(i, _)| i)
750 .collect();
751 let w = entries
752 .iter()
753 .map(|(n, _)| text_width(n) + 2)
754 .max()
755 .unwrap_or(0);
756 if w == 0 || w > plot.width {
757 return;
758 }
759 let x = match self.legend {
760 LegendPosition::TopLeft | LegendPosition::BottomLeft => plot.x,
761 _ => plot.right() - w,
762 };
763 let label = self.legend_style.unwrap_or_else(|| {
764 Style::default().fg(self.theme.as_ref().map_or(Color::Gray, |t| t.muted))
765 });
766 for (i, (name, color)) in entries.iter().enumerate() {
767 let row = i as u16;
768 if row >= plot.height {
769 break;
770 }
771 let y = match self.legend {
772 LegendPosition::BottomLeft | LegendPosition::BottomRight => {
773 plot.bottom() - 1 - (entries.len() as u16 - 1 - row).min(plot.height - 1)
774 }
775 _ => plot.y + row,
776 };
777 let off = self.is_hidden(ids[i]);
778 let (dot, text) = if off {
779 (
780 "○",
781 label.add_modifier(
782 ratatui::style::Modifier::CROSSED_OUT | ratatui::style::Modifier::DIM,
783 ),
784 )
785 } else {
786 ("●", label)
787 };
788 buf.set_string(x, y, dot, Style::default().fg(*color));
789 buf.set_string(x + 2, y, name, text);
790 interact::record_legend(Rect::new(x, y, w, 1), ids[i], name);
791 }
792 }
793}
794
795fn catmull_rom(pts: &[(i32, i32)]) -> Vec<(i32, i32)> {
797 if pts.len() < 3 {
798 return pts.to_vec();
799 }
800 let n = pts.len();
801 let mut out = Vec::with_capacity(n * 4);
802 for i in 0..n - 1 {
803 let p0 = pts[i.saturating_sub(1)];
804 let (p1, p2) = (pts[i], pts[i + 1]);
805 let p3 = pts[(i + 2).min(n - 1)];
806 out.push(p1);
807 let span = (p2.0 - p1.0).abs().max((p2.1 - p1.1).abs());
808 let steps = (span / 2).clamp(1, 64);
809 for k in 1..steps {
810 let t = k as f64 / steps as f64;
811 let (t2, t3) = (t * t, t * t * t);
812 let f = |a: i32, b: i32, c: i32, d: i32| {
813 let (a, b, c, d) = (a as f64, b as f64, c as f64, d as f64);
814 (0.5 * (2.0 * b
815 + (c - a) * t
816 + (2.0 * a - 5.0 * b + 4.0 * c - d) * t2
817 + (3.0 * b - a - 3.0 * c + d) * t3))
818 .round()
819 .clamp(-20_000.0, 20_000.0) as i32
820 };
821 out.push((f(p0.0, p1.0, p2.0, p3.0), f(p0.1, p1.1, p2.1, p3.1)));
822 }
823 }
824 out.push(pts[n - 1]);
825 out
826}
827
828fn fill_band(canvas: &mut Canvas, band: &[(i32, i32, i32)], color: Color) {
830 let (pw, ph) = (canvas.px_w(), canvas.px_h());
831 let column = |px: i32, a: i32, b: i32, canvas: &mut Canvas| {
832 if !(0..pw).contains(&px) {
833 return;
834 }
835 for py in a.min(b).max(0)..=a.max(b).min(ph - 1) {
836 if (px + py) % 2 == 0 {
837 canvas.set(px, py, color);
838 }
839 }
840 };
841 if band.len() == 1 {
842 column(band[0].0, band[0].1, band[0].2, canvas);
843 }
844 for w in band.windows(2) {
845 let (l, r) = if w[0].0 <= w[1].0 {
846 (w[0], w[1])
847 } else {
848 (w[1], w[0])
849 };
850 for px in l.0.max(0)..=r.0.min(pw - 1) {
851 let t = if r.0 == l.0 {
852 0.0
853 } else {
854 (px - l.0) as f64 / (r.0 - l.0) as f64
855 };
856 let lerp = |a: i32, b: i32| (a as f64 + t * (b - a) as f64).round() as i32;
857 column(px, lerp(l.1, r.1), lerp(l.2, r.2), canvas);
858 }
859 }
860}
861
862fn decimate(pts: &[(i32, i32)]) -> Vec<(i32, i32)> {
866 if pts.windows(2).any(|w| w[1].0 < w[0].0) {
867 return pts.to_vec();
868 }
869 let mut out = Vec::with_capacity(pts.len() / 8 + 8);
870 let mut i = 0;
871 while i < pts.len() {
872 let x = pts[i].0;
873 let mut j = i;
874 let (mut lo, mut hi) = (i, i);
875 while j < pts.len() && pts[j].0 == x {
876 if pts[j].1 < pts[lo].1 {
877 lo = j;
878 }
879 if pts[j].1 > pts[hi].1 {
880 hi = j;
881 }
882 j += 1;
883 }
884 let mut keep = [i, lo, hi, j - 1];
885 keep.sort_unstable();
886 let mut last = usize::MAX;
887 for k in keep {
888 if k != last {
889 out.push(pts[k]);
890 last = k;
891 }
892 }
893 i = j;
894 }
895 out
896}
897
898fn draw_series(
899 canvas: &mut Canvas,
900 pts: &[(i32, i32)],
901 mode: LineMode,
902 color: Color,
903 grad: Option<&Gradient>,
904) {
905 let bottom = canvas.px_h() - 1;
906 match mode {
907 LineMode::Scatter => {
908 for &(x, y) in pts {
909 canvas.blob(x, y, color);
910 }
911 }
912 LineMode::Line | LineMode::Area | LineMode::Step => {
913 if mode == LineMode::Area {
914 for w in pts.windows(2) {
915 fill_segment(canvas, w[0], w[1], bottom, color, grad);
916 }
917 }
918 if pts.len() == 1 {
919 canvas.set(pts[0].0, pts[0].1, color);
920 }
921 for w in pts.windows(2) {
922 let ((x0, y0), (x1, y1)) = (w[0], w[1]);
923 if mode == LineMode::Step {
924 canvas.line(x0, y0, x1, y0, color);
925 canvas.line(x1, y0, x1, y1, color);
926 } else {
927 canvas.line(x0, y0, x1, y1, color);
928 }
929 }
930 }
931 }
932}
933
934fn fill_segment(
935 canvas: &mut Canvas,
936 a: (i32, i32),
937 b: (i32, i32),
938 bottom: i32,
939 color: Color,
940 grad: Option<&Gradient>,
941) {
942 let (lo, hi) = if a.0 <= b.0 { (a, b) } else { (b, a) };
943 let start = lo.0.max(0);
944 let end = hi.0.min(canvas.px_w() - 1);
945 let (rx, ry) = canvas.marker().resolution();
947 let (sx, sy) = (if rx > 1 { 2 } else { 1 }, if ry > 1 { 2 } else { 1 });
948 for px in start..=end {
949 let t = if hi.0 == lo.0 {
950 0.0
951 } else {
952 (px - lo.0) as f64 / (hi.0 - lo.0) as f64
953 };
954 let py = (lo.1 as f64 + t * (hi.1 - lo.1) as f64).round() as i32;
955 for yy in py.max(0)..=bottom {
956 if px % sx == 0 && yy % sy == 0 {
957 let c = match grad {
958 Some(g) if bottom > 0 => g.color_at((bottom - yy) as f64 / bottom as f64),
959 _ => color,
960 };
961 canvas.set(px, yy, c);
962 }
963 }
964 }
965}
966
967impl LineChart {
968 fn render_into(&self, area: Rect, buf: &mut Buffer) {
969 self.render_inner(area, buf);
970 }
971}
972
973widget_impls!(LineChart);
974
975#[cfg(feature = "theme")]
976impl tui_nuances::Themed for LineChart {
977 fn apply_theme(self, theme: &tui_nuances::Theme) -> Self {
978 self.theme(theme)
979 }
980}
981
982#[cfg(test)]
983mod tests {
984 use super::*;
985 use ratatui::widgets::Widget;
986
987 fn chart() -> LineChart {
988 LineChart::new(vec![
989 Series::new("a").values([1.0, 3.0, 2.0, 5.0]),
990 Series::new("b").data([(0.0, 0.0), (3.0, 4.0)]),
991 ])
992 }
993
994 #[test]
995 fn bounds_auto() {
996 let ((x0, x1), (y0, y1)) = chart().bounds();
997 assert_eq!((x0, x1), (0.0, 3.0));
998 assert!(y0 <= 0.0 && y1 >= 5.0);
999 }
1000
1001 #[test]
1002 fn bounds_fixed_and_empty() {
1003 let c = LineChart::default().x_axis(Axis::new().bounds(2.0, 4.0));
1004 assert_eq!(c.bounds().0, (2.0, 4.0));
1005 assert_eq!(c.bounds().1, (0.0, 1.0));
1006 }
1007
1008 #[test]
1009 fn bounds_single_point_padded() {
1010 let c = LineChart::new(vec![Series::new("p").data([(1.0, 1.0)])]);
1011 let ((x0, x1), (y0, y1)) = c.bounds();
1012 assert!(x1 > x0 && y1 > y0);
1013 }
1014
1015 #[test]
1016 fn nan_points_ignored() {
1017 let c = LineChart::new(vec![Series::new("p").data([
1018 (f64::NAN, 1.0),
1019 (1.0, 2.0),
1020 (2.0, 4.0),
1021 ])]);
1022 assert_eq!(c.bounds().0, (1.0, 2.0));
1023 }
1024
1025 #[test]
1026 fn series_helpers() {
1027 let s = Series::new("x")
1028 .values([1.0, 2.0])
1029 .color(Color::Red)
1030 .mode(LineMode::Step);
1031 assert_eq!(s.name(), "x");
1032 assert_eq!(s.len(), 2);
1033 assert!(!s.is_empty());
1034 assert!(Series::new("e").is_empty());
1035 }
1036
1037 #[test]
1038 fn renders_without_panic_all_modes() {
1039 for mode in [
1040 LineMode::Line,
1041 LineMode::Step,
1042 LineMode::Area,
1043 LineMode::Scatter,
1044 ] {
1045 for marker in [
1046 Marker::Braille,
1047 Marker::HalfBlock,
1048 Marker::Block,
1049 Marker::Dot,
1050 ] {
1051 let area = Rect::new(0, 0, 50, 14);
1052 let mut buf = Buffer::empty(area);
1053 chart()
1054 .mode(mode)
1055 .marker(marker)
1056 .x_axis(Axis::new().title("x").grid(true))
1057 .y_axis(Axis::new().title("y").grid(true))
1058 .block(Block::bordered().title("t"))
1059 .render(area, &mut buf);
1060 }
1061 }
1062 }
1063
1064 #[test]
1065 fn tiny_area_is_safe() {
1066 for (w, h) in [(0, 0), (1, 1), (5, 3), (9, 4)] {
1067 let area = Rect::new(0, 0, w, h);
1068 let mut buf = Buffer::empty(area);
1069 chart().render(area, &mut buf);
1070 }
1071 }
1072
1073 #[test]
1074 fn draws_data_and_legend() {
1075 let area = Rect::new(0, 0, 40, 12);
1076 let mut buf = Buffer::empty(area);
1077 chart().render(area, &mut buf);
1078 let text: String = (0..12)
1079 .flat_map(|y| (0..40).map(move |x| (x, y)))
1080 .map(|p| buf[p].symbol().to_string())
1081 .collect();
1082 assert!(text.chars().any(|c| ('\u{2801}'..='\u{28ff}').contains(&c)));
1083 assert!(text.contains('●'));
1084 assert!(text.contains('└'));
1085 }
1086
1087 #[test]
1088 fn legend_none_hides() {
1089 let area = Rect::new(0, 0, 40, 12);
1090 let mut buf = Buffer::empty(area);
1091 chart().legend(LegendPosition::None).render(area, &mut buf);
1092 let text: String = (0..12)
1093 .flat_map(|y| (0..40).map(move |x| (x, y)))
1094 .map(|p| buf[p].symbol().to_string())
1095 .collect();
1096 assert!(!text.contains('●'));
1097 }
1098
1099 fn text_of(buf: &Buffer, w: u16, h: u16) -> String {
1100 (0..h)
1101 .flat_map(|y| (0..w).map(move |x| (x, y)))
1102 .map(|p| buf[p].symbol().to_string())
1103 .collect()
1104 }
1105
1106 #[test]
1107 fn log_bounds_decades_and_labels() {
1108 let c = LineChart::new(vec![Series::new("a").data([
1109 (0.0, 3.0),
1110 (1.0, 4500.0),
1111 (2.0, -1.0),
1112 ])])
1113 .y_log(true);
1114 assert_eq!(c.bounds().1, (1.0, 10_000.0));
1115 let m = c.y_marks((1.0, 10_000.0));
1116 assert_eq!(m.first().unwrap().1, "1");
1117 assert_eq!(m.last().unwrap().1, "10000");
1118 assert!((m[2].0 - 0.5).abs() < 1e-9);
1119 assert_eq!(LineChart::default().y_log(true).bounds().1, (1.0, 10.0));
1120 }
1121
1122 #[test]
1123 fn secondary_axis_bounds_and_render() {
1124 let c = LineChart::new(vec![
1125 Series::new("a").values([1.0, 2.0]),
1126 Series::new("b").values([100.0, 900.0]).secondary_axis(true),
1127 ]);
1128 assert!(c.bounds().1 .1 < 10.0);
1129 let b2 = c.y2_bounds().unwrap();
1130 assert!(b2.1 >= 900.0);
1131 let area = Rect::new(0, 0, 40, 10);
1132 let mut buf = Buffer::empty(area);
1133 c.render(area, &mut buf);
1134 assert!(text_of(&buf, 40, 10).contains('┘'));
1135 assert!(LineChart::default().y2_bounds().is_none());
1136 }
1137
1138 #[test]
1139 fn err_band_extend_bounds() {
1140 let c = LineChart::new(vec![Series::new("a")
1141 .values([1.0, 2.0])
1142 .y_err([10.0, 10.0])]);
1143 assert!(c.bounds().1 .1 >= 12.0);
1144 let c = LineChart::new(vec![Series::new("a")
1145 .values([1.0, 2.0])
1146 .band([(-5.0, 1.0), (0.0, 3.0)])]);
1147 assert!(c.bounds().1 .0 <= -5.0);
1148 }
1149
1150 #[test]
1151 fn catmull_densifies() {
1152 let p = catmull_rom(&[(0, 0), (20, 10), (40, 0), (60, 10)]);
1153 assert!(p.len() > 4);
1154 assert_eq!(p[0], (0, 0));
1155 assert_eq!(*p.last().unwrap(), (60, 10));
1156 assert_eq!(catmull_rom(&[(1, 1)]), vec![(1, 1)]);
1157 }
1158
1159 #[test]
1160 fn nearest_finds_point() {
1161 let n = chart().nearest(3.0, 4.0).unwrap();
1162 assert_eq!((n.series, n.index), (1, 1));
1163 assert!(LineChart::default().nearest(0.0, 0.0).is_none());
1164 }
1165
1166 #[test]
1167 fn features_render_safely_everywhere() {
1168 let c = LineChart::new(vec![
1169 Series::new("a")
1170 .values([1.0, 0.0, f64::NAN, 5.0])
1171 .y_err([0.5, f64::NAN, 1.0])
1172 .smooth(true),
1173 Series::new("b")
1174 .values([10.0, 20.0, 5.0])
1175 .band([(1.0, 30.0), (2.0, 40.0), (0.0, 9.0)])
1176 .secondary_axis(true),
1177 ])
1178 .y_log(true)
1179 .annotation(Annotation::hline(2.0).text("lim"))
1180 .annotation(Annotation::x_region(0.5, 1.5))
1181 .crosshair(Some(Crosshair::new(1.0, 2.0)));
1182 for (w, h) in [(0, 0), (1, 1), (5, 3), (12, 6), (60, 20)] {
1183 let area = Rect::new(0, 0, w, h);
1184 let mut buf = Buffer::empty(area);
1185 (&c).render(area, &mut buf);
1186 }
1187 }
1188
1189 #[test]
1190 fn crosshair_draws_tooltip() {
1191 let area = Rect::new(0, 0, 50, 16);
1192 let mut buf = Buffer::empty(area);
1193 chart()
1194 .crosshair(Some(Crosshair::new(1.0, 2.0)))
1195 .render(area, &mut buf);
1196 let t = text_of(&buf, 50, 16);
1197 assert!(t.contains('┼'));
1198 assert!(t.contains("x 1"));
1199 }
1200
1201 #[cfg(feature = "theme")]
1202 #[test]
1203 fn crosshair_uses_theme_colors() {
1204 let th = Theme::dracula();
1205 let area = Rect::new(0, 0, 50, 16);
1206 let mut buf = Buffer::empty(area);
1207 chart()
1208 .theme(&th)
1209 .crosshair(Some(Crosshair::new(1.0, 2.0)))
1210 .render(area, &mut buf);
1211 assert!(buf
1212 .content()
1213 .iter()
1214 .any(|c| c.symbol() == "┼" && c.fg == th.crosshair));
1215 let mut buf = Buffer::empty(area);
1216 let own = Style::default().fg(Color::Red);
1217 chart()
1218 .theme(&th)
1219 .crosshair(Some(Crosshair::new(1.0, 2.0).style(own)))
1220 .render(area, &mut buf);
1221 assert!(buf
1222 .content()
1223 .iter()
1224 .any(|c| c.symbol() == "┼" && c.fg == Color::Red));
1225 }
1226
1227 #[test]
1228 fn decimate_keeps_extremes_and_order() {
1229 let pts = vec![(0, 5), (0, 1), (0, 9), (0, 4), (1, 2), (2, 3)];
1230 let d = decimate(&pts);
1231 assert_eq!(d, vec![(0, 5), (0, 1), (0, 9), (0, 4), (1, 2), (2, 3)]);
1232 let unsorted = vec![(3, 1), (1, 1)];
1233 assert_eq!(decimate(&unsorted), unsorted);
1234 }
1235
1236 #[test]
1237 fn interaction_hits_hidden_series_and_legend() {
1238 use crate::{HitKind, HitMap};
1239 let two = || {
1240 LineChart::new(vec![
1241 Series::new("a").data([(0.0, 1.0), (1.0, 2.0), (2.0, 3.0)]),
1242 Series::new("b").data([(0.0, 3.0), (1.0, 1.0), (2.0, 2.0)]),
1243 ])
1244 };
1245 let area = Rect::new(0, 0, 40, 12);
1246 let mut buf = Buffer::empty(area);
1247 let hits = HitMap::capture(two(), area, &mut buf);
1248 let pts = hits
1249 .hits()
1250 .iter()
1251 .filter(|h| h.kind == HitKind::Point)
1252 .count();
1253 assert_eq!(pts, 6);
1254 assert_eq!(
1255 hits.hits()
1256 .iter()
1257 .filter(|h| h.kind == HitKind::Legend)
1258 .count(),
1259 2
1260 );
1261 let p = &hits.hits()[0];
1262 assert_eq!(p.title, "a");
1263 assert!(p.lines[0].starts_with("x "));
1264 let mut buf = Buffer::empty(area);
1266 let hits = HitMap::capture(two().hidden([0]), area, &mut buf);
1267 assert!(hits
1268 .hits()
1269 .iter()
1270 .all(|h| h.kind == HitKind::Legend || h.series == 1));
1271 assert!(hits
1272 .hits()
1273 .iter()
1274 .any(|h| h.kind == HitKind::Legend && h.series == 0));
1275 let mut buf = Buffer::empty(area);
1277 two().hidden([0, 1]).render(area, &mut buf);
1278 }
1279}