Creation Wasteland Logo

ProjectsDatalys2 Reports → Python API


Datalys2 Reports - Python API

Price
Free
Version
0.2.5
Type
Python Library
Marketplaces
GitHubPyPI
description
A Python library for programmatically creating rich, interactive data reports. Simplifies report generation through a clean API and integrates seamlessly with popular data science tools.

Datalys2 Reporting Python API

Version 0.2.6

A Python library to build and compile interactive HTML reports using the Datalys2 Reporting framework.

Note: Compatible with dl2 version 0.2.6 https://github.com/kameronbrooks/datalys2-reporting

Installation

pip install dl2-reports

Quick Start

import pandas as pd
from dl2_reports import DL2Report

# Create a report
report = DL2Report(title="My Report")

# Add data
df = pd.DataFrame({"A": [1, 2], "B": [3, 4]})
report.add_df("my_data", df, compress=True)

# Add a page and visual
page = report.add_page("Overview")
page.add_row().add_kpi("my_data", value_column="A", title="Metric A")

# Save to HTML or show in Jupyter
report.save("report.html")
report.show()

Data Compression

Always use compression for production reports. The Python API provides automatic gzip compression for your datasets, which significantly reduces file size and improves browser performance.

Why Compression Matters

  • Large datasets will cause severe performance issues or fail to load entirely without compression
  • Compressed reports load faster and consume less memory in the browser
  • File sizes can be reduced by 80-90% or more
  • The browser automatically decompresses data on-the-fly using the built-in DecompressionStream API

Using Compression

Report-Level Default

When creating a DL2Report, you can set the default compression behavior:

from dl2_reports import DL2Report

# Enable compression by default (recommended)
report = DL2Report(
    title="My Report",
    compress_visuals=True  # This is the default
)

Per-Dataset Control

Control compression for individual datasets using the compress parameter in add_df():

import pandas as pd
from dl2_reports import DL2Report

report = DL2Report(title="Sales Report")

# Compress large datasets (recommended for most data)
large_df = pd.read_csv("sales_data.csv")
report.add_df("salesData", large_df, compress=True)

# Small datasets can be uncompressed for easier debugging
small_df = pd.DataFrame({"kpi": [100]})
report.add_df("kpiData", small_df, compress=False)

How It Works

When you set compress=True, the Python API automatically:

  1. Serializes your data to JSON
  2. Compresses it using gzip
  3. Encodes it as a Base64 string
  4. Stores it in a separate <script> tag in the HTML
  5. Adds the gc-compressed-data meta tag for automatic memory cleanup

The browser then decompresses the data when the report loads.

Best Practices

  • ✅ Always compress in production - essential for performance and reliability
  • ✅ Compress any dataset with more than a few rows - the overhead is minimal
  • ❌ Only disable compression when:
    • Debugging and you need to inspect the raw JSON in the HTML file
    • Working with extremely small datasets (single-row KPI values) during development

Features

Jupyter Notebook Support

You can render reports directly inside Jupyter Notebooks (including VS Code and JupyterLab).

  • report.show(height=800): Displays the report in an iframe.
  • Automatic Rendering: Simply placing the report object at the end of a cell will render it automatically.

Requirements:

  • IPython must be installed in your environment.

Available Visuals

All visuals are added to a layout row using row.add_<type>(...).

Common Visual Keyword Arguments

All Layout.add_* visual helpers accept **kwargs which are passed through to the viewer as visual properties.

Common properties supported by the viewer include:

  • padding: number (px)
  • margin: number (px)
  • border: bool or CSS border string
  • shadow: bool or CSS box-shadow string
  • flex: number (flex grow)
  • modal_id: string (global modal id opened via the expand icon)

The Python API accepts these in snake_case; the compiled report JSON uses camelCase.

Layout Visual Helper APIs

Below are the current convenience helpers available on Layout (rows are layouts).

Visual Types (Quick Summary)

These are the visual types you can add via the Layout helpers:

  • kpi (via add_kpi)
  • table (via add_table)
  • card (via add_card)
  • pie (via add_pie)
  • clusteredBar / stackedBar (via add_bar(stacked=...))
  • scatter (via add_scatter)
  • line (via add_line)
  • checklist (via add_checklist)
  • histogram (via add_histogram)
  • heatmap (via add_heatmap)
  • boxplot (via add_boxplot)
  • modal (via add_modal_button)

You can also add any viewer-supported visual type directly using add_visual(type=..., ...).

Generic Visual

Use this when you want to pass through viewer props that don't have a dedicated helper yet.

ParameterTypeDefaultDescription
typestr(required)Visual type (e.g., 'kpi', 'table', 'line', 'scatter').
dataset_idstr | NoneNoneDataset id to bind to this visual (required for most chart/data visuals).
**kwargsAnyAdditional visual properties (serialized to JSON). Common ones include padding, margin, border, shadow, flex, modal_id.

