Plotly.rs
Plotly for Rust
Install / Use
/learn @plotly/Plotly.rsREADME
Table of Contents
Introduction
A plotting library for Rust powered by Plotly.js.
Documentation and numerous interactive examples are available in the Plotly.rs Book, the examples/ directory and docs.rs.
For changes since the last version, please consult the changelog.
Basic Usage
Add this to your Cargo.toml:
[dependencies]
plotly = "0.14"
Exporting a single Interactive Plot
Any figure can be saved as an HTML file using the Plot.write_html() method. These HTML files can be opened in any web browser to access the fully interactive figure.
use plotly::{Plot, Scatter};
let mut plot = Plot::new();
let trace = Scatter::new(vec![0, 1, 2], vec![2, 1, 0]);
plot.add_trace(trace);
plot.write_html("out.html");
By default, the Plotly JavaScript library and some MathJax components will always be included via CDN, which results in smaller file-size, but slightly slower first load as the JavaScript libraries have to be downloaded first. Alternatively, to embed the JavaScript libraries (several megabytes in size) directly into the HTML file, plotly-rs must be compiled with the feature flag plotly_embed_js. With this feature flag the Plotly and MathJax JavaScript libraries are directly embedded in the generated HTML file. It is still possible to use the CDN version, by using the use_cdn_js method.
// <-- Create a `Plot` -->
plot.use_cdn_js();
plot.write_html("out.html");
If you only want to view the plot in the browser quickly, use the Plot.show() method.
// <-- Create a `Plot` -->
plot.show(); // The default web browser will open, displaying an interactive plot
Exporting Static Images with plotly_static (Recommended)
The recommended way to export static images is using the plotly_static backend, which uses a headless browser via WebDriver (Chrome or Firefox) for rendering. This is available via the static_export_default feature:
[dependencies]
plotly = { version = "0.14", features = ["static_export_default"] }
This supports PNG, JPEG, WEBP, SVG, and PDF formats:
use plotly::{Plot, Scatter,ImageFormat};
let mut plot = Plot::new();
plot.add_trace(Scatter::new(vec![0, 1, 2], vec![2, 1, 0]));
plot.write_image("out.png", ImageFormat::PNG, 800, 600, 1.0)?;
plot.write_image("out.svg", ImageFormat::SVG, 800, 600, 1.0)?;
let base64_data = plot.to_base64(ImageFormat::PNG, 800, 600, 1.0)?;
let svg_string = plot.to_svg(800, 600, 1.0)?;
Note: This feature requires a WebDriver-compatible browser (Chrome or Firefox) as well as a Webdriver (chromedriver/geckodriver) to be available on the system.
The above example uses the legacy API that is backwards compatible with the Kaleido API. However, for more efficient workflows a StaticExporter object can be built and reused between calls to write_image.
More specifically, enabling any of the plotly features static_export_chromedriver, static_export_geckodriver, or static_export_default gives access to both the synchronous StaticExporter and the asynchronous AsyncStaticExporter (available via plotly::plotly_static). For exporter reuse and up-to-date sync/async usage patterns, please see the dedicated example in examples/static_export, which demonstrates both synchronous and asynchronous exporters and how to reuse a single exporter instance across multiple exports.
For further details see plotly_static crate documentation.
Exporting Static Images with Kaleido (legacy)
Enable the kaleido feature and opt in for automatic downloading of the kaleido binaries by doing the following
# Cargo.toml
[dependencies]
plotly = { version = "0.14", features = ["kaleido", "kaleido_download"] }
Alternatively, enable only the kaleido feature and manually install Kaleido.
# Cargo.toml
[dependencies]
plotly = { version = "0.14", features = ["kaleido"] }
With the feature enabled, plots can be saved as any of png, jpeg, webp, svg, pdf and eps. Note that the plot will be a static image, i.e. they will be non-interactive.
Exporting a simple plot looks like this:
use plotly::{ImageFormat, Plot};
let mut plot = Plot::new();
let trace = Scatter::new(vec![0, 1, 2], vec![2, 1, 0]);
plot.add_trace(trace);
plot.write_image("out.png", ImageFormat::PNG, 800, 600, 1.0);
Kaleido external dependency
When developing applications for your host, enabling both kaleido and kaleido_download features will ensure that the kaleido binary is downloaded for your system's architecture at compile time. After download, it is unpacked into a specific path, e.g., on Linux this is /home/USERNAME/.config/kaleido. With these two features enabled, static images can be exported as described in the next section as long as the application runs on the same machine where it has been compiled on.
When the applications developed with plotly.rs are intended for other targets or when the user wants to control where the kaleido binary is installed then Kaleido must be manually downloaded and installed. Setting the environment variable KALEIDO_PATH=/path/installed/kaleido/ will ensure that applications that were built with the kaleido feature enabled can locate the kaleido executable and use it to generate static images.
Kaleido binaries are available on Github release page. It currently supports Linux(x86_64), Windows(x86_64) and MacOS(x86_64/aarch64).
Usage Within a WASM Environment
Plotly.rs can be used with a WASM-based frontend framework. Note that the kaleido and plotly_static static export features are not supported in WASM environments and will throw a compilation error if used.
The needed dependencies are automatically enabled for wasm32 targets at compile time and there is no longer a need for the custom wasm flag in this crate.
First, make sure that you have the Plotly JavaScript library in your base HTML template:
<!-- index.html -->
<!doctype html>
<html lang="en">
<head>
<!-- snip -->
<script src="https://cdn.plot.ly/plotly-2.14.0.min.js"></script>
</head>
<!-- snip -->
</html>
A simple Plot component would look as follows, using Yew as an example frontend framework:
use plotly::{Plot, Scatter};
use yew::prelude::*;
#[function_component(PlotComponent)]
pub fn plot_component() -> Html {
let p = yew_hooks::use_async::<_, _, ()>({
let id = "plot-div";
let mut plot = Plot::new();
let trace = Scatter::new(vec![0, 1, 2], vec![2, 1, 0]);
plot.add_trace(trace);
async move {
plotly::bindings::new_plot(id, &plot).await;
Ok(())
}
});
use_effect_with((), move |_| {
p.run();
|| ()
});
html! {
<div id="plot-div"></div>
}
}
Timeseries Downsampling
In situations where the number of points of a timeseries is extremely large, generating a plot and visualizing it using plotly will be slow or not possible.
For such cases, it is ideal to use a downsampling method that preserves the visual characteristics of the timeseries. One such method is to use the Largest Triangle Three Bucket (LTTB) method. The Min
