Using d3blocks to Create Interactive D3.js Visualizations in Python
The article introduces d3blocks, a Python library that extends D3.js's interactive visualization capabilities to Python, demonstrating how to create interactive scatter, network, Sankey, and image slider charts with just a few lines of code and offering examples with code snippets and GIF illustrations.
d3blocks is a Python package that brings the powerful, interactive visualisation features of D3.js into the Python ecosystem, allowing users to generate rich, web‑based charts with minimal code.
One example shows how to combine a PCA scatter plot with a t‑SNE layout using the d3.scatter() function. The code imports the library, loads an example dataset, randomly generates point sizes and opacities, and then calls d3.scatter() with PCA and t‑SNE coordinates, colour, tooltip, and styling options, outputting an interactive HTML file.
# 导入d3blocks
from d3blocks import D3Blocks
import numpy as np
# 初始化
d3 = D3Blocks()
# 数据准备
df = d3.import_example('mnist')
size = np.random.randint(0, 8, df.shape[0])
opacity = np.random.randint(0, 8, df.shape[0]) / 10
tooltip = df['y'].values.astype(str)
# 绘图
d3.scatter(
df['PC1'].values, # PCA图主成分PC1 x轴数据
df['PC2'].values, # PCA图主成分PC2 y轴数据
x1=df['tsne_1'].values, # tSNE图x轴数据
y1=df['tsne_2'].values, # tSNE图y轴数据
color=df['y'].values.astype(str),
tooltip=tooltip, # 设置点的值
size=size,
opacity=opacity, # 设置点透明度
stroke='#000000',
cmap='tab20', # 设置Colormap
scale=True,
label_radio=['PCA', 'tSNE'],
figsize=[1024, 768],
filepath='scatter_demo.html', #设置结果名称,结果为网页html格式
)Another case demonstrates a network graph using d3.d3graph() , followed by a Sankey diagram created with d3.sankey() . The Sankey example loads an "energy" dataset and customises node alignment, width, padding, colours, link opacity, margins, and output file.
from d3blocks import D3Blocks
d3 = D3Blocks()
df = d3.import_example('energy')
d3.sankey(df,
title='Sankey - d3blocks',
filepath='sankey.html',
figsize=(800, 600),
node={"align": "justify", "width": 15, "padding": 15, "color": "currentColor"},
link={"color": "source-target", "stroke_opacity": 0.5},
margin={"top": 5, "right": 1, "bottom": 5, "left": 1},
showfig=True,
overwrite=True)The article also showcases an image‑slider visualisation for comparing experimental results, and mentions additional chart types such as time‑series, heatmaps, and moving bubbles, all accessible through consistent function calls. A link to the GitHub repository is provided for further exploration.
IT Services Circle
Delivering cutting-edge internet insights and practical learning resources. We're a passionate and principled IT media platform.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.