Skip to main content

Crate plotlars

Crate plotlars 

Source
Expand description

§Plotlars

Crates.io docs.rs Downloads License

Plotlars is a versatile Rust library that acts as a wrapper around the Plotly crate, bridging the gap between the powerful Polars data analysis library and Plotly. It simplifies the process of creating visualizations from data frames, allowing developers to focus on data insights rather than the intricacies of plot creation.

§Implemented Plots Overview


Array 2D

Bar Plot

Box Plot

Candlestick

Contour Plot

Density Mapbox

Heat Map

Histogram

Image

Line Plot

Mesh3D

OHLC

Pie Chart

Sankey Diagram

Scatter 3D Plot

Scatter Geo

Scatter Map

Scatter Plot

Scatter Polar

Subplot Grid Irregular

Subplot Grid Regular

Surface Plot

Table

Time Series

§Plot Types Reference

Plot TypeRequired ParamsFacetGroup
Array2dPlotdata
BarPlotdata, labels, valuesYesYes
BoxPlotdata, labels, valuesYesYes
CandlestickPlotdata, dates, open, high, low, close
ContourPlotdata, x, y, zYes
DensityMapboxdata, lat, lon, z
HeatMapdata, x, y, zYes
Histogramdata, xYesYes
Imagepath
LinePlotdata, x, yYes
Mesh3Ddata, x, y, zYes
OhlcPlotdata, dates, open, high, low, close
PieChartdata, labelsYes
SankeyDiagramdata, sources, targets, valuesYes
Scatter3dPlotdata, x, y, zYesYes
ScatterGeodata, lat, lonYes
ScatterMapdata, latitude, longitudeYes
ScatterPlotdata, x, yYesYes
ScatterPolardata, theta, rYesYes
SubplotGridplots
SurfacePlotdata, x, y, zYes
Tabledata, columns
TimeSeriesPlotdata, x, yYes

§Motivation

The creation of Plotlars was driven by the need to simplify the process of creating complex plots in Rust, particularly when working with the powerful Polars data manipulation library. Generating visualizations often requires extensive boilerplate code and deep knowledge of both the plotting library (Plotly) and the data structure. This complexity can be a significant hurdle, especially for users who need to focus on analyzing and interpreting data rather than wrestling with intricate plotting logic.

To illustrate this, consider the following example where a scatter plot is created without Plotlars:

use plotly::{
    common::*,
    layout::*,
    Plot,
    Scatter,
};

use polars::prelude::*;

fn main() {
    let dataset = LazyCsvReader::new(PlRefPath::new("data/penguins.csv"))
        .finish().unwrap()
        .select([
            col("species"),
            col("flipper_length_mm").cast(DataType::Int16),
            col("body_mass_g").cast(DataType::Int16),
        ])
        .collect().unwrap();

    let group_column = "species";
    let x = "body_mass_g";
    let y = "flipper_length_mm";

    let groups = dataset
        .column(group_column).unwrap()
        .unique().unwrap();

    let layout = Layout::new()
        .title(Title::with_text("Penguin Flipper Length vs Body Mass"))
        .x_axis(Axis::new().title(Title::with_text("Body Mass (g)")))
        .y_axis(Axis::new().title(Title::with_text("Flipper Length (mm)")))
        .legend(Legend::new().title(Title::with_text("Species")));

    let mut plot = Plot::new();
    plot.set_layout(layout);

    let groups_str = groups.str().unwrap();

    for group in groups_str.into_iter() {
        let group = group.unwrap();

        let data = dataset
            .clone()
            .lazy()
            .filter(col(group_column).eq(lit(group)))
            .collect().unwrap();

        let x = data
            .column(x).unwrap()
            .i16().unwrap()
            .to_vec();

        let y = data
            .column(y).unwrap()
            .i16().unwrap()
            .to_vec();

        let trace = Scatter::default()
            .x(x)
            .y(y)
            .name(group)
            .mode(Mode::Markers)
            .marker(Marker::new().size(10).opacity(0.5));

        plot.add_trace(trace);
    }

    plot.show();
}

In this example, creating a scatter plot involves writing substantial code to manually handle the data and configure the plot, including grouping the data by category and setting up the plot layout.

Now, compare that to the same plot created using Plotlars:

use plotlars::{
    ScatterPlot,
    Plot,
    Rgb,
};

use polars::prelude::*;

fn main() {
    let dataset = LazyCsvReader::new(PlRefPath::new("data/penguins.csv"))
        .finish().unwrap()
        .select([
            col("species"),
            col("flipper_length_mm").cast(DataType::Int16),
            col("body_mass_g").cast(DataType::Int16),
        ])
        .collect().unwrap();

    ScatterPlot::builder()
        .data(&dataset)
        .x("body_mass_g")
        .y("flipper_length_mm")
        .group("species")
        .opacity(0.5)
        .size(12)
        .colors(vec![
            Rgb(178, 34, 34),
            Rgb(65, 105, 225),
            Rgb(255, 140, 0),
        ])
        .plot_title("Penguin Flipper Length vs Body Mass")
        .x_title("Body Mass (g)")
        .y_title("Flipper Length (mm)")
        .legend_title("Species")
        .build()
        .plot();
}

This is the output:

Plot example

With Plotlars, the same scatter plot is created with significantly less code. The library abstracts away the complexities of dealing with individual plot components and allows the user to specify high-level plot characteristics. This streamlined approach not only saves time but also reduces the potential for errors and makes the code more readable and maintainable.

§Installation

cargo add plotlars

