or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

3d-charts.mdbasic-charts.mdcomposite-charts.mdgeographic-charts.mdindex.mdoptions.mdrendering.mdutilities.md

rendering.mddocs/

0

# Rendering and Output

1

2

Chart rendering capabilities supporting multiple output formats and integration environments. pyecharts provides flexible rendering options for HTML files, static images, Jupyter notebooks, and web framework integration.

3

4

## Capabilities

5

6

### Chart Rendering Methods

7

8

Core rendering methods available on all chart instances.

9

10

```python { .api }

11

class ChartRenderMethods:

12

def render(self, path="render.html"):

13

"""

14

Render chart to HTML file.

15

16

Args:

17

path (str): Output file path

18

19

Returns:

20

str: Generated HTML content

21

"""

22

23

def render_embed(self):

24

"""

25

Render chart as embeddable HTML fragment.

26

27

Returns:

28

str: HTML fragment without full page structure

29

"""

30

31

def render_notebook(self):

32

"""

33

Render chart for Jupyter notebook display.

34

35

Returns:

36

HTML: Jupyter notebook HTML display object

37

"""

38

39

def dump_options(self):

40

"""

41

Export chart configuration as JSON.

42

43

Returns:

44

str: JSON string of chart options

45

"""

46

47

def dump_options_with_quotes(self):

48

"""

49

Export chart configuration as JSON with quoted keys.

50

51

Returns:

52

str: JSON string with quoted keys

53

"""

54

55

def get_js_dependencies(self):

56

"""

57

Get JavaScript dependencies for the chart.

58

59

Returns:

60

list: List of required JavaScript files

61

"""

62

```

63

64

### Static Image Generation

65

66

Generate static images from interactive charts using browser automation.

67

68

```python { .api }

69

def make_snapshot(driver, file_content, output_name, delay=1, pixel_ratio=1, is_remove_html=False, **kwargs):

70

"""

71

Generate static image snapshot of chart.

72

73

Args:

74

driver: Browser driver instance (selenium, pyppeteer, phantomjs)

75

file_content (str): HTML content or file path

76

output_name (str): Output image file path

77

delay (int): Delay before screenshot in seconds

78

pixel_ratio (int): Device pixel ratio for high-DPI displays

79

is_remove_html (bool): Remove temporary HTML file after generation

80

**kwargs: Additional driver-specific options

81

82

Returns:

83

str: Output file path

84

"""

85

```

86

87

**Supported Image Formats:**

88

- PNG (default)

89

- JPEG/JPG

90

- PDF (driver-dependent)

91

- SVG (driver-dependent)

92

93

**Usage Example:**

94

```python

95

from pyecharts.charts import Bar

96

from pyecharts.render import make_snapshot

97

from snapshot_selenium import snapshot as driver

98

99

# Create chart

100

bar = Bar().add_xaxis(["A", "B", "C"]).add_yaxis("Series", [1, 2, 3])

101

102

# Generate image

103

make_snapshot(driver, bar.render(), "chart.png")

104

```

105

106

### Browser Driver Options

107

108

Different browser automation drivers for image generation.

109

110

#### Selenium Driver

111

```python

112

# Install: pip install snapshot-selenium

113

from snapshot_selenium import snapshot as selenium_driver

114

115

make_snapshot(selenium_driver, chart.render(), "output.png", delay=2)

116

```

117

118

#### PyPPeteer Driver

119

```python

120

# Install: pip install snapshot-pyppeteer

121

from snapshot_pyppeteer import snapshot as pyppeteer_driver

122

123

make_snapshot(pyppeteer_driver, chart.render(), "output.png")

124

```

125

126

#### PhantomJS Driver

127

```python

128

# Install: pip install snapshot-phantomjs

129

from snapshot_phantomjs import snapshot as phantomjs_driver

130

131

make_snapshot(phantomjs_driver, chart.render(), "output.png")

132

```

133

134

### Jupyter Notebook Integration

135

136

Seamless integration with Jupyter environments for interactive development.

137

138

