Pre-1.0: the API is not stable yet and may change from version to version. Pin the exact version in your Cargo.toml and check the changelog before upgrading.

14. Charts and graphs

A function on a set of axes, a dot that rides it, and a zoom that the whole chart follows.

Loading live preview…

Source of learn_14_charts — edit in the playground
//! Lesson 14 — Charts and graphs.
//!
//! `Axes` maps data coordinates into a box. A plot is a function of x,
//! sampled again every frame, so it follows when the ranges move. Values
//! that change are signals, like everything else in oxframe.

use oxframe::prelude::*;

#[oxframe::scene]
pub async fn charts_lesson(view: View) {
    let axes = view.add(Axes::new().x_range(-4.0..4.0).y_range(-1.5..1.5));

    // A curve draws itself on, like any path.
    let curve = axes.plot(|x| (x * 1.5).sin());
    curve.draw_on().await;

    // A dot rides on the curve: its x is a signal.
    let x = Signal::new(-4.0);
    axes.point_on(&curve, x.clone());
    x.to(4.0, 2.0).await;

    // Morph into another function, then zoom out.
    curve
        .to_fn(|x| x.sin() * 0.5 + (3.0 * x).sin() * 0.4, 1.0)
        .await;
    axes.x_range().to(-8.0..8.0, 1.0).await;
    wait_for(0.4).await;
}

// Try: plot `|x| x.tan()` — the gaps stay gaps, no line jumps across.

pub fn project() -> Project {
    Project::new("charts_lesson").scene(charts_lesson())
}

Axes map data into a box

Axes::new().x_range(-4.0..4.0).y_range(-1.5..1.5) puts data coordinates into a box with a grid, ticks and labels. You think in data — x from -4 to 4 — and oxframe finds the pixels.

A plot is a function of x

axes.plot(|x| (x * 1.5).sin()) draws the curve. It is a path, so .draw_on() works as in lesson 9. axes.point_on(&curve, x) keeps a dot on it; move the signal x and the dot rides the curve.

Everything follows the ranges

curve.to_fn(..) morphs into another function, and axes.x_range().to(-8.0..8.0, 1.0) zooms out: the grid, the labels, the curve and the dot move together, because they are drawn from the range every frame.

Edit this page on GitHub