Getting started

Installation

pyobsplot can be installed with pip:

pip install pyobsplot

If you want to use output formats like PNG or SVG, you must have a working installation of node.js and you must install the pyobsplot npm package globally or locally:

# Install locally
npm install pyobsplot
# Install globally
npm install -g pyobsplot

Creating a plot

To use pyobsplot, you must import its Plot object with:

from pyobsplot import Plot

To create a plot, call the Plot.plot method with a plot specification: a Python dictionary with a syntax nearly identical as the JavaScript one.

So, starting with a very simple DataFrame:

import polars as pl

data = pl.DataFrame(
    {
        "x": [1, 5, 2, 4, 6, 2, 4],
        "y": [2, 1, 3, 4, 5, 1, 2],
        "type": ["T1", "T2", "T1", "T2", "T1", "T1", "T2"],
    }
)

If your JavaScript plot function looks like this:

Plot.plot(
    {
        grid: true,
        marks: [Plot.dot(data, {x: "x", y: "y", fill: "type", r: 5})]
    }
)

Then you can reproduce the plot with:

Plot.plot(
    {
        "grid": True,
        "marks": [Plot.dot(data, {"x": "x", "y": "y", "fill": "type", "r": 5})],
    }
)
1.01.52.02.53.03.54.04.55.0↑ y1.01.52.02.53.03.54.04.55.05.56.0x →

The syntax here is almost identical, except that dictionary keys must be quoted, and JavaScript true is be replaced by Python True.

You can use pandas and polars DataFrames as data sources, they are automatically serialized and passed to JavaScript via Arrow IPC format:

penguins = pl.read_csv("data/penguins.csv")

Plot.plot(
    {
        "grid": True,
        "color": {"legend": True},
        "marks": [
            Plot.dot(
                penguins,
                {"x": "flipper_length_mm", "y": "body_mass_g", "fill": "island"},
            )
        ],
    }
)
BiscoeDreamTorgersen
3,0003,5004,0004,5005,0005,5006,000↑ body_mass_g180190200210220230flipper_length_mm →

Output formats

By default, plots will be created as Jupyter widgets, but pyobsplot is also able to output plots in PNG, SVG or static HTML formats.

The output format is configured by passing a format argument to Plot.plot():

# Display plot as PNG
Plot.plot(Plot.auto(penguins, {"x": "flipper_length_mm"}), format="png")

To save the plot to a file, you can add a path argument. The file extension will determine the output type, which can be HTML, PNG, SVG or PDF:

# Save plot as SVG
Plot.plot(Plot.auto(penguins, {"x": "flipper_length_mm"}), path="plot.svg")
Note

With the “widget” format, export can only be done to HTML files.

Learn more

To go further, see the usage page.