```python { .api }

139

class JupyterIntegration:

140

def render_notebook(self):

141

"""

142

Display chart in Jupyter notebook cell output.

143

144

Returns:

145

HTML: IPython HTML display object

146

"""

147

148

def load_javascript(self):

149

"""

150

Load required JavaScript libraries in notebook.

151

152

Note: Usually handled automatically

153

"""

154

```

155

156

**Jupyter Usage Patterns:**

157

```python

158

# Basic notebook display

159

from pyecharts.charts import Bar

160

161

bar = Bar().add_xaxis(["A", "B", "C"]).add_yaxis("Series", [1, 2, 3])

162

bar.render_notebook() # Displays chart inline

163

164

# JupyterLab support

165

# Charts display natively in JupyterLab cells

166

167

# Notebook theming

168

from pyecharts import options as opts

169

170

bar = Bar(init_opts=opts.InitOpts(theme="dark"))

171

# Theme automatically adapts to notebook environment

172

```

173

174

### Web Framework Integration

175

176

Integration helpers for popular Python web frameworks.

177

178

#### Flask Integration

179

```python

180

from flask import Flask, render_template

181

from pyecharts.charts import Bar

182

from pyecharts import options as opts

183

from pyecharts.globals import CurrentConfig

184

185

app = Flask(__name__)

186

187

# Configure pyecharts for Flask

188

CurrentConfig.GLOBAL_ENV = Environment(loader=FileSystemLoader("./templates"))

189

190

@app.route("/")

191

def index():

192

bar = (

193

Bar()

194

.add_xaxis(["A", "B", "C", "D"])

195

.add_yaxis("Series", [1, 2, 3, 4])

196

.set_global_opts(title_opts=opts.TitleOpts(title="Flask Chart"))

197

)

198

return render_template("index.html", chart=bar.render_embed())

199

```

200

201

#### Django Integration

202

```python

203

from django.shortcuts import render

204

from pyecharts.charts import Line

205

206

def chart_view(request):

207

line = (

208

Line()

209

.add_xaxis(["Jan", "Feb", "Mar", "Apr"])

210

.add_yaxis("Revenue", [100, 200, 150, 300])

211

)

212

213

context = {"chart": line.render_embed()}

214

return render(request, "chart.html", context)

215

```

216

217

#### Sanic Integration

218

```python

219

from sanic import Sanic, response

220

from pyecharts.charts import Pie

221

222

app = Sanic("ChartApp")

223

224

@app.route("/chart")

225

async def chart_handler(request):

226

pie = (

227

Pie()

228

.add("", [("A", 25), ("B", 35), ("C", 40)])

229

)

230

231

html_content = f"""

232

<!DOCTYPE html>

233

<html>

234

<head><title>Chart</title></head>

235

<body>{pie.render_embed()}</body>

236

</html>

237

"""

238

return response.html(html_content)

239

```

240

241

### Asset Management

242

243

JavaScript asset handling and CDN configuration.

244

245

```python { .api }

246

# Global configuration options

247

class CurrentConfig:

248

ONLINE_HOST = "https://assets.pyecharts.org/assets/" # CDN host

249

NOTEBOOK_TYPE = "jupyter_notebook" # Notebook type

250

251

# Asset management functions

252

def configure_assets(host=None, **kwargs):

253

"""

254

Configure asset loading settings.

255

256

Args:

257

host (str): Custom asset host URL

258

**kwargs: Additional configuration options

259

"""

260

261

def get_js_dependencies():

262

"""

263

Get list of JavaScript dependencies.

264

265

Returns:

266

list: Required JavaScript files

267

"""

268

```

269

270

**Custom Asset Configuration:**

271

```python

272

from pyecharts.globals import CurrentConfig

273

274

# Use local assets

275

CurrentConfig.ONLINE_HOST = "http://localhost:8000/assets/"

276

277

# Use custom CDN

278

CurrentConfig.ONLINE_HOST = "https://cdn.jsdelivr.net/npm/echarts@5/dist/"

279

```

280

281

### Template System

282

283

Template-based rendering for custom HTML output.

284

285

