plotly.rs Documentation

repository·main·Indexed 23 days ago

https://github.com/plotly/plotly.rs

A Rust wrapper for the Plotly.js graphing library (version 0.14.1) used for creating high-quality, interactive, and static data visualizations. It supports exporting plots to PNG, JPEG, WEBP, SVG, and PDF via the plotly_static crate and kaleido feature. The library provides integration for Jupyter environments using evcxr_jupyter, WebAssembly applications via Yew and Trunk, and customizable HTML output for responsive, full-page layouts.

Tokens
33.8K
Snippets
96
Records
218
Agent score
79%

What's inside plotly.rs

  1. Export Plotly plots to static images using plotly_static

    main

    The plotly_static crate provides an interface to convert Plotly plots into static image formats including PNG, JPEG, WEBP, SVG, and PDF. It achieves this by using WebDriver and headless browsers.

    There are two main API styles:

    1. Old Style API: Creates a new StaticExporter instance for every write_image call. This is suitable for one-off exports.
    2. New Style API (Recommended): Allows you to reuse a single StaticExporter instance across multiple exports, which is significantly more efficient for performance.

    Both synchronous (StaticExporter) and asynchronous (AsyncStaticExporter) APIs are available via plotly::plotly_static when the appropriate static export features are enabled.

  2. Core Features of Plotly.rs

    main

    Plotly.rs provides a comprehensive suite of features for data visualization in Rust, including:

    • Jupyter Support: Enables interactive plotting directly within Jupyter notebooks.
    • ndarray Support: Provides seamless integration with the ndarray crate for efficient numerical computing and data handling.
    • Shapes: Allows for adding geometric shapes and text annotations to enhance plot context.
    • Themes: Supports customizing the visual appearance of plots using predefined or custom themes.
    • Static Image Export: Enables exporting interactive plots to static formats like PNG, JPEG, SVG, and PDF using WebDriver.
    • Timeseries Downsampling: Includes tools for downsampling large timeseries datasets to make them suitable for visualization.
  3. Explore Custom Controls for interactive plots

    main

    You can add interactive controls to your plots to dynamically modify data or layout attributes. The available control types in plotly.rs include:

    • Dropdown Menus and Buttons: Use these to switch between different data traces or update layout properties via menu selections.
    • Sliders: Use these to control parameters like time, scale, or specific data indices, allowing for smooth transitions or step-by-step exploration.
    • Animations: Implement frame-based transitions to visualize changes over time or across different parameter states.
  4. Use Sliders for interactive animation and parameter control

    main

    Sliders in plotly.rs provide interactive controls to animate through different data states or parameters. They are distinct from range sliders and are primarily used for:

    1. Animating through time series data: Stepping through sequential data points (e.g., population changes over years).
    2. Changing plot parameters dynamically: Modifying function parameters in real-time (e.g., adjusting the frequency of a wave).

    Key customization capabilities include:

    • Positioning: Controlling x/y coordinates and anchors.
    • Styling: Background color, border color, width, and font.
    • Behavior: Active step highlighting and step execution control.
    • Dimensions: Length, width, and orientation (horizontal or vertical).
    • Steps: Defining multiple steps, where each step can represent a different data state or parameter value.
  5. Using Shape types in Plotly

    main

    The plotly.rs library supports various shape types to annotate plots. Based on the documentation examples, you can implement:

    • Filled Area Charts: Using shapes to create filled regions.
    • Lines: Positioned either relative to the axes (using axis coordinates) or relative to the plot (using paper coordinates).
    • Rectangles: Used for highlighting specific regions, such as time series intervals, or creating Venn diagrams. These can be positioned relative to axes or the plot.
    • Circles: Used for highlighting clusters of points or creating Venn diagrams.
    • SVG Paths: For custom complex shapes.
    • Subplots: Shapes can be added specifically to subplots within a layout.
  6. Create dynamic animations in Plotly.rs

    main
    Animations in Plotly.rs enable the creation of dynamic, interactive visualizations that transition through different data states over time. This is typically achieved by defining frames that represent different snapshots of the data and providing UI controls like buttons and sliders to trigger transitions or step through the animation sequence.
  7. How Funnel Charts work in plotly.rs

    main

    A Funnel Chart visualizes how a quantity narrows through a sequence of stages. It is a containment-based visualization where each stage is treated as a subset of the stage preceding it.

    Key behaviors:

    • Upstream-first ordering: Stages are processed starting from index 0, which is drawn at the top of the chart. This is the inverse of a standard category axis.
    • Nesting requirement: Because stages are understood as subsets, Funnel Charts should only be used for pipelines that genuinely nest (e.g., conversion funnels). For independent totals or sequences with negative contributions, use Waterfall Charts instead.
    • Text Information: The text_info property accepts a +-joined flaglist to control what data is displayed on the bands. Available flags include:
      • "value+percent previous": Shows the stage's value and its percentage relative to the previous stage.
      • "percent initial": Shows the share of the very first stage.
      • "percent total": Shows the share of the total quantity.
  8. Create Density Maps with DensityMapbox

    main

    A DensityMapbox trace allows you to render a kernel density estimate as a heatmap layer on top of a Mapbox-style basemap.

    To use DensityMapbox, you will typically need to configure a Mapbox object within your Layout to specify the basemap style and center point. Note that rendering these maps requires an active internet connection to fetch the Mapbox basemap tiles.

    Commonly used imports for density maps include:

    • plotly::DensityMapbox for the trace type.
    • plotly::layout::{Mapbox, MapboxStyle, Center} for configuring the map container.
  9. Create Table charts with the Table trace

    main

    A Table trace renders structured data as an HTML table within a plot. Unlike cartesian traces (like scatter or bar charts), Table traces do not use x/y axes. Instead, you define the table structure using Header and Cells blocks.

    To customize the table, you can use the following modules:

    • Header: Defines the top row of the table.
    • Cells: Defines the data rows.
    • TableAlign: Controls text alignment.
    • TableFill: Controls background colors.
    • TableFont: Controls text styling.
    • TableLine: Controls border styling.
    use plotly::color::NamedColor;
    use plotly::traces::table::{
        Align as TableAlign, Cells, Fill as TableFill, Font as TableFont, Header, Line as TableLine,
    };
    use plotly::{Plot, Table};
  10. How plotly.rs works

    main

    Plotly.rs is a thin wrapper around the plotly.js library. It provides Rust structs and enums that are serialized to JSON and passed to plotly.js for rendering.

    Core Components

    • Plot: The main container that holds one or more Trace objects.
    • Trace: Describes the structure of the data to be displayed (e.g., Scatter, Bar, Histogram).
    • Layout: (Optional) Specifies the layout of the plot.
    • Configuration: (Optional) Specifies the configuration of the plot.

    Key Patterns

    • Builder Pattern: The library uses the builder pattern extensively. You only specify the attributes you want to change; all other attributes fall back to plotly.js defaults.
    • Namespace Hoisting: Common components like Plot, Layout, and various traces (e.g., Scatter) are hoisted into the plotly namespace for easy importing.
  11. Configure Scatter Plot Modes and Styles

    main

    Scatter plots in plotly.rs can be customized using several key components:

    Modes

    Use the Mode enum to define how data points are connected:

    • Mode::Markers: Only points are shown.
    • Mode::Lines: Points are connected by lines.
    • Mode::LinesAndMarkers: Both points and connecting lines are shown.

    Styling

    • Markers: Use the Marker struct to control point size, color, and symbol.
    • Lines: Use the Line struct to control line width, color, and DashType.
    • Colors: Colors can be specified using NamedColor, Rgb, or Rgba from the plotly::color module.
    • Data Labels: Labels can be configured for hover interactions or displayed directly on the plot.
  12. Create multiple traces from a 2D `ndarray`

    main

    To display multiple traces from a 2D array (Array<_, Ix2>), use the Scatter::to_traces method.

    This method requires three arguments:

    1. The common axis (e.g., an Ix1 array for the x-axis).
    2. The 2D array containing the trace data.
    3. An ArrayTraces enum to resolve whether traces are arranged by columns or rows.

    Use ArrayTraces::OverColumns if every column in the matrix represents an individual trace. Use ArrayTraces::OverRows if every row in the matrix represents an individual trace.

    use plotly::common::{Mode};
    use plotly::{Plot, Scatter};
    use ndarray::{Array, Ix1, Ix2};
    use plotly::ndarray::ArrayTraces;
    
    fn multiple_ndarray_traces_over_columns() {
        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));
        // ... (populate ys) ...
    
        let traces = Scatter::default()
            .mode(Mode::LinesMarkers)
            .to_traces(t, ys, ArrayTraces::OverColumns);
    
        let mut plot = Plot::new();
        plot.add_traces(traces);
        plot.show();
    }