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

utilities.mddocs/

0

# Utilities and Extensions

1

2

Helper utilities for JavaScript code injection, geographic data management, custom chart extensions, and advanced functionality. These tools enable customization beyond the standard API and integration with external data sources.

3

4

## Capabilities

5

6

### JavaScript Code Integration

7

8

Inject custom JavaScript code into charts for advanced functionality and customization.

9

10

```python { .api }

11

class JsCode:

12

def __init__(self, js_code):

13

"""

14

JavaScript code wrapper for custom functionality.

15

16

Args:

17

js_code (str): JavaScript code string

18

"""

19

20

def replace(self, pattern, repl):

21

"""

22

Replace patterns in JavaScript code using regex.

23

24

Args:

25

pattern (str): Regular expression pattern

26

repl (str): Replacement string

27

28

Returns:

29

JsCode: Self for method chaining

30

"""

31

```

32

33

**Usage Examples:**

34

```python

35

from pyecharts.commons.utils import JsCode

36

from pyecharts.charts import Bar

37

from pyecharts import options as opts

38

39

# Custom formatter function

40

custom_formatter = JsCode("""

41

function(params) {

42

return params.name + ': ' + params.value + '%';

43

}

44

""")

45

46

# Custom tooltip formatter

47

tooltip_formatter = JsCode("""

48

function(params) {

49

var result = params[0].name + '<br/>';

50

params.forEach(function(item) {

51

result += item.marker + item.seriesName + ': ' + item.value + '<br/>';

52

});

53

return result;

54

}

55

""")

56

57

# Apply to chart

58

bar = (

59

Bar()

60

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

61

.add_yaxis("Series", [10, 20, 30])

62

.set_global_opts(

63

tooltip_opts=opts.TooltipOpts(formatter=tooltip_formatter),

64

yaxis_opts=opts.AxisOpts(axislabel_opts=opts.LabelOpts(formatter=custom_formatter))

65

)

66

)

67

68

# Custom color function

69

color_function = JsCode("""

70

function(params) {

71

var colors = ['#FF6B6B', '#4ECDC4', '#45B7D1', '#96CEB4', '#FECA57'];

72

return colors[params.dataIndex % colors.length];

73

}

74

""")

75

76

# Apply dynamic coloring

77

bar.set_series_opts(itemstyle_opts=opts.ItemStyleOpts(color=color_function))

78

```

79

80

### Data Structures

81

82

Specialized data structures for chart data management.

83

84

```python { .api }

85

class OrderedSet:

86

def __init__(self, *args):

87

"""

88

Ordered set data structure preserving insertion order.

89

90

Args:

91

*args: Initial items to add

92

"""

93

94

def add(self, *items):

95

"""

96

Add items to the ordered set.

97

98

Args:

99

*items: Items to add (duplicates ignored)

100

"""

101

```

102

103

**Usage Example:**

104

```python

105

from pyecharts.commons.utils import OrderedSet

106

107

# Create ordered set for category management

108

categories = OrderedSet("Q1", "Q2", "Q3", "Q4")

109

categories.add("Q1", "Q5") # Q1 already exists, only Q5 added

110

print(categories.items) # ["Q1", "Q2", "Q3", "Q4", "Q5"]

111

```

112

113

### Geographic Data Management

114

115

Built-in geographic data and custom registration functions.

116

117

```python { .api }

118

# Geographic data dictionaries (from pyecharts.datasets)

119

FILENAMES # FuzzyDict: Map filename mappings

120

COORDINATES # FuzzyDict: City coordinate mappings

121

EXTRA # dict: Additional geographic data registry

122

123

def register_url(asset_url):

124

"""

125

Register external map asset URLs.

126

127

Args:

128

asset_url (str): Base URL for map assets

129

130

Raises:

131

Exception: If URL is invalid or registry cannot be loaded

132

"""

133

134

def register_files(asset_files):

135

"""

136

Register custom map files.

137

138

Args:

139

asset_files (dict): Mapping of region names to filenames

140

"""

141

142

def register_coords(coords):

143

"""

144

Register custom coordinates.

145

146

Args:

147

coords (dict): Mapping of location names to [longitude, latitude] pairs

148

"""

149

```

150

151

**Usage Examples:**

152

```python

153

from pyecharts.datasets import register_coords, register_files, COORDINATES, FILENAMES

154

155

# Register custom coordinates

156

custom_locations = {

157

"Custom City": [116.46, 39.92],

158

"Another Place": [121.48, 31.22],

159

"Special Zone": [113.23, 23.16]

160

}

161

register_coords(custom_locations)

162

163

# Register custom map files

164

custom_maps = {

165

"custom_region": "path/to/custom_map.js",

166

"special_area": "path/to/special_area.json"

167

}

168

register_files(custom_maps)

169

170

# Register external map assets

171

register_url("https://cdn.example.com/maps/")

172

173

# Access built-in data with fuzzy matching

174

print(COORDINATES["Beijing"]) # Returns coordinates for Beijing

175

print(FILENAMES["china"]) # Returns filename for China map

176

177

# Fuzzy matching for typos

178

print(COORDINATES["Biejing"]) # Still finds Beijing coordinates

179

print(FILENAMES["cina"]) # Still finds China map

180

```