```python { .api }

286

class TemplateEngine:

287

def render_chart_to_file(self, chart, template_name, output_path, **context):

288

"""

289

Render chart using custom template.

290

291

Args:

292

chart: Chart instance

293

template_name (str): Template file name

294

output_path (str): Output file path

295

**context: Additional template context variables

296

"""

297

298

def render_charts_to_file(self, charts, template_name, output_path, **context):

299

"""

300

Render multiple charts using custom template.

301

302

Args:

303

charts (list): List of chart instances

304

template_name (str): Template file name

305

output_path (str): Output file path

306

**context: Additional template context variables

307

"""

308

```

309

310

**Custom Template Example:**

311

```html

312

<!-- templates/custom_chart.html -->

313

<!DOCTYPE html>

314

<html>

315

<head>

316

<title>{{ title }}</title>

317

<script src="https://cdn.jsdelivr.net/npm/echarts@5/dist/echarts.min.js"></script>

318

</head>

319

<body>

320

<h1>{{ title }}</h1>

321

<div id="chart" style="width: 100%; height: 400px;"></div>

322

{{ chart_script }}

323

</body>

324

</html>

325

```

326

327

### Performance Optimization

328

329

Rendering optimization techniques for better performance.

330

331

#### Lazy Loading

332

```python

333

# Enable lazy loading for large datasets

334

from pyecharts import options as opts

335

336

bar = (

337

Bar(init_opts=opts.InitOpts(renderer="canvas")) # Use canvas for better performance

338

.add_xaxis(large_dataset_x)

339

.add_yaxis("Series", large_dataset_y, is_large=True, large_threshold=1000)

340

)

341

```

342

343

#### Progressive Enhancement

344

```python

345

# Progressive rendering for large datasets

346

bar = (

347

Bar()

348

.add_xaxis(data_x)

349

.add_yaxis("Series", data_y, progressive=5000, progressive_threshold=10000)

350

)

351

```

352

353

#### Memory Management

354

```python

355

# Optimize memory usage for batch rendering

356

charts = []

357

for data_chunk in large_dataset_chunks:

358

chart = create_chart(data_chunk)

359

charts.append(chart.render_embed())

360

del chart # Free memory

361

362

# Combine rendered charts

363

final_html = combine_charts(charts)

364

```

365

366

### Output Formats

367

368

Supported output formats and their characteristics.

369

370

#### HTML Output

371

- **Interactive**: Full interactivity with tooltips, zoom, pan

372

- **Responsive**: Adapts to container size

373

- **JavaScript Required**: Requires JavaScript execution

374

- **File Size**: Larger due to JavaScript libraries

375

376

#### Image Output

377

- **Static**: No interactivity

378

- **Portable**: Works without JavaScript

379

- **Print-Ready**: Suitable for reports and publications

380

- **File Size**: Smaller, faster loading

381

382

#### SVG Output

383

- **Vector**: Scalable without quality loss

384

- **Editable**: Can be modified in vector graphics software

385

- **Text-Searchable**: Text remains selectable

386

- **Browser Support**: Excellent modern browser support

387

388

#### PDF Output

389

- **Print-Ready**: Optimized for printing

390

- **Professional**: Suitable for business reports

391

- **Archival**: Long-term document preservation

392

- **Driver-Dependent**: Requires compatible browser driver

393

394

### Error Handling

395

396

Common rendering issues and solutions.

397

398

```python

399

# Handle rendering errors gracefully

400

try:

401

chart.render("output.html")

402

except Exception as e:

403

print(f"Rendering error: {e}")

404

# Fallback to embedded rendering

405

html_content = chart.render_embed()

406

with open("output.html", "w", encoding="utf-8") as f:

407

f.write(f"<html><body>{html_content}</body></html>")

408

409

# Validate chart before rendering

410

def validate_chart(chart):

411

"""Check if chart has required data and options."""

412

if not chart.options.get("series"):

413

raise ValueError("Chart has no data series")

414

return True

415

416

# Memory-safe batch rendering

417

def render_charts_safely(charts, output_dir):

418

"""Render multiple charts with memory management."""

419

for i, chart in enumerate(charts):

420

try:

421

chart.render(f"{output_dir}/chart_{i}.html")

422

except Exception as e:

423

print(f"Failed to render chart {i}: {e}")

424

finally:

425

del chart # Free memory

426

```