from pyobsplot import Plot
Getting started
Installation
pyobsplot
can be installed with pip
:
pip install pyobsplot
If you want to use the jsdom
renderer, 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
Usage
To use pyobsplot
, you must import at least its Plot
class with:
To create a plot, call the Plot.plot
method with a plot specification. The simplest specification form is 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
must 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"},
{
)
],
} )
Plot generator object
Calling Plot.plot()
is the fastest way to generate a plot with the default settings, but for further customization you can import the Obsplot
class and create a plot generator object:
from pyobsplot import Obsplot, Plot
= Obsplot() op
You can then create plots by calling this generator object with your plot specification:
op(
{"grid": True,
"marks": [Plot.dot(data, {"x": "x", "y": "y", "fill": "type", "r": 5})],
} )
For the simplest cases, you can also create your plot directly by passing a Plot
mark method:
"x": "flipper_length_mm"})) op(Plot.auto(penguins, {
jsdom renderer
By default, plots will be created as Jupyter widgets. This allows for (very basic) interactivity, but also generates bigger files. An alternative is to use the jsdom
renderer, which generates SVG or HTML outputs.
The renderer is configured by passing a renderer
argument to Obsplot()
when creating a generator object:
# Switch to widget renderer (default one)
= Obsplot(renderer="widget")
opw # Switch to jsdom renderer
= Obsplot(renderer="jsdom") opj
Learn more
To go further, see the usage page.