cpmech
plotpy
Rust

Rust plotting library using Python (Matplotlib)

Last updated Jun 8, 2026
86
Stars
10
Forks
0
Issues
0
Stars/day
Attention Score
41
Language breakdown
No language data available.
โ–ธ Files click to expand
README

Rust plotting library using Python (Matplotlib)

documentation Track Awesome List

Arch Ubuntu

Contents

- Arch Linux - Debian/Ubuntu Linux - Other systems - Setting Cargo.toml - Use of Jupyter via evcxr - Barplot - Boxplot - Canvas - Contour - Curve - Histogram - Image - InsetAxes - Surface - Text - Chaining pattern (builder style) - Consistent conventions across all files

Introduction

This crate implements functions for generating plots and drawings in Rust. It uses Python/Matplotlib but is designed specifically for Rust developers, combining the convenience of a Rust-native API with the exceptional quality of Matplotlib ๐Ÿ˜€.

Plotpy is more verbose than native Matplotlib because the aim here is to take advantage of the intelligence of the IDE (e.g., VS Code) to auto-complete the code while developing in Rust.

Plotpy generates Python code in a temporary directory (e.g., /tmp/plotpy). It then runs the code via Python 3 using Rust's std::process::Command. The result is an image file such as SVG.

For more information (and examples), check out the plotpy documentation on docs.rs.

See also the examples directory with the output of the integration tests.

Installation

This code is mainly tested on Arch Linux and Debian/Ubuntu Linux.

This crate needs Python3 and Matplotlib.

Arch Linux

Install the dependencies:

pacman -Syu --noconfirm python-matplotlib

Debian/Ubuntu Linux

Install the dependencies:

sudo apt install python3-matplotlib

Other systems

It is possible to run plotpy in other systems where Python and Matplotlib are already installed. The Rust code calls python3 via std::process::Command. However, there is an option to call a different python executable; for instance (the code below is untested):

let mut plot = Plot::new();
plot.setpythonexe("C:\Windows11\WhereIs\python.exe")
    .add(...)
    .save(...)?;

Setting Cargo.toml

Crates.io

๐Ÿ‘† Check the crate version and update your Cargo.toml accordingly:

[dependencies]
plotpy = "*"

Use of Jupyter via evcxr

Plotpy can be used with Jupyter via evcxr. Thus, it can interactively display the plots in a Jupyter Notebook. This feature requires the installation of evcxr. See the Jupyter/evcxr article.

The following code shows a minimal example (the code below is untested)

// set the python path
let python = "where-is-my/python";

// set the figure path and name to be saved let path = "my-figure.svg";

// plot and show in a Jupyter notebook let mut plot = Plot::new(); plot.setpythonexe(python) .setlabelx("x") .setlabely("y") .showinjupyter(path)?;

Examples

Note, below StrError is defined as pub type StrError = &'static str; โ€” a type alias for a static string slice. It's used throughout the library as the error type returned from functions. It's essentially a lightweight, allocation-free error type that avoids pulling in a full error-handling crate.

Barplot

See the documentation

use plotpy::{Barplot, Plot, StrError};

