custom_colors/
custom_colors.rs

1//! Example: Set custom colors for traces via `TracesController`
2//!
3//! What it demonstrates
4//! - Using `TracesController` to change trace colors programmatically after traces are registered.
5//!
6//! How to run
7//! ```bash
8//! cargo run --example custom_colors
9//! ```
10//! The example streams two signals and sets custom RGB colors for the `sine` and `cosine` traces.
11
12use liveplot::{channel_plot, run_liveplot, LivePlotConfig, PlotPoint, TracesController};
13use std::time::{Duration, SystemTime, UNIX_EPOCH};
14
15fn main() -> eframe::Result<()> {
16    // Create multi-trace plot channel
17    let (sink, rx) = channel_plot();
18    let tr_sine = sink.create_trace("sine", None);
19    let tr_cos = sink.create_trace("cosine", None);
20
21    // Producer: 1 kHz sample rate, 3 Hz sine and cosine
22    std::thread::spawn(move || {
23        const FS_HZ: f64 = 1000.0; // 1 kHz sampling rate
24        const F_HZ: f64 = 3.0; // 3 Hz
25        let dt = Duration::from_millis(1);
26        let mut n: u64 = 0;
27        loop {
28            let t = n as f64 / FS_HZ;
29            let s_val = (2.0 * std::f64::consts::PI * F_HZ * t).sin();
30            let c_val = (2.0 * std::f64::consts::PI * F_HZ * t).cos();
31            let t_s = SystemTime::now()
32                .duration_since(UNIX_EPOCH)
33                .map(|d| d.as_secs_f64())
34                .unwrap_or(0.0);
35            let _ = sink.send_point(&tr_sine, PlotPoint { x: t_s, y: s_val });
36            let _ = sink.send_point(&tr_cos, PlotPoint { x: t_s, y: c_val });
37            n = n.wrapping_add(1);
38            std::thread::sleep(dt);
39        }
40    });
41
42    // Traces controller to set custom colors once traces appear
43    let traces_ctrl = TracesController::new();
44    {
45        // In a background thread, subscribe to trace info and set colors when seen
46        let ctrl = traces_ctrl.clone();
47        let rx_info = ctrl.subscribe();
48        std::thread::spawn(move || {
49            while let Ok(info) = rx_info.recv() {
50                for tr in info.traces {
51                    match tr.name.as_str() {
52                        "sine" => ctrl.request_set_color("sine", [0xFF, 0x66, 0x00]), // orange
53                        "cosine" => ctrl.request_set_color("cosine", [0x00, 0x99, 0xFF]), // blue
54                        _ => {}
55                    }
56                }
57            }
58        });
59    }
60
61    // Run the UI with the controller attached via config
62    let mut cfg = LivePlotConfig::default();
63    cfg.title = "LivePlot (custom colors)".into();
64    cfg.traces_controller = Some(traces_ctrl);
65    run_liveplot(rx, cfg)
66}