181

182

### Fuzzy Dictionary

183

184

Dictionary with fuzzy string matching capabilities for geographic data.

185

186

```python { .api }

187

class FuzzyDict(dict):

188

def __init__(self, cutoff=0.6):

189

"""

190

Dictionary that performs fuzzy lookup for keys.

191

192

Args:

193

cutoff (float): Match ratio threshold (0-1)

194

"""

195

196

def __contains__(self, item):

197

"""Check if item exists with fuzzy matching."""

198

199

def __getitem__(self, lookfor):

200

"""Get item with fuzzy key matching."""

201

```

202

203

**Usage Example:**

204

```python

205

from pyecharts.datasets import FuzzyDict

206

207

# Create fuzzy dictionary

208

city_data = FuzzyDict(cutoff=0.7)

209

city_data.update({

210

"Beijing": [116.46, 39.92],

211

"Shanghai": [121.48, 31.22],

212

"Guangzhou": [113.23, 23.16]

213

})

214

215

# Fuzzy lookups work with typos

216

print(city_data["Biejing"]) # Finds Beijing

217

print(city_data["Shangai"]) # Finds Shanghai

218

print(city_data["Guangzou"]) # Finds Guangzhou

219

220

# Check membership with fuzzy matching

221

print("Bejing" in city_data) # True (fuzzy match)

222

```

223

224

### Asset Management Utilities

225

226

JavaScript dependency and asset management functions.

227

228

```python { .api }

229

def produce_require_dict(js_dependencies, js_host):

230

"""

231

Generate require.js configuration for JavaScript dependencies.

232

233

Args:

234

js_dependencies (list): List of JavaScript file dependencies

235

js_host (str): Host URL for JavaScript files

236

237

Returns:

238

dict: require.js configuration dictionary

239

"""

240

```

241

242

**Usage Example:**

243

```python

244

from pyecharts.commons.utils import produce_require_dict

245

246

# Generate require.js config

247

dependencies = ["echarts", "echarts-gl", "echarts-wordcloud"]

248

host = "https://cdn.jsdelivr.net/npm/"

249

250

config = produce_require_dict(dependencies, host)

251

print(config)

252

# Returns require.js paths configuration

253

```

254

255

### Custom Chart Extensions

256

257

Create custom chart types and extend existing functionality.

258

259

```python

260

# Example: Custom gauge chart with additional features

261

from pyecharts.charts import Gauge

262

from pyecharts import options as opts

263

from pyecharts.commons.utils import JsCode

264

265

class AdvancedGauge(Gauge):

266

def __init__(self, **kwargs):

267

super().__init__(**kwargs)

268

269

def add_multi_pointer(self, data_pairs, **kwargs):

270

"""Add multiple pointers to gauge chart."""

271

# Custom implementation

272

return self.add("", data_pairs, **kwargs)

273

274

def set_gradient_colors(self, colors):

275

"""Apply gradient colors to gauge."""

276

gradient_js = JsCode(f"""

277

new echarts.graphic.LinearGradient(0, 0, 0, 1, {colors})

278

""")

279

return self.set_series_opts(

280

itemstyle_opts=opts.ItemStyleOpts(color=gradient_js)

281

)

282

283

# Usage

284

gauge = (

285

AdvancedGauge()

286

.add_multi_pointer([("CPU", 75), ("Memory", 60)])

287

.set_gradient_colors([

288

{"offset": 0, "color": "#00ff00"},

289

{"offset": 0.5, "color": "#ffff00"},

290

{"offset": 1, "color": "#ff0000"}

291

])

292

)

293

```

294

295

### Data Processing Utilities

296

297

Helper functions for data preparation and transformation.

298

299

```python

300

# Example utility functions (implementation would be in user code)

301

def prepare_time_series(data, date_column, value_column):

302

"""

303

Prepare time series data for line charts.

304

305

Args:

306

data (DataFrame): Input data

307

date_column (str): Date column name

308

value_column (str): Value column name

309

310

Returns:

311

tuple: (dates, values) formatted for pyecharts

312

"""

313

dates = data[date_column].dt.strftime('%Y-%m-%d').tolist()

314

values = data[value_column].tolist()

315

return dates, values

316

317

def aggregate_categorical_data(data, category_column, value_column, agg_func='sum'):

318

"""

319

Aggregate categorical data for bar/pie charts.

320

321

Args:

322

data (DataFrame): Input data

323

category_column (str): Category column name

324

value_column (str): Value column name

325

agg_func (str): Aggregation function

326

327

Returns:

328

tuple: (categories, values) formatted for pyecharts

329

"""

330

grouped = data.groupby(category_column)[value_column].agg(agg_func)

331

return grouped.index.tolist(), grouped.values.tolist()

332

333

def create_heatmap_data(data, x_column, y_column, value_column):

334

"""

335

Create heatmap data from tabular format.

336

337

Args:

338

data (DataFrame): Input data

339

x_column (str): X-axis column name

340

y_column (str): Y-axis column name

341

value_column (str): Value column name

342

343

Returns:

344

list: Heatmap data in [x_index, y_index, value] format

345

"""

346

x_categories = sorted(data[x_column].unique())

347

y_categories = sorted(data[y_column].unique())

348

349

heatmap_data = []

350

for _, row in data.iterrows():

351

x_idx = x_categories.index(row[x_column])

352

y_idx = y_categories.index(row[y_column])

353

heatmap_data.append([x_idx, y_idx, row[value_column]])

354

355

return heatmap_data, x_categories, y_categories

356

```