KPI

ParameterTypeDefaultDescription
dataset_idstr(required)The dataset id.
value_columnstr | int(required)Column for the main KPI value.
titlestr | NoneNoneOptional KPI card title.
comparison_columnstr | int | NoneNoneColumn for the comparison value.
comparison_row_indexint | NoneNoneRow index to use for comparison (supports negative indices). If not provided, the viewer uses the same row as row_index.
comparison_textstrThe comparison text to show alongside the comparison value. Ex. ("Last Month", "Yesterday", etc.)
row_indexint | NoneNoneRow index to display (supports negative indices).
formatstr | NoneNone'number', 'currency', 'percent', 'date', 'hms'.
`
currency_symbolstr | NoneNoneCurrency symbol (viewer default is usually '$').
good_directionstr | NoneNoneWhich direction is “good” ('higher' or 'lower').
breach_valuefloat | int | NoneNoneValue that triggers a breach indicator.
warning_valuefloat | int | NoneNoneValue that triggers a warning indicator.
descriptionstr | NoneNoneOptional description text.
widthint | NoneNoneOptional width.
heightint | NoneNoneOptional height.
**kwargsAnyAdditional common visual properties (e.g., modal_id, padding/margins, etc.).

Table

ParameterTypeDefaultDescription
dataset_idstr(required)The dataset id.
titlestr | NoneNoneOptional table title.
columnslist[str] | NoneNoneOptional list of columns to display.
page_sizeint | NoneNoneRows per page.
table_stylestr | NoneNone'plain', 'bordered', or 'alternating'.
show_searchbool | NoneNoneWhether to show the search box.
**kwargsAnyAdditional common visual properties.

Card

ParameterTypeDefaultDescription
titlestr | None(required)Optional title (supports template syntax in the viewer).
textstr(required)Main card text (supports template syntax in the viewer).
**kwargsAnyAdditional common visual properties.

Pie / Donut

ParameterTypeDefaultDescription
dataset_idstr(required)The dataset id.
category_columnstr | int(required)Column for slice labels.
value_columnstr | int(required)Column for slice values.
inner_radiusint | NoneNoneInner radius for donut styling.
show_legendbool | NoneNoneWhether to show the legend.
**kwargsAnyAdditional common visual properties.

Bar (Clustered / Stacked)

ParameterTypeDefaultDescription
dataset_idstr(required)The dataset id.
x_columnstr | int(required)Column for X-axis categories.
y_columnslist[str](required)Series columns for Y values.
stackedboolFalseIf True, uses stacked bars; otherwise clustered.
x_axis_labelstr | NoneNoneOptional X-axis label.
y_axis_labelstr | NoneNoneOptional Y-axis label.
show_legendbool | NoneNoneWhether to show the legend.
show_labelsbool | NoneNoneWhether to show value labels.
horizontalbool | NoneNoneWhether to render bars horizontally (viewer-dependent).
**kwargsAnyAdditional common visual properties.

Scatter

ParameterTypeDefaultDescription
dataset_idstr(required)The dataset id.
x_columnstr | int(required)Column for numeric X values.
y_columnstr | int(required)Column for numeric Y values.
category_columnstr | int | NoneNoneOptional column for coloring points by category.
show_trendlinebool | NoneNoneWhether to show a trendline.
show_correlationbool | NoneNoneWhether to show correlation stats.
point_sizeint | NoneNonePoint size.
x_axis_labelstr | NoneNoneOptional X-axis label.
y_axis_labelstr | NoneNoneOptional Y-axis label.
**kwargsAnyAdditional common visual properties.

Line

ParameterTypeDefaultDescription
dataset_idstr(required)The dataset id.
x_columnstr | int(required)Column for X values (time or category).
y_columnslist[str] | str(required)Column(s) for Y series.
smoothbool | NoneNoneWhether to render smooth curves.
show_legendbool | NoneNoneWhether to show the legend.
show_labelsbool | NoneNoneWhether to show value labels.
min_yfloat | int | NoneNoneOptional minimum Y.
max_yfloat | int | NoneNoneOptional maximum Y.
colorslist[str] | NoneNoneOptional list of series colors.
x_axis_labelstr | NoneNoneOptional X-axis label.
y_axis_labelstr | NoneNoneOptional Y-axis label.
**kwargsAnyAdditional common visual properties.

Checklist

ParameterTypeDefaultDescription
dataset_idstr(required)The dataset id.
status_columnstr(required)Column containing a truthy completion value.
warning_columnstr | NoneNoneOptional date column to evaluate for warnings.
warning_thresholdint | NoneNoneDays before due date to trigger warning.
columnslist[str] | NoneNoneOptional subset of columns to display.
page_sizeint | NoneNoneRows per page.
show_searchbool | NoneNoneWhether to show the search box.
**kwargsAnyAdditional common visual properties.

Histogram

ParameterTypeDefaultDescription
dataset_idstr(required)The dataset id.
columnstr | int(required)Numeric column to bin.
binsint | NoneNoneNumber of bins.
colorstr | NoneNoneBar color.
show_labelsbool | NoneNoneWhether to show count labels.
x_axis_labelstr | NoneNoneOptional X-axis label.
y_axis_labelstr | NoneNoneOptional Y-axis label.
**kwargsAnyAdditional common visual properties.

Heatmap

ParameterTypeDefaultDescription
dataset_idstr(required)The dataset id.
x_columnstr | int(required)Column for X categories.
y_columnstr | int(required)Column for Y categories.
value_columnstr | int(required)Column for cell values.
show_cell_labelsbool | NoneNoneWhether to show values inside cells.
min_valuefloat | int | NoneNoneOptional minimum for the color scale.
max_valuefloat | int | NoneNoneOptional maximum for the color scale.
colorstr | list[str] | NoneNoneD3 interpolator name (e.g., 'Viridis') or custom colors.
x_axis_labelstr | NoneNoneOptional X-axis label.
y_axis_labelstr | NoneNoneOptional Y-axis label.
**kwargsAnyAdditional common visual properties.

Boxplot

Supports two modes:

  • Data mode: provide data_column (and optional category_column)
  • Pre-calculated mode: provide min_column, q1_column, median_column, q3_column, max_column (and optional mean_column)
ParameterTypeDefaultDescription
dataset_idstr(required)The dataset id.
data_columnstr | int | NoneNoneRaw values column (data mode).
category_columnstr | int | NoneNoneGrouping/label column.
min_columnstr | int | NoneNonePre-calculated minimum column.
q1_columnstr | int | NoneNonePre-calculated Q1 column.
median_columnstr | int | NoneNonePre-calculated median column.
q3_columnstr | int | NoneNonePre-calculated Q3 column.
max_columnstr | int | NoneNonePre-calculated maximum column.
mean_columnstr | int | NoneNonePre-calculated mean column (optional).
directionstr | NoneNone'vertical' or 'horizontal'.
show_outliersbool | NoneNoneWhether to show outliers.
colorstr | list[str] | NoneNoneFill color or scheme.
x_axis_labelstr | NoneNoneOptional X-axis label.
y_axis_labelstr | NoneNoneOptional Y-axis label.
**kwargsAnyAdditional common visual properties.

Modal Button

ParameterTypeDefaultDescription
modal_idstr(required)The global modal id to open.
button_labelstr(required)Button label text.
**kwargsAnyAdditional common visual properties.

Note: Most visuals also support modal_id as a keyword argument to enable an "expand" icon that opens a modal on click.

Modals

Create detailed overlays that can be triggered from any element.

# Define a modal
modal = report.add_modal("details", "Detailed View")
modal.add_row().add_table("my_data")

# Trigger from a visual
page.add_row().add_kpi("my_data", "A", "Metric", modal_id="details")

# Or add a dedicated button
page.add_row().add_modal_button("details", "Open Details")

Visual Elements (Annotations)

Add trend lines, markers, and custom axes to your charts.

Trend Lines

You can add a trend line using the .add_trend() method. It can automatically calculate linear or polynomial regression if you don't provide coefficients.

chart = page.add_row().add_scatter("my_data", "A", "B")

# Auto-calculate linear trend (degree 1)
chart.add_trend(color="red")

# Auto-calculate polynomial trend (e.g., degree 2)
chart.add_trend(coefficients=2, color="blue", line_style="dashed")

# Manually provide coefficients [intercept, slope, ...]
chart.add_trend(coefficients=[0, 1.5], color="green")

Other Elements

Use .add_element(type, **kwargs) for other annotations.

Element TypeDescriptionKey Arguments
xAxisVertical line at a specific X value.value, color, label, line_style
yAxisHorizontal line at a specific Y value.value, color, label, line_style
markerA point marker at a specific value.value, size, shape (circle, square, triangle), color
labelA text label at a specific value.value, label, font_size, font_weight
chart.add_element("yAxis", value=100, label="Target", color="green")

Tree Traversal

All components (Pages, Rows, Layouts, Visuals) are part of a tree. You can access the root report from any component using .get_report().

visual = layout.add_visual("line", "my_data")
report = visual.get_report()
print(report.title)

Datalys2 Documentation

For detailed information on available visuals and configuration, see DOCUMENTATION.md.

Or see the github repo at https://github.com/kameronbrooks/datalys2-reporting