//! # [Ratatui] Sparkline example
//! The latest version of this example is available in the [examples] folder in the repository.
//! Please note that the examples are designed to be run against the `main` branch of the Github
//! repository. This means that you may not be able to compile with the latest release version on
//! crates.io, or the one that you have installed locally.
//! See the [examples readme] for more information on finding examples that match the version of the
//! library you are using.
//! [Ratatui]: https://github.com/ratatui-org/ratatui
//! [examples]: https://github.com/ratatui-org/ratatui/blob/main/examples
//! [examples readme]: https://github.com/ratatui-org/ratatui/blob/main/examples/README.md
time::{Duration, Instant},
distributions::{Distribution, Uniform},
event::{self, DisableMouseCapture, EnableMouseCapture, Event, KeyCode},
terminal::{disable_raw_mode, enable_raw_mode, EnterAlternateScreen, LeaveAlternateScreen},
widgets::{Block, Borders, Sparkline},
distribution: Uniform<u64>,
fn new(lower: u64, upper: u64) -> Self {
distribution: Uniform::new(lower, upper),
impl Iterator for RandomSignal {
fn next(&mut self) -> Option<u64> {
Some(self.distribution.sample(&mut self.rng))
let mut signal = RandomSignal::new(0, 100);
let data1 = signal.by_ref().take(200).collect::<Vec<u64>>();
let data2 = signal.by_ref().take(200).collect::<Vec<u64>>();
let data3 = signal.by_ref().take(200).collect::<Vec<u64>>();
let value = self.signal.next().unwrap();
self.data1.insert(0, value);
let value = self.signal.next().unwrap();
self.data2.insert(0, value);
let value = self.signal.next().unwrap();
self.data3.insert(0, value);
fn main() -> Result<(), Box<dyn Error>> {
let mut stdout = io::stdout();
execute!(stdout, EnterAlternateScreen, EnableMouseCapture)?;
let backend = CrosstermBackend::new(stdout);
let mut terminal = Terminal::new(backend)?;
let tick_rate = Duration::from_millis(250);
let res = run_app(&mut terminal, app, tick_rate);
terminal: &mut Terminal<B>,
let mut last_tick = Instant::now();
terminal.draw(|f| ui(f, &app))?;
let timeout = tick_rate.saturating_sub(last_tick.elapsed());
if event::poll(timeout)? {
if let Event::Key(key) = event::read()? {
if key.code == KeyCode::Char('q') {
if last_tick.elapsed() >= tick_rate {
last_tick = Instant::now();
fn ui(f: &mut Frame, app: &App) {
let chunks = Layout::vertical([
let sparkline = Sparkline::default()
.borders(Borders::LEFT | Borders::RIGHT)
.style(Style::default().fg(Color::Yellow));
f.render_widget(sparkline, chunks[0]);
let sparkline = Sparkline::default()
.borders(Borders::LEFT | Borders::RIGHT)
.style(Style::default().bg(Color::Green));
f.render_widget(sparkline, chunks[1]);
let sparkline = Sparkline::default()
.borders(Borders::LEFT | Borders::RIGHT)
.style(Style::default().fg(Color::Red));
f.render_widget(sparkline, chunks[2]);