from pyobsplot import Plot
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:
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
= pl.DataFrame(
data
{"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})],
} )
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:
= pl.read_csv("data/penguins.csv")
penguins
Plot.plot(
{"grid": True,
"color": {"legend": True},
"marks": [
Plot.dot(
penguins,"x": "flipper_length_mm", "y": "body_mass_g", "fill": "island"},
{
)
],
} )
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
"x": "flipper_length_mm"}), format="png") Plot.plot(Plot.auto(penguins, {
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
"x": "flipper_length_mm"}), path="plot.svg") Plot.plot(Plot.auto(penguins, {
With the “widget” format, export can only be done to HTML files.
Learn more
To go further, see the usage page.