357

358

### Theme and Styling Utilities

359

360

Custom theme creation and advanced styling functions.

361

362

```python

363

# Example: Custom theme creation

364

def create_custom_theme(primary_color="#1f77b4", background_color="#ffffff"):

365

"""

366

Create custom color theme for charts.

367

368

Args:

369

primary_color (str): Primary color hex code

370

background_color (str): Background color hex code

371

372

Returns:

373

dict: Custom theme configuration

374

"""

375

return {

376

"color": [primary_color, "#ff7f0e", "#2ca02c", "#d62728", "#9467bd"],

377

"backgroundColor": background_color,

378

"textStyle": {"color": "#333333"},

379

"title": {"textStyle": {"color": "#333333"}},

380

"line": {"itemStyle": {"borderWidth": 2}},

381

"pie": {"itemStyle": {"borderWidth": 1, "borderColor": "#ffffff"}},

382

"bar": {"itemStyle": {"barBorderWidth": 0.5, "barBorderColor": "#ffffff"}}

383

}

384

385

# Apply custom theme

386

from pyecharts.charts import Bar

387

from pyecharts import options as opts

388

389

custom_theme = create_custom_theme("#e74c3c", "#f8f9fa")

390

bar = Bar(init_opts=opts.InitOpts(theme=custom_theme))

391

```

392

393

### Integration Helpers

394

395

Utilities for integrating with external libraries and data sources.

396

397

```python

398

# Example: Pandas integration helpers

399

def from_pandas_dataframe(df, x_column, y_columns, chart_type="bar"):

400

"""

401

Create chart directly from pandas DataFrame.

402

403

Args:

404

df (DataFrame): Source data

405

x_column (str): X-axis column name

406

y_columns (list): Y-axis column names

407

chart_type (str): Chart type to create

408

409

Returns:

410

Chart: Configured chart instance

411

"""

412

from pyecharts.charts import Bar, Line, Scatter

413

414

chart_classes = {

415

"bar": Bar,

416

"line": Line,

417

"scatter": Scatter

418

}

419

420

chart = chart_classes[chart_type]()

421

chart.add_xaxis(df[x_column].tolist())

422

423

for column in y_columns:

424

chart.add_yaxis(column, df[column].tolist())

425

426

return chart

427

428

# NumPy integration

429

def from_numpy_arrays(x_data, y_data, chart_type="line"):

430

"""

431

Create chart from NumPy arrays.

432

433

Args:

434

x_data (ndarray): X-axis data

435

y_data (ndarray): Y-axis data

436

chart_type (str): Chart type to create

437

438

Returns:

439

Chart: Configured chart instance

440

"""

441

from pyecharts.charts import Line, Scatter

442

443

chart_classes = {"line": Line, "scatter": Scatter}

444

chart = chart_classes[chart_type]()

445

446

chart.add_xaxis(x_data.tolist())

447

chart.add_yaxis("Series", y_data.tolist())

448

449

return chart

450

```

451

452

### Debug and Development Utilities

453

454

Tools for debugging charts and development workflow.

455

456

```python

457

# Example development utilities

458

def debug_chart_options(chart):

459

"""

460

Print chart configuration for debugging.

461

462

Args:

463

chart: Chart instance to debug

464

"""

465

import json

466

options = chart.dump_options()

467

print(json.dumps(json.loads(options), indent=2))

468

469

def validate_chart_data(chart):

470

"""

471

Validate chart has proper data structure.

472

473

Args:

474

chart: Chart instance to validate

475

476

Returns:

477

list: List of validation errors

478

"""

479

errors = []

480

options = json.loads(chart.dump_options())

481

482

if not options.get("series"):

483

errors.append("Chart has no data series")

484

485

for i, series in enumerate(options.get("series", [])):

486

if not series.get("data"):

487

errors.append(f"Series {i} has no data")

488

489

return errors

490

491

def chart_performance_profile(chart, output_path="profile.html"):

492

"""

493

Generate performance profile for chart rendering.

494

495

Args:

496

chart: Chart instance to profile

497

output_path (str): Output file path

498

"""

499

import time

500

501

start_time = time.time()

502

html_content = chart.render_embed()

503

render_time = time.time() - start_time

504

505

data_size = len(json.loads(chart.dump_options()).get("series", []))

506

507

profile_info = f"""

508

Render Time: {render_time:.3f}s

509

Data Series: {data_size}

510

HTML Size: {len(html_content)} characters

511

"""

512

513

print(profile_info)

514

return profile_info

515

```