§Running the examples

Plotlars comes with several ready‑to‑use demo programs in the examples/ directory. You can build and execute any of them with Cargo’s --example flag:

cargo run --example barplot

Replace barplot with the file name (without the .rs extension) of the example you want to run.

§Features

  • Seamless Integration with Polars: Leverage the power of Polars for efficient data manipulation and analysis.
  • Support for Multiple Plot Types: Easily create bar, line, scatter, and other plot types.
  • Customization: Modify plot appearance with an intuitive API.

§Exporting Plots

Plotlars supports exporting plots to static image files in various formats (PNG, JPG, WEBP, SVG) through the write_image method.

§Prerequisites

To use image export functionality, you need to enable one of the export features and have the corresponding WebDriver installed:

  • Default (recommended - uses any available driver):

    cargo add plotlars --features export-default
  • Chrome/Chromium:

    cargo add plotlars --features export-chrome

    Install ChromeDriver: https://chromedriver.chromium.org/

  • Firefox:

    cargo add plotlars --features export-firefox

    Install GeckoDriver: https://github.com/mozilla/geckodriver/releases

§Usage

use plotlars::{ScatterPlot, Plot};
use polars::prelude::*;

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let dataset = LazyCsvReader::new(PlRefPath::new("data/penguins.csv"))
        .finish()?
        .collect()?;

    let plot = ScatterPlot::builder()
        .data(&dataset)
        .x("body_mass_g")
        .y("flipper_length_mm")
        .plot_title("Penguin Data")
        .build();

    // Export as PNG (1200x800 pixels, 2x scale for high DPI)
    plot.write_image("output.png", 1200, 800, 2.0)?;

    Ok(())
}

§Plotlars in Jupyter Notebooks

Plotlars seamlessly integrates with Jupyter Notebooks, allowing you to leverage the power of interactive data visualization directly within your notebook environment. This integration is made possible through the use of the evcxr project, which provides a Jupyter kernel for the Rust programming language.

Jupyter notebook

With Polars, evcxr, and Plotlars, data science in Rust leaps to the next level , making powerful data analysis and visualization more accessible and efficient than ever before.

§License

This project is licensed under the MIT License. See the LICENSE.txt file for details.

§Acknowledgements

  • Polars: For providing a fast and efficient data manipulation library.
  • Plotly: For the inspiration and ideas behind visualization libraries.
  • Evcxr: For enabling the use of Rust in Jupyter Notebooks.
  • Rust Community: For the support and development of an amazing programming language.

Structs§

Array2dPlot
A structure representing a 2D array plot.
Axis
A structure representing a customizable axis.
BarPlot
A structure representing a bar plot.
BoxPlot
A structure representing a box plot.
CandlestickPlot
A structure representing a Candlestick financial chart.
Cell
A structure representing cell formatting for tables.
ColorBar
A structure representing a color bar component for visualizations.
ContourPlot
A structure representing a contour plot.
DensityMapbox
A structure representing a density mapbox visualization.
Dimensions
A structure representing plot dimensions and sizing behavior.
Direction
A structure representing the styling for candlestick directions (increasing/decreasing).
FacetConfig
A structure representing facet configuration for creating small multiples.
Header
A structure representing header formatting for tables.
HeatMap
A structure representing a heat map.
Histogram
A structure representing a histogram.
Image
A structure representing an image plot.
Legend
A structure representing a customizable plot legend.
Lighting
A structure describing the lighting model.
LinePlot
A structure representing a line plot.
Mesh3D
A structure representing a 3D mesh plot.
OhlcPlot
A structure representing an OHLC (Open-High-Low-Close) financial chart.
PieChart
A structure representing a pie chart.
Rgb
A structure representing an RGB color with red, green, and blue components.
SankeyDiagram
A structure representing a Sankey diagram.
Scatter3dPlot
A structure representing a 3D scatter plot.
ScatterGeo
A structure representing a geographic scatter plot.
ScatterMap
A structure representing a scatter plot on a map.
ScatterPlot
A structure representing a scatter plot.
ScatterPolar
A structure representing a scatter polar plot.
SubplotGrid
A structure representing a subplot grid layout.
SurfacePlot
A structure representing a 3-D surface plot.
Table
A structure representing a table plot.
Text
A structure representing text with customizable content, font, size, and color.
TimeSeriesPlot
A structure representing a time series plot.

Enums§

Arrangement
An enumeration representing node arrangement strategies for Sankey diagrams.
AxisSide
Enumeration representing the position of the axis.
AxisType
Enumeration representing the type of the axis.
BarMode
An enumeration representing how bars are displayed when multiple bar traces share the same axis.
Coloring
Enumeration representing the coloring strategy applied to contour levels.
FacetScales
Controls axis scaling behavior across facets in a faceted plot.
Fill
An enumeration representing different fill modes for area traces in plots.
IntensityMode
An enumeration representing the source of intensity values for mesh coloring.
Line
An enumeration representing different styles of lines that can be used in plots.
Mode
An enumeration representing different drawing modes for scatter-type plots.
Orientation
An enumeration representing the orientation of the legend.
Palette
Example
Shape
An enumeration of various marker shapes used in plots.
TickDirection
Enumeration representing the direction of axis ticks.
ValueExponent
An enumeration representing the format for value exponents on the axis.

Traits§

Plot
A trait representing a generic plot that can be displayed or rendered.
PlotHelper
Helper trait for internal use by the Plot trait implementation. Can be used to get the underlying layout and traces of a plot (for example, to create a subplot).