fn main() -> Result<(), StrError> { // data let fruits = ["Apple", "Banana", "Orange"]; let prices = [10.0, 20.0, 30.0]; let errors = [3.0, 2.0, 1.0];

// barplot object and options let mut bar = Barplot::new(); bar.set_errors(&errors) .set_horizontal(true) .setwithtext("edge") .drawwithstr(&fruits, &prices);

// save figure let mut plot = Plot::new(); plot.setinvy() .add(&bar) .set_title("Fruits") .setlabelx("price");

// plot.save("/tmp/plotpy/doctests/docbarplot_3.svg")?; Ok(()) }

barplot.svg

Boxplot

See the documentation

use plotpy::{Boxplot, Plot, StrError};

fn main() -> Result<(), StrError> { // data (as a nested list) let data = vec![ vec![1, 2, 3, 4, 5], // A vec![2, 3, 4, 5, 6, 7, 8, 9, 10], // B vec![3, 4, 5, 6], // C vec![4, 5, 6, 7, 8, 9, 10], // D vec![5, 6, 7], // E ];

// x ticks and labels let n = data.len(); let ticks: Vec<> = (1..(n + 1)).intoiter().collect(); let labels = ["A", "B", "C", "D", "E"];

// boxplot object and options let mut boxes = Boxplot::new(); boxes.draw(&data);

// save figure let mut plot = Plot::new(); plot.add(&boxes) .set_title("boxplot documentation test") .setticksx_labels(&ticks, &labels);

// plot.save("/tmp/plotpy/doctests/docboxplot_2.svg")?; Ok(()) }

boxplot.svg

Canvas

See the documentation

use plotpy::{Canvas, Plot, PolyCode, StrError};

fn main() -> Result<(), StrError> { // codes let data = [ (3.0, 0.0, PolyCode::MoveTo), (1.0, 1.5, PolyCode::Curve4), (0.0, 4.0, PolyCode::Curve4), (2.5, 3.9, PolyCode::Curve4), (3.0, 3.8, PolyCode::LineTo), (3.5, 3.9, PolyCode::LineTo), (6.0, 4.0, PolyCode::Curve4), (5.0, 1.5, PolyCode::Curve4), (3.0, 0.0, PolyCode::Curve4), ];

// polycurve let mut canvas = Canvas::new(); canvas.setfacecolor("#f88989").setedgecolor("red"); canvas.polycurve_begin(); for (x, y, code) in data { canvas.polycurve_add(x, y, code); } canvas.polycurve_end(true);

// add canvas to plot let mut plot = Plot::new(); plot.add(&canvas);

// save figure plot.set_range(1.0, 5.0, 0.0, 4.0) .setframeborders(false) .sethideaxes(true) .setequalaxes(true) .setshowerrors(true);

// plot.save("/tmp/plotpy/doctests/doccanvas_polycurve.svg")?; Ok(()) }

canvas.svg

Contour

See the documentation

use plotpy::{generate3d, Contour, Plot, StrError};

fn main() -> Result<(), StrError> { // generate (x,y,z) matrices let n = 21; let (x, y, z) = generate3d(-2.0, 2.0, -2.0, 2.0, n, n, |x, y| x x - y y);

// configure contour let mut contour = Contour::new(); contour .setcolorbarlabel("temperature") .setcolormapname("terrain") .setselectedlevel(0.0, true);

// draw contour contour.draw(&x, &y, &z);

// add contour to plot let mut plot = Plot::new(); plot.add(&contour) .set_labels("x", "y");

// plot.save("/tmp/plotpy/readme_contour.svg")?; Ok(()) }

contour.svg

Curve

See the documentation

use plotpy::{linspace, Curve, Plot, StrError};

fn main() -> Result<(), StrError> { // generate (x,y) points let x = linspace(-1.0, 1.0, 21); let y: Vec<_> = x.iter().map(|v| 1.0 / (1.0 + f64::exp(-5.0 v))).collect();

// configure curve let mut curve = Curve::new(); curve .set_label("logistic function") .setlinealpha(0.8) .setlinecolor("#5f9cd8") .setlinestyle("-") .setlinewidth(5.0) .setmarkercolor("#eeea83") .setmarkerevery(5) .setmarkerline_color("#da98d1") .setmarkerline_width(2.5) .setmarkersize(20.0) .setmarkerstyle("*");

// draw curve curve.draw(&x, &y);

// add curve to plot let mut plot = Plot::new(); plot.add(&curve) .setnumticks_y(11) .gridlabelslegend("x", "y");

// plot.save("/tmp/plotpy/doctests/doccurve.svg")?; Ok(()) }

curve.svg

Histogram

See the documentation

use plotpy::{Histogram, Plot, StrError};

fn main() -> Result<(), StrError> { // set values let values = vec![ vec![1, 1, 1, 2, 2, 2, 2, 2, 3, 3, 4, 5, 6], // first series vec![-1, -1, 0, 1, 2, 3], // second series vec![5, 6, 7, 8], // third series ];

// set labels let labels = ["first", "second", "third"];

// configure and draw histogram let mut histogram = Histogram::new(); histogram.set_colors(&["#9de19a", "#e7eca3", "#98a7f2"]) .setlinewidth(10.0) .set_stacked(true) .set_style("step"); histogram.draw(&values, &labels);

// add histogram to plot let mut plot = Plot::new(); plot.add(&histogram) .setframeborder(true, false, true, false) .gridlabelslegend("values", "count");

// plot.save("/tmp/plotpy/doctests/dochistogram.svg")?; Ok(()) }

histogram

Image

use plotpy::{Image, Plot, StrError};

fn main() -> Result<(), StrError> { // set values let data = [ [0.8, 2.4, 2.5, 3.9, 0.0, 4.0, 0.0], [2.4, 0.0, 4.0, 1.0, 2.7, 0.0, 0.0], [1.1, 2.4, 0.8, 4.3, 1.9, 4.4, 0.0], [0.6, 0.0, 0.3, 0.0, 3.1, 0.0, 0.0], [0.7, 1.7, 0.6, 2.6, 2.2, 6.2, 0.0], [1.3, 1.2, 0.0, 0.0, 0.0, 3.2, 5.1], [0.1, 2.0, 0.0, 1.4, 0.0, 1.9, 6.3], ];

// image plot and options let mut img = Image::new(); img.setcolormapname("hsv").draw(&data);

// save figure let mut plot = Plot::new(); plot.add(&img);

// plot.save("/tmp/plotpy/doctests/docimage_1.svg")?; Ok(()) }

image

InsetAxes

use plotpy::{Curve, InsetAxes, Plot, StrError};

fn main() -> Result<(), StrError> { // draw curve let mut curve = Curve::new(); curve.draw(&[0.0, 1.0, 2.0], &[0.0, 1.0, 4.0]);

// allocate inset and add curve to it let mut inset = InsetAxes::new(); inset .add(&curve) // add curve to inset .set_range(0.5, 1.5, 0.5, 1.5) // set the range of the inset .draw(0.5, 0.5, 0.4, 0.3);

// add curve and inset to plot let mut plot = Plot::new(); plot.add(&curve) .set_range(0.0, 5.0, 0.0, 5.0) .add(&inset); // IMPORTANT: add inset after setting the range

// plot.save("/tmp/plotpy/doctests/docinsetaxesadd.svg")?; Ok(()) }

inset</em>axes

Surface

See the documentation

use plotpy::{Plot, StrError, Surface};

fn main() -> Result<(), StrError> { // star let r = &[1.0, 1.0, 1.0]; let c = &[-1.0, -1.0, -1.0]; let k = &[0.5, 0.5, 0.5]; let mut star = Surface::new(); star.setcolormapname("jet") .draw_superquadric(c, r, k, -180.0, 180.0, -90.0, 90.0, 40, 20)?;

// pyramids let c = &[1.0, -1.0, -1.0]; let k = &[1.0, 1.0, 1.0]; let mut pyramids = Surface::new(); pyramids .setcolormapname("inferno") .draw_superquadric(c, r, k, -180.0, 180.0, -90.0, 90.0, 40, 20)?;

// rounded cube let c = &[-1.0, 1.0, 1.0]; let k = &[4.0, 4.0, 4.0]; let mut cube = Surface::new(); cube.setsurfcolor("#ee29f2") .draw_superquadric(c, r, k, -180.0, 180.0, -90.0, 90.0, 40, 20)?;

// sphere let c = &[0.0, 0.0, 0.0]; let k = &[2.0, 2.0, 2.0]; let mut sphere = Surface::new(); sphere .setcolormapname("rainbow") .draw_superquadric(c, r, k, -180.0, 180.0, -90.0, 90.0, 40, 20)?;

// sphere (direct) let mut sphere_direct = Surface::new(); spheredirect.drawsphere(&[1.0, 1.0, 1.0], 1.0, 40, 20)?;

// add features to plot let mut plot = Plot::new(); plot.add(&star) .add(&pyramids) .add(&cube) .add(&sphere) .add(&sphere_direct);

// save figure plot.setequalaxes(true) .setfiguresize_points(600.0, 600.0);

// plot.save("/tmp/plotpy/readme_superquadric.svg")?; Ok(()) }

readme</em>superquadric.svg

Text

use plotpy::{Plot, Text, StrError};
use std::path::Path;

fn main() -> Result<(), StrError> { // configure text let mut text = Text::new(); text.set_color("purple") .setalignhorizontal("center") .setalignvertical("center") .set_fontsize(30.0) .set_bbox(true) .setbboxfacecolor("pink") .setbboxedgecolor("black") .setbboxalpha(0.3) .setbboxstyle("roundtooth,pad=0.3,tooth_size=0.2");

// draw text text.draw_3d(0.5, 0.5, 0.5, "Hello World!");

// add text to plot let mut plot = Plot::new(); plot.add(&text);

// plot.save("/tmp/plotpy/doctests/doctext.svg")?; Ok(()) }

text


Architecture

(Generated by DeepSeek)

Core idea: Generates Python 3 scripts as strings from Rust, then executes them via python3. Not a direct API wrapper โ€” it's a code generator.

  • 25 source files in src/, each a standalone module
  • Each "graph entity" struct (Curve, Barplot, Boxplot, Contour, Surface, Canvas, Histogram, Text, etc.) implements GraphMaker trait (getbuffer() + clearbuffer())
  • Plot is the central coordinator โ€” collects buffers via add(&entity), prepends a Python header, appends plt.savefig(), writes .py file, executes it
  • Only one dependency: num-traits = "0.2" (for generic Num bound)
  • Two data abstraction traits: AsVector (for 1D data) and AsMatrix (for 2D data)

Chaining pattern (builder style)

The entire library follows something.method1().method2().method3() pervasively.

Graph entities โ€” setters return &mut Self:

curve.set_label("logistic")      .setlinecolor("#5f9cd8")      .setlinestyle("-")      .setlinewidth(5.0); curve.draw(&x, &y);
Note: draw() methods don't return &mut Self (they finalize by writing Python code). But pointsbegin()/pointsadd()/points_end() do chain.

Plot โ€” everything returns &mut Self:

plot.set_subplot(2, 2, 1)     .set_title("first")     .add(&curve1)     .gridlabelslegend("x", "y")     .setequalaxes(true);

Consistent conventions across all files

  • new() โ†’ defaults (empty strings, 0.0 sentinels)
  • set_*() โ†’ returns &mut Self
  • options() โ†’ private method builds CSV-style parameter string
  • draw() โ†’ writes Python to buffer using write! macro (all .unwrap() since String writes are infallible)
  • GraphMaker impl โ†’ exposes the buffer
  • Inline #[cfg(test)] mod tests in every file + integration tests under tests/
  • max_width = 120 in rustfmt.toml
  • Error type: pub type StrError = &'static str;
๐Ÿ”— More in this category

ยฉ 2026 GitRepoTrend ยท cpmech/plotpy ยท Updated daily from GitHub