ndarray Support

To enable ndarray support in Plotly.rs add the following feature to your Cargo.toml file:

[dependencies]
plotly = { version = ">=0.7.0", features = ["plotly_ndarray"] }

This extends the Plotly.rs API in two ways:

  • Scatter traces can now be created using the Scatter::from_ndarray constructor,
  • and also multiple traces can be created with the Scatter::to_traces method.

The full source code for the examples below can be found here.

ndarray Traces

The following imports have been used to produce the plots below:

#![allow(unused)]
fn main() {
use plotly::common::{Mode};
use plotly::{Plot, Scatter};
use ndarray::{Array, Ix1, Ix2};
use plotly::ndarray::ArrayTraces;
}

Single Trace

#![allow(unused)]
fn main() {
fn single_ndarray_trace(show: bool) {
    let n: usize = 11;
    let t: Array<f64, Ix1> = Array::range(0., 10., 10. / n as f64);
    let ys: Array<f64, Ix1> = t.iter().map(|v| (*v).powf(2.)).collect();

    let trace = Scatter::from_array(t, ys).mode(Mode::LinesMarkers);

    let mut plot = Plot::new();
    plot.add_trace(trace);
    if show {
        plot.show();
    }
    println!("{}", plot.to_inline_html(Some("single_ndarray_trace")));
}
}

Multiple Traces

To display a 2D array (Array<_, Ix2>) you can use the Scatter::to_traces method. The first argument of the method represents the common axis for the traces (x axis) whilst the second argument contains a collection of traces. At this point it should be noted that there is some ambiguity when passing a 2D array; namely are the traces arranged along the columns or the rows of the matrix? This ambiguity is resolved by the third argument of the Scatter::to_traces method. If that argument is set to ArrayTraces::OverColumns then the library assumes that every column represents an individual trace, alternatively if this is set to ArrayTraces::OverRows the assumption is that every row represents a trace.

To illustrate this distinction consider the following examples:

#![allow(unused)]
fn main() {
fn multiple_ndarray_traces_over_columns(show: bool) {
    let n: usize = 11;
    let t: Array<f64, Ix1> = Array::range(0., 10., 10. / n as f64);
    let mut ys: Array<f64, Ix2> = Array::zeros((11, 11));
    let mut count = 0.;
    for mut row in ys.columns_mut() {
        for index in 0..row.len() {
            row[index] = count + (index as f64).powf(2.);
        }
        count += 1.;
    }

    let traces =
        Scatter::default()
            .mode(Mode::LinesMarkers)
            .to_traces(t, ys, ArrayTraces::OverColumns);

    let mut plot = Plot::new();
    plot.add_traces(traces);
    if show {
        plot.show();
    }
    println!("{}", plot.to_inline_html(Some("multiple_ndarray_traces_over_columns")));
}
}

Replacing ArrayTraces::OverColumns with ArrayTraces::OverRows results in the following: