notecharts 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- notecharts/__init__.py +5 -0
- notecharts/charts.py +841 -0
- notecharts/widget.py +283 -0
- notecharts-0.1.0.dist-info/METADATA +108 -0
- notecharts-0.1.0.dist-info/RECORD +9 -0
- notecharts-0.1.0.dist-info/WHEEL +5 -0
- notecharts-0.1.0.dist-info/licenses/LICENSE +21 -0
- notecharts-0.1.0.dist-info/licenses/NOTICE +8 -0
- notecharts-0.1.0.dist-info/top_level.txt +1 -0
notecharts/__init__.py
ADDED
notecharts/charts.py
ADDED
|
@@ -0,0 +1,841 @@
|
|
|
1
|
+
import random
|
|
2
|
+
import colorsys
|
|
3
|
+
from .widget import Chart, JSCode
|
|
4
|
+
|
|
5
|
+
def _format_data(data):
|
|
6
|
+
"""Formats the input data for ECharts.
|
|
7
|
+
|
|
8
|
+
Args:
|
|
9
|
+
data (list-of-lists, list-of-dicts, or DataFrame): The input data.
|
|
10
|
+
|
|
11
|
+
Returns:
|
|
12
|
+
list: The formatted data.
|
|
13
|
+
"""
|
|
14
|
+
if hasattr(data, "to_dict") and hasattr(data, "columns"):
|
|
15
|
+
return data.to_dict(orient="records")
|
|
16
|
+
return data
|
|
17
|
+
|
|
18
|
+
def _deep_update(d, u):
|
|
19
|
+
"""Recursively updates a dictionary.
|
|
20
|
+
|
|
21
|
+
Args:
|
|
22
|
+
d (dict): The dictionary to update.
|
|
23
|
+
u (dict): The update dictionary.
|
|
24
|
+
"""
|
|
25
|
+
for k, v in u.items():
|
|
26
|
+
if isinstance(v, dict) and k in d and isinstance(d[k], dict):
|
|
27
|
+
_deep_update(d[k], v)
|
|
28
|
+
else:
|
|
29
|
+
d[k] = v
|
|
30
|
+
|
|
31
|
+
def _get_harmony_hues(base_hue, harmony):
|
|
32
|
+
"""Returns a list of hue angles for the given harmony scheme.
|
|
33
|
+
|
|
34
|
+
Args:
|
|
35
|
+
base_hue (float): Base hue angle (0-360).
|
|
36
|
+
harmony (str): Harmony scheme Name. One of 'monochromatic', 'complementary',
|
|
37
|
+
'triadic', 'tetradic', 'split-complementary', or 'analogous'.
|
|
38
|
+
|
|
39
|
+
Returns:
|
|
40
|
+
list[float]: List of hue angles.
|
|
41
|
+
"""
|
|
42
|
+
base = base_hue % 360
|
|
43
|
+
if harmony == "monochromatic":
|
|
44
|
+
return [base]
|
|
45
|
+
elif harmony == "complementary":
|
|
46
|
+
return [base, (base + 180) % 360]
|
|
47
|
+
elif harmony == "triadic":
|
|
48
|
+
return [base, (base + 120) % 360, (base + 240) % 360]
|
|
49
|
+
elif harmony == "tetradic":
|
|
50
|
+
return [base, (base + 90) % 360, (base + 180) % 360, (base + 270) % 360]
|
|
51
|
+
elif harmony == "split-complementary":
|
|
52
|
+
return [base, (base + 150) % 360, (base + 210) % 360]
|
|
53
|
+
elif harmony == "analogous":
|
|
54
|
+
return [(base - 30) % 360, base, (base + 30) % 360]
|
|
55
|
+
else:
|
|
56
|
+
return [base]
|
|
57
|
+
|
|
58
|
+
def _hsv_palette(n_colors, color_theme="pastel", base_hue=None, chart_theme="light", harmony="auto"):
|
|
59
|
+
"""Generates a cohesive HEX color palette based on HSV values and harmonies.
|
|
60
|
+
|
|
61
|
+
Args:
|
|
62
|
+
n_colors (int): Number of colors to generate.
|
|
63
|
+
color_theme (str, optional): Preset saturation/value ('pastel', 'neon', 'professional').
|
|
64
|
+
Defaults to "pastel".
|
|
65
|
+
base_hue (float, optional): Seed hue (0-360). Defaults to None.
|
|
66
|
+
chart_theme (str, optional): 'light' or 'dark' background context. Defaults to "light".
|
|
67
|
+
harmony (str, optional): Color harmony scheme or 'auto'. Defaults to "auto".
|
|
68
|
+
|
|
69
|
+
Returns:
|
|
70
|
+
list[str]: List of HEX color strings.
|
|
71
|
+
|
|
72
|
+
Raises:
|
|
73
|
+
ValueError: If color_theme is unknown.
|
|
74
|
+
"""
|
|
75
|
+
if n_colors <= 0:
|
|
76
|
+
return []
|
|
77
|
+
|
|
78
|
+
if chart_theme == "dark":
|
|
79
|
+
presets = {
|
|
80
|
+
"pastel": (0.25, 0.90),
|
|
81
|
+
"neon": (0.80, 0.95),
|
|
82
|
+
"professional": (0.45, 0.80),
|
|
83
|
+
}
|
|
84
|
+
else:
|
|
85
|
+
presets = {
|
|
86
|
+
"pastel": (0.40, 0.80),
|
|
87
|
+
"neon": (0.75, 1.00),
|
|
88
|
+
"professional": (0.50, 0.75),
|
|
89
|
+
}
|
|
90
|
+
if color_theme not in presets:
|
|
91
|
+
raise ValueError(f"Unknown color_theme '{color_theme}'. Choose from {list(presets.keys())}.")
|
|
92
|
+
sat, val = presets[color_theme]
|
|
93
|
+
|
|
94
|
+
if base_hue is None:
|
|
95
|
+
random.seed(42)
|
|
96
|
+
base_hue = random.random() * 360
|
|
97
|
+
|
|
98
|
+
# Auto-select harmony based on number of colors
|
|
99
|
+
if harmony == "auto":
|
|
100
|
+
if n_colors == 1:
|
|
101
|
+
harmony = "monochromatic"
|
|
102
|
+
elif n_colors == 2:
|
|
103
|
+
harmony = "complementary"
|
|
104
|
+
elif n_colors == 3:
|
|
105
|
+
harmony = "triadic"
|
|
106
|
+
elif n_colors == 4:
|
|
107
|
+
harmony = "tetradic"
|
|
108
|
+
elif n_colors == 5:
|
|
109
|
+
harmony = "split-complementary"
|
|
110
|
+
else:
|
|
111
|
+
harmony = "tetradic"
|
|
112
|
+
|
|
113
|
+
base_hues = _get_harmony_hues(base_hue, harmony)
|
|
114
|
+
colors = []
|
|
115
|
+
for i in range(n_colors):
|
|
116
|
+
if i < len(base_hues):
|
|
117
|
+
hue = base_hues[i]
|
|
118
|
+
s = sat
|
|
119
|
+
v = val
|
|
120
|
+
else:
|
|
121
|
+
# Generate variants by cycling through base hues and subtly altering sat/val
|
|
122
|
+
cycle = (i - len(base_hues)) // len(base_hues)
|
|
123
|
+
idx = (i - len(base_hues)) % len(base_hues)
|
|
124
|
+
hue = base_hues[idx]
|
|
125
|
+
# Alternate between slightly desaturated/lighter and slightly darkened
|
|
126
|
+
if cycle % 2 == 0:
|
|
127
|
+
s = sat * 0.85
|
|
128
|
+
v = min(1.0, val * 1.15)
|
|
129
|
+
else:
|
|
130
|
+
s = sat * 1.0
|
|
131
|
+
v = max(0.0, val * 0.85)
|
|
132
|
+
rgb = colorsys.hsv_to_rgb(hue / 360.0, s, v)
|
|
133
|
+
hex_color = "#{:02x}{:02x}{:02x}".format(
|
|
134
|
+
int(rgb[0] * 255), int(rgb[1] * 255), int(rgb[2] * 255)
|
|
135
|
+
)
|
|
136
|
+
colors.append(hex_color)
|
|
137
|
+
return colors
|
|
138
|
+
|
|
139
|
+
class Bar(Chart):
|
|
140
|
+
"""Pre-built modern Bar Chart.
|
|
141
|
+
|
|
142
|
+
Notecharts' Bar integration handles automatic layout, tooltips, and themes.
|
|
143
|
+
"""
|
|
144
|
+
|
|
145
|
+
def __init__(
|
|
146
|
+
self,
|
|
147
|
+
data,
|
|
148
|
+
x,
|
|
149
|
+
y,
|
|
150
|
+
title=None,
|
|
151
|
+
width="99%",
|
|
152
|
+
height="500px",
|
|
153
|
+
renderer="canvas",
|
|
154
|
+
theme="light",
|
|
155
|
+
custom_options=None,
|
|
156
|
+
user_colors=None,
|
|
157
|
+
**kwargs
|
|
158
|
+
):
|
|
159
|
+
"""Initializes a Bar Chart.
|
|
160
|
+
|
|
161
|
+
Args:
|
|
162
|
+
data (list-of-lists, list-of-dicts, or DataFrame): The source data.
|
|
163
|
+
x (str): Column name for the x-axis.
|
|
164
|
+
y (str or list[str]): Column name(s) for the y-axis.
|
|
165
|
+
title (str, optional): Chart title. Defaults to None.
|
|
166
|
+
width (str, optional): CSS width. Defaults to "99%".
|
|
167
|
+
height (str, optional): CSS height. Defaults to "500px".
|
|
168
|
+
renderer (str, optional): 'canvas' or 'svg'. Defaults to "canvas".
|
|
169
|
+
theme (str, optional): 'light' or 'dark'. Defaults to "light".
|
|
170
|
+
custom_options (dict, optional): Extra options to merge into the ECharts dict.
|
|
171
|
+
user_colors (list[str], optional): List of hex colors. Defaults to None.
|
|
172
|
+
**kwargs: Forwarded to the base Chart class.
|
|
173
|
+
"""
|
|
174
|
+
formatted_data = _format_data(data)
|
|
175
|
+
y_cols = y if isinstance(y, list) else [y]
|
|
176
|
+
|
|
177
|
+
series = []
|
|
178
|
+
for y_col in y_cols:
|
|
179
|
+
series.append({
|
|
180
|
+
"type": "bar",
|
|
181
|
+
"encode": {"x": x, "y": y_col},
|
|
182
|
+
"name": str(y_col),
|
|
183
|
+
"itemStyle": {
|
|
184
|
+
"borderRadius": [6, 6, 0, 0],
|
|
185
|
+
},
|
|
186
|
+
"animationDuration": 1200,
|
|
187
|
+
"animationEasing": "cubicOut",
|
|
188
|
+
})
|
|
189
|
+
|
|
190
|
+
# Use user-provided colors if given, else auto-generate harmonious palette
|
|
191
|
+
if user_colors is not None:
|
|
192
|
+
palette = user_colors
|
|
193
|
+
else:
|
|
194
|
+
palette = _hsv_palette(len(y_cols), color_theme="neon", chart_theme=theme, harmony="auto")
|
|
195
|
+
|
|
196
|
+
options = {
|
|
197
|
+
"color": palette,
|
|
198
|
+
"title": {
|
|
199
|
+
"text": title,
|
|
200
|
+
"left": "center",
|
|
201
|
+
"top": 24,
|
|
202
|
+
"textStyle": {
|
|
203
|
+
"fontSize": 22,
|
|
204
|
+
"fontWeight": 600,
|
|
205
|
+
},
|
|
206
|
+
},
|
|
207
|
+
"tooltip": {
|
|
208
|
+
"trigger": "axis",
|
|
209
|
+
"axisPointer": {"type": "shadow"},
|
|
210
|
+
"borderWidth": 0,
|
|
211
|
+
"padding": [14, 18],
|
|
212
|
+
"shadowBlur": 10,
|
|
213
|
+
"shadowColor": "rgba(0, 0, 0, 0.4)",
|
|
214
|
+
"shadowOffsetX": 0,
|
|
215
|
+
"shadowOffsetY": 4,
|
|
216
|
+
"extraCssText": "border-radius: 12px;"
|
|
217
|
+
},
|
|
218
|
+
"toolbox": {
|
|
219
|
+
"feature": {
|
|
220
|
+
"restore": {},
|
|
221
|
+
"magicType": {
|
|
222
|
+
"type": ["line", "stack"]
|
|
223
|
+
},
|
|
224
|
+
"saveAsImage": {
|
|
225
|
+
"name": title if title else "Chart"
|
|
226
|
+
}
|
|
227
|
+
}
|
|
228
|
+
},
|
|
229
|
+
"dataZoom": {
|
|
230
|
+
"type": JSCode("'inside'")
|
|
231
|
+
},
|
|
232
|
+
"legend": {
|
|
233
|
+
"bottom": 20,
|
|
234
|
+
"type": "scroll",
|
|
235
|
+
"icon": "roundRect",
|
|
236
|
+
"textStyle": {"fontSize": 13},
|
|
237
|
+
},
|
|
238
|
+
"grid": {
|
|
239
|
+
"left": "5%",
|
|
240
|
+
"right": "5%",
|
|
241
|
+
"bottom": "18%",
|
|
242
|
+
"top": "18%",
|
|
243
|
+
"containLabel": True,
|
|
244
|
+
},
|
|
245
|
+
"xAxis": {
|
|
246
|
+
"type": "category",
|
|
247
|
+
"axisLine": {"show": False},
|
|
248
|
+
"axisTick": {"show": False},
|
|
249
|
+
"axisLabel": {"fontSize": 12},
|
|
250
|
+
},
|
|
251
|
+
"yAxis": {
|
|
252
|
+
"type": "value",
|
|
253
|
+
"splitLine": {
|
|
254
|
+
"lineStyle": {
|
|
255
|
+
"type": "dashed",
|
|
256
|
+
}
|
|
257
|
+
},
|
|
258
|
+
"axisLabel": {"fontSize": 12},
|
|
259
|
+
},
|
|
260
|
+
"dataset": {"source": formatted_data},
|
|
261
|
+
"series": series,
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
if title is None:
|
|
265
|
+
del options["title"]
|
|
266
|
+
|
|
267
|
+
if custom_options:
|
|
268
|
+
_deep_update(options, custom_options)
|
|
269
|
+
|
|
270
|
+
super().__init__(
|
|
271
|
+
options=options,
|
|
272
|
+
width=width,
|
|
273
|
+
height=height,
|
|
274
|
+
renderer=renderer,
|
|
275
|
+
theme=theme,
|
|
276
|
+
**kwargs
|
|
277
|
+
)
|
|
278
|
+
|
|
279
|
+
class Line(Chart):
|
|
280
|
+
"""Pre-built modern Line Chart.
|
|
281
|
+
|
|
282
|
+
Supports smooth lines, area fill, and automatic color palettes.
|
|
283
|
+
"""
|
|
284
|
+
|
|
285
|
+
def __init__(
|
|
286
|
+
self,
|
|
287
|
+
data,
|
|
288
|
+
x,
|
|
289
|
+
y,
|
|
290
|
+
title=None,
|
|
291
|
+
area=True,
|
|
292
|
+
smooth=True,
|
|
293
|
+
width="99%",
|
|
294
|
+
height="500px",
|
|
295
|
+
renderer="canvas",
|
|
296
|
+
theme="light",
|
|
297
|
+
custom_options=None,
|
|
298
|
+
user_colors=None,
|
|
299
|
+
**kwargs
|
|
300
|
+
):
|
|
301
|
+
"""Initializes a Line Chart.
|
|
302
|
+
|
|
303
|
+
Args:
|
|
304
|
+
data (list-of-lists, list-of-dicts, or DataFrame): The source data.
|
|
305
|
+
x (str): Column name for the x-axis.
|
|
306
|
+
y (str or list[str]): Column name(s) for the y-axis.
|
|
307
|
+
title (str, optional): Chart title. Defaults to None.
|
|
308
|
+
area (bool, optional): Whether to show area fill. Defaults to True.
|
|
309
|
+
smooth (bool, optional): Whether to smooth the line. Defaults to True.
|
|
310
|
+
width (str, optional): CSS width. Defaults to "99%".
|
|
311
|
+
height (str, optional): CSS height. Defaults to "500px".
|
|
312
|
+
renderer (str, optional): 'canvas' or 'svg'. Defaults to "canvas".
|
|
313
|
+
theme (str, optional): 'light' or 'dark'. Defaults to "light".
|
|
314
|
+
custom_options (dict, optional): Extra options to merge into the ECharts dict.
|
|
315
|
+
user_colors (list[str], optional): List of hex colors. Defaults to None.
|
|
316
|
+
**kwargs: Forwarded to the base Chart class.
|
|
317
|
+
"""
|
|
318
|
+
formatted_data = _format_data(data)
|
|
319
|
+
y_cols = y if isinstance(y, list) else [y]
|
|
320
|
+
|
|
321
|
+
if user_colors is not None:
|
|
322
|
+
palette = user_colors
|
|
323
|
+
else:
|
|
324
|
+
palette = _hsv_palette(len(y_cols), color_theme="neon", chart_theme=theme, harmony="auto")
|
|
325
|
+
|
|
326
|
+
series = []
|
|
327
|
+
for i, y_col in enumerate(y_cols):
|
|
328
|
+
color = palette[i % len(palette)]
|
|
329
|
+
ser = {
|
|
330
|
+
"type": "line",
|
|
331
|
+
"encode": {"x": x, "y": y_col},
|
|
332
|
+
"name": str(y_col),
|
|
333
|
+
"smooth": smooth,
|
|
334
|
+
"symbol": "circle",
|
|
335
|
+
"symbolSize": 8,
|
|
336
|
+
"lineStyle": {"width": 3},
|
|
337
|
+
"animationDuration": 1000,
|
|
338
|
+
"animationEasing": "cubicOut",
|
|
339
|
+
}
|
|
340
|
+
if area:
|
|
341
|
+
ser["areaStyle"] = {
|
|
342
|
+
"color": {
|
|
343
|
+
"type": "linear",
|
|
344
|
+
"x": 0, "y": 0, "x2": 0, "y2": 1,
|
|
345
|
+
"colorStops": [
|
|
346
|
+
{"offset": 0, "color": f"{color}40"},
|
|
347
|
+
{"offset": 1, "color": f"{color}00"}
|
|
348
|
+
]
|
|
349
|
+
}
|
|
350
|
+
}
|
|
351
|
+
series.append(ser)
|
|
352
|
+
|
|
353
|
+
options = {
|
|
354
|
+
"color": palette,
|
|
355
|
+
"title": {
|
|
356
|
+
"text": title,
|
|
357
|
+
"left": "center",
|
|
358
|
+
"top": 24,
|
|
359
|
+
"textStyle": {"fontSize": 22, "fontWeight": 600},
|
|
360
|
+
},
|
|
361
|
+
"tooltip": {
|
|
362
|
+
"trigger": "axis",
|
|
363
|
+
"borderWidth": 0,
|
|
364
|
+
"padding": [14, 18],
|
|
365
|
+
"shadowBlur": 10,
|
|
366
|
+
"shadowColor": "rgba(0, 0, 0, 0.12)",
|
|
367
|
+
"extraCssText": "border-radius: 12px;",
|
|
368
|
+
},
|
|
369
|
+
"toolbox": {
|
|
370
|
+
"feature": {
|
|
371
|
+
"restore": {},
|
|
372
|
+
"magicType": {"type": ["bar", "stack"]},
|
|
373
|
+
"saveAsImage": {
|
|
374
|
+
"name": title if title else "Chart",
|
|
375
|
+
"pixelRatio": 3
|
|
376
|
+
},
|
|
377
|
+
"dataZoom": {}
|
|
378
|
+
}
|
|
379
|
+
},
|
|
380
|
+
"dataZoom": {"type": JSCode("'inside'")},
|
|
381
|
+
"legend": {
|
|
382
|
+
"bottom": 20,
|
|
383
|
+
"type": "scroll",
|
|
384
|
+
"icon": "circle",
|
|
385
|
+
"textStyle": {"fontSize": 13},
|
|
386
|
+
},
|
|
387
|
+
"grid": {
|
|
388
|
+
"left": "5%",
|
|
389
|
+
"right": "5%",
|
|
390
|
+
"bottom": "18%",
|
|
391
|
+
"top": "18%",
|
|
392
|
+
"containLabel": True,
|
|
393
|
+
},
|
|
394
|
+
"xAxis": {
|
|
395
|
+
"type": "category",
|
|
396
|
+
"axisLine": {"show": False},
|
|
397
|
+
"axisTick": {"show": False},
|
|
398
|
+
"axisLabel": {"fontSize": 12},
|
|
399
|
+
},
|
|
400
|
+
"yAxis": {
|
|
401
|
+
"type": "value",
|
|
402
|
+
"splitLine": {"lineStyle": {"type": "dashed"}},
|
|
403
|
+
"axisLabel": {"fontSize": 12},
|
|
404
|
+
},
|
|
405
|
+
"dataset": {"source": formatted_data},
|
|
406
|
+
"series": series,
|
|
407
|
+
}
|
|
408
|
+
|
|
409
|
+
if title is None:
|
|
410
|
+
del options["title"]
|
|
411
|
+
|
|
412
|
+
if custom_options:
|
|
413
|
+
_deep_update(options, custom_options)
|
|
414
|
+
|
|
415
|
+
super().__init__(
|
|
416
|
+
options=options,
|
|
417
|
+
width=width,
|
|
418
|
+
height=height,
|
|
419
|
+
renderer=renderer,
|
|
420
|
+
theme=theme,
|
|
421
|
+
**kwargs
|
|
422
|
+
)
|
|
423
|
+
|
|
424
|
+
class Scatter(Chart):
|
|
425
|
+
"""Pre-built modern Scatter Plot.
|
|
426
|
+
|
|
427
|
+
Optimized for high-density visualizations with clear tooltips.
|
|
428
|
+
"""
|
|
429
|
+
|
|
430
|
+
def __init__(
|
|
431
|
+
self,
|
|
432
|
+
data,
|
|
433
|
+
x,
|
|
434
|
+
y,
|
|
435
|
+
title=None,
|
|
436
|
+
name_col=None,
|
|
437
|
+
width="99%",
|
|
438
|
+
height="500px",
|
|
439
|
+
renderer="canvas",
|
|
440
|
+
theme="light",
|
|
441
|
+
custom_options=None,
|
|
442
|
+
user_colors=None,
|
|
443
|
+
**kwargs
|
|
444
|
+
):
|
|
445
|
+
"""Initializes a Scatter Plot.
|
|
446
|
+
|
|
447
|
+
Args:
|
|
448
|
+
data (list-of-lists, list-of-dicts, or DataFrame): The source data.
|
|
449
|
+
x (str): Column name for the x-axis.
|
|
450
|
+
y (str or list[str]): Column name(s) for the y-axis.
|
|
451
|
+
title (str, optional): Chart title. Defaults to None.
|
|
452
|
+
name_col (str, optional): Column name for series names. Defaults to None.
|
|
453
|
+
width (str, optional): CSS width. Defaults to "99%".
|
|
454
|
+
height (str, optional): CSS height. Defaults to "500px".
|
|
455
|
+
renderer (str, optional): 'canvas' or 'svg'. Defaults to "canvas".
|
|
456
|
+
theme (str, optional): 'light' or 'dark'. Defaults to "light".
|
|
457
|
+
custom_options (dict, optional): Extra options to merge into the ECharts dict.
|
|
458
|
+
user_colors (list[str], optional): List of hex colors. Defaults to None.
|
|
459
|
+
**kwargs: Forwarded to the base Chart class.
|
|
460
|
+
"""
|
|
461
|
+
formatted_data = _format_data(data)
|
|
462
|
+
y_cols = y if isinstance(y, list) else [y]
|
|
463
|
+
|
|
464
|
+
series = []
|
|
465
|
+
for y_col in y_cols:
|
|
466
|
+
series.append({
|
|
467
|
+
"type": "scatter",
|
|
468
|
+
"encode": {"x": x, "y": y_col},
|
|
469
|
+
"name": str(y_col),
|
|
470
|
+
"symbolSize": 14,
|
|
471
|
+
"animationDuration": 1000,
|
|
472
|
+
"animationEasing": "cubicOut",
|
|
473
|
+
})
|
|
474
|
+
|
|
475
|
+
if user_colors is not None:
|
|
476
|
+
palette = user_colors
|
|
477
|
+
else:
|
|
478
|
+
palette = _hsv_palette(len(y_cols), color_theme="neon", chart_theme=theme, harmony="auto")
|
|
479
|
+
|
|
480
|
+
options = {
|
|
481
|
+
"color": palette,
|
|
482
|
+
"title": {
|
|
483
|
+
"text": title,
|
|
484
|
+
"left": "center",
|
|
485
|
+
"top": 24,
|
|
486
|
+
"textStyle": {"fontSize": 22, "fontWeight": 600},
|
|
487
|
+
},
|
|
488
|
+
"tooltip": {
|
|
489
|
+
"trigger": "item",
|
|
490
|
+
"borderWidth": 0,
|
|
491
|
+
"padding": [14, 18],
|
|
492
|
+
"shadowBlur": 10,
|
|
493
|
+
"shadowColor": "rgba(0, 0, 0, 0.12)",
|
|
494
|
+
"extraCssText": "border-radius: 12px;",
|
|
495
|
+
"formatter": JSCode(
|
|
496
|
+
f"""function(params) {{
|
|
497
|
+
var row = params.data;
|
|
498
|
+
var lines = [];
|
|
499
|
+
var nameVal = '{name_col}' ? row['{name_col}'] : null;
|
|
500
|
+
if (nameVal !== undefined && nameVal !== null) {{
|
|
501
|
+
lines.push('<strong>' + nameVal + '</strong>');
|
|
502
|
+
}}
|
|
503
|
+
var val, display;
|
|
504
|
+
for (var key in row) {{
|
|
505
|
+
if (row.hasOwnProperty(key) && key !== '{name_col}') {{
|
|
506
|
+
val = row[key];
|
|
507
|
+
display = (typeof val === 'number') ? val.toFixed(3) : val;
|
|
508
|
+
lines.push(key + ': ' + display);
|
|
509
|
+
}}
|
|
510
|
+
}}
|
|
511
|
+
return lines.join('<br/>');
|
|
512
|
+
}}"""
|
|
513
|
+
)
|
|
514
|
+
},
|
|
515
|
+
"toolbox": {
|
|
516
|
+
"feature": {
|
|
517
|
+
"restore": {},
|
|
518
|
+
"saveAsImage": {
|
|
519
|
+
"name": title if title else "Chart",
|
|
520
|
+
"pixelRatio": 3
|
|
521
|
+
},
|
|
522
|
+
"dataZoom": {}
|
|
523
|
+
}
|
|
524
|
+
},
|
|
525
|
+
"dataZoom": {
|
|
526
|
+
"type": JSCode("'inside'")
|
|
527
|
+
},
|
|
528
|
+
"legend": {
|
|
529
|
+
"bottom": 20,
|
|
530
|
+
"type": "scroll",
|
|
531
|
+
"icon": "circle",
|
|
532
|
+
"textStyle": {"fontSize": 13},
|
|
533
|
+
},
|
|
534
|
+
"grid": {
|
|
535
|
+
"left": "5%",
|
|
536
|
+
"right": "5%",
|
|
537
|
+
"bottom": "18%",
|
|
538
|
+
"top": "18%",
|
|
539
|
+
"containLabel": True,
|
|
540
|
+
},
|
|
541
|
+
"xAxis": {
|
|
542
|
+
"type": "value",
|
|
543
|
+
"splitLine": {"lineStyle": {"type": "dashed"}},
|
|
544
|
+
"axisLabel": {"fontSize": 12},
|
|
545
|
+
},
|
|
546
|
+
"yAxis": {
|
|
547
|
+
"type": "value",
|
|
548
|
+
"splitLine": {"lineStyle": {"type": "dashed"}},
|
|
549
|
+
"axisLabel": {"fontSize": 12},
|
|
550
|
+
},
|
|
551
|
+
"dataset": {"source": formatted_data},
|
|
552
|
+
"series": series,
|
|
553
|
+
}
|
|
554
|
+
|
|
555
|
+
if title is None:
|
|
556
|
+
del options["title"]
|
|
557
|
+
|
|
558
|
+
if custom_options:
|
|
559
|
+
_deep_update(options, custom_options)
|
|
560
|
+
|
|
561
|
+
super().__init__(
|
|
562
|
+
options=options,
|
|
563
|
+
width=width,
|
|
564
|
+
height=height,
|
|
565
|
+
renderer=renderer,
|
|
566
|
+
theme=theme,
|
|
567
|
+
**kwargs
|
|
568
|
+
)
|
|
569
|
+
|
|
570
|
+
class Donut(Chart):
|
|
571
|
+
"""Pre-built modern Donut/Pie Chart.
|
|
572
|
+
|
|
573
|
+
Supports Nightingale Rose charts and automatic total label centering.
|
|
574
|
+
"""
|
|
575
|
+
|
|
576
|
+
def __init__(
|
|
577
|
+
self,
|
|
578
|
+
data,
|
|
579
|
+
label_col,
|
|
580
|
+
value_col,
|
|
581
|
+
title=None,
|
|
582
|
+
rose=False,
|
|
583
|
+
show_total=True,
|
|
584
|
+
width="99%",
|
|
585
|
+
height="500px",
|
|
586
|
+
renderer="canvas",
|
|
587
|
+
theme="light",
|
|
588
|
+
custom_options=None,
|
|
589
|
+
user_colors=None,
|
|
590
|
+
**kwargs
|
|
591
|
+
):
|
|
592
|
+
"""Initializes a Donut Chart.
|
|
593
|
+
|
|
594
|
+
Args:
|
|
595
|
+
data (list-of-lists, list-of-dicts, or DataFrame): The source data.
|
|
596
|
+
label_col (str): Column name for slice labels.
|
|
597
|
+
value_col (str): Column name for slice values.
|
|
598
|
+
title (str, optional): Chart title. Defaults to None.
|
|
599
|
+
rose (bool, optional): Whether to use 'rose' type (Nightingale Chart). Defaults to False.
|
|
600
|
+
show_total (bool, optional): Whether to show the total value in the center. Defaults to True.
|
|
601
|
+
width (str, optional): CSS width. Defaults to "99%".
|
|
602
|
+
height (str, optional): CSS height. Defaults to "500px".
|
|
603
|
+
renderer (str, optional): 'canvas' or 'svg'. Defaults to "canvas".
|
|
604
|
+
theme (str, optional): 'light' or 'dark'. Defaults to "light".
|
|
605
|
+
custom_options (dict, optional): Extra options to merge into the ECharts dict.
|
|
606
|
+
user_colors (list[str], optional): List of hex colors. Defaults to None.
|
|
607
|
+
**kwargs: Forwarded to the base Chart class.
|
|
608
|
+
"""
|
|
609
|
+
formatted_data = _format_data(data)
|
|
610
|
+
|
|
611
|
+
pie_data = [{"name": str(row[label_col]), "value": row[value_col]} for row in formatted_data]
|
|
612
|
+
|
|
613
|
+
total = sum(row[value_col] for row in formatted_data)
|
|
614
|
+
|
|
615
|
+
series = {
|
|
616
|
+
"type": "pie",
|
|
617
|
+
"radius": ["45%", "75%"] if not rose else ["30%", "75%"],
|
|
618
|
+
"center": ["50%", "50%"],
|
|
619
|
+
"data": pie_data,
|
|
620
|
+
"label": {
|
|
621
|
+
"show": True,
|
|
622
|
+
"position": "outside",
|
|
623
|
+
"formatter": "{b}: {c} ({d}%)",
|
|
624
|
+
"fontSize": 12,
|
|
625
|
+
},
|
|
626
|
+
"emphasis": {
|
|
627
|
+
"label": {"fontSize": 16, "fontWeight": "bold"},
|
|
628
|
+
"scale": True,
|
|
629
|
+
"scaleSize": 10,
|
|
630
|
+
},
|
|
631
|
+
"animationType": "scale",
|
|
632
|
+
"animationEasing": "elasticOut",
|
|
633
|
+
}
|
|
634
|
+
|
|
635
|
+
if rose:
|
|
636
|
+
series["roseType"] = "radius"
|
|
637
|
+
|
|
638
|
+
graphic = None
|
|
639
|
+
if show_total and not rose:
|
|
640
|
+
graphic = [
|
|
641
|
+
{
|
|
642
|
+
"type": "text",
|
|
643
|
+
"left": "center",
|
|
644
|
+
"top": "center",
|
|
645
|
+
"style": {
|
|
646
|
+
"text": f"{total}",
|
|
647
|
+
"textAlign": "center",
|
|
648
|
+
"fontSize": 24,
|
|
649
|
+
"fontWeight": "bold",
|
|
650
|
+
"fill": "#333" if theme == "light" else "#eee",
|
|
651
|
+
},
|
|
652
|
+
}
|
|
653
|
+
]
|
|
654
|
+
|
|
655
|
+
if user_colors is not None:
|
|
656
|
+
palette = user_colors
|
|
657
|
+
else:
|
|
658
|
+
palette = _hsv_palette(len(pie_data), color_theme="neon", chart_theme=theme, harmony="auto")
|
|
659
|
+
|
|
660
|
+
options = {
|
|
661
|
+
"color": palette,
|
|
662
|
+
"title": {
|
|
663
|
+
"text": title,
|
|
664
|
+
"left": "center",
|
|
665
|
+
"top": 24,
|
|
666
|
+
"textStyle": {"fontSize": 22, "fontWeight": 600},
|
|
667
|
+
},
|
|
668
|
+
# "tooltip": {
|
|
669
|
+
# "trigger": "item",
|
|
670
|
+
# "formatter": "{b}: {c} ({d}%)",
|
|
671
|
+
# "borderWidth": 0,
|
|
672
|
+
# "padding": [14, 18],
|
|
673
|
+
# "shadowBlur": 10,
|
|
674
|
+
# "shadowColor": "rgba(0, 0, 0, 0.12)",
|
|
675
|
+
# "extraCssText": "border-radius: 12px;",
|
|
676
|
+
# },
|
|
677
|
+
"toolbox": {
|
|
678
|
+
"feature": {
|
|
679
|
+
"restore": {},
|
|
680
|
+
"saveAsImage": {
|
|
681
|
+
"name": title if title else "Chart",
|
|
682
|
+
"pixelRatio": 3
|
|
683
|
+
},
|
|
684
|
+
}
|
|
685
|
+
},
|
|
686
|
+
"legend": {
|
|
687
|
+
"bottom": 20,
|
|
688
|
+
"type": "scroll",
|
|
689
|
+
"icon": "circle",
|
|
690
|
+
"textStyle": {"fontSize": 13},
|
|
691
|
+
},
|
|
692
|
+
"series": [series],
|
|
693
|
+
}
|
|
694
|
+
|
|
695
|
+
if graphic:
|
|
696
|
+
options["graphic"] = graphic
|
|
697
|
+
|
|
698
|
+
if title is None:
|
|
699
|
+
del options["title"]
|
|
700
|
+
|
|
701
|
+
if custom_options:
|
|
702
|
+
_deep_update(options, custom_options)
|
|
703
|
+
|
|
704
|
+
super().__init__(
|
|
705
|
+
options=options,
|
|
706
|
+
width=width,
|
|
707
|
+
height=height,
|
|
708
|
+
renderer=renderer,
|
|
709
|
+
theme=theme,
|
|
710
|
+
**kwargs
|
|
711
|
+
)
|
|
712
|
+
|
|
713
|
+
class Radar(Chart):
|
|
714
|
+
"""Pre-built modern Radar Chart.
|
|
715
|
+
|
|
716
|
+
Radar charts are ideal for displaying multivariate data on a 2D chart.
|
|
717
|
+
"""
|
|
718
|
+
|
|
719
|
+
def __init__(
|
|
720
|
+
self,
|
|
721
|
+
data,
|
|
722
|
+
name_col,
|
|
723
|
+
dimensions,
|
|
724
|
+
title=None,
|
|
725
|
+
width="99%",
|
|
726
|
+
height="500px",
|
|
727
|
+
renderer="canvas",
|
|
728
|
+
theme="light",
|
|
729
|
+
custom_options=None,
|
|
730
|
+
user_colors=None,
|
|
731
|
+
**kwargs
|
|
732
|
+
):
|
|
733
|
+
"""Initializes a Radar Chart.
|
|
734
|
+
|
|
735
|
+
Args:
|
|
736
|
+
data (list-of-lists, list-of-dicts, or DataFrame): The source data.
|
|
737
|
+
name_col (str): Column that identifies each series (e.g., 'player').
|
|
738
|
+
dimensions (list[str]): Column names for the radar axes (e.g., ['speed', 'power']).
|
|
739
|
+
title (str, optional): Chart title. Defaults to None.
|
|
740
|
+
width (str, optional): CSS width. Defaults to "99%".
|
|
741
|
+
height (str, optional): CSS height. Defaults to "500px".
|
|
742
|
+
renderer (str, optional): 'canvas' or 'svg'. Defaults to "canvas".
|
|
743
|
+
theme (str, optional): 'light' or 'dark'. Defaults to "light".
|
|
744
|
+
custom_options (dict, optional): Extra options to merge into the ECharts dict.
|
|
745
|
+
user_colors (list[str], optional): List of hex colors. Defaults to None.
|
|
746
|
+
**kwargs: Forwarded to the base Chart class.
|
|
747
|
+
"""
|
|
748
|
+
formatted_data = _format_data(data)
|
|
749
|
+
|
|
750
|
+
# Group data by series name
|
|
751
|
+
series_map = {}
|
|
752
|
+
for row in formatted_data:
|
|
753
|
+
name = row[name_col]
|
|
754
|
+
series_map.setdefault(name, []).append(row)
|
|
755
|
+
|
|
756
|
+
# Compute max per dimension for indicator range
|
|
757
|
+
dim_max = {d: 0 for d in dimensions}
|
|
758
|
+
for row in formatted_data:
|
|
759
|
+
for d in dimensions:
|
|
760
|
+
if row[d] > dim_max[d]:
|
|
761
|
+
dim_max[d] = row[d]
|
|
762
|
+
|
|
763
|
+
indicators = [{"name": d, "max": dim_max[d]} for d in dimensions]
|
|
764
|
+
|
|
765
|
+
# Build series list
|
|
766
|
+
series = []
|
|
767
|
+
for idx, (name, rows) in enumerate(series_map.items()):
|
|
768
|
+
row = rows[0]
|
|
769
|
+
values = [row[d] for d in dimensions]
|
|
770
|
+
series.append({
|
|
771
|
+
"type": "radar",
|
|
772
|
+
"data": [{"value": values, "name": str(name)}],
|
|
773
|
+
"areaStyle": {"opacity": 0.2},
|
|
774
|
+
"symbol": "circle",
|
|
775
|
+
"symbolSize": 6,
|
|
776
|
+
"lineStyle": {"width": 2},
|
|
777
|
+
})
|
|
778
|
+
|
|
779
|
+
if user_colors is not None:
|
|
780
|
+
palette = user_colors
|
|
781
|
+
else:
|
|
782
|
+
palette = _hsv_palette(len(series), color_theme="neon", chart_theme=theme, harmony="auto")
|
|
783
|
+
|
|
784
|
+
options = {
|
|
785
|
+
"color": palette,
|
|
786
|
+
"title": {
|
|
787
|
+
"text": title,
|
|
788
|
+
"left": "center",
|
|
789
|
+
"top": 24,
|
|
790
|
+
"textStyle": {"fontSize": 22, "fontWeight": 600},
|
|
791
|
+
},
|
|
792
|
+
"tooltip": {
|
|
793
|
+
"trigger": "item",
|
|
794
|
+
"borderWidth": 0,
|
|
795
|
+
"padding": [14, 18],
|
|
796
|
+
"shadowBlur": 10,
|
|
797
|
+
"shadowColor": "rgba(0, 0, 0, 0.12)",
|
|
798
|
+
"extraCssText": "border-radius: 12px;",
|
|
799
|
+
},
|
|
800
|
+
"toolbox": {
|
|
801
|
+
"feature": {
|
|
802
|
+
"restore": {},
|
|
803
|
+
"saveAsImage": {
|
|
804
|
+
"name": title if title else "Chart",
|
|
805
|
+
"pixelRatio": 3
|
|
806
|
+
},
|
|
807
|
+
}
|
|
808
|
+
},
|
|
809
|
+
"legend": {
|
|
810
|
+
"bottom": 20,
|
|
811
|
+
"type": "scroll",
|
|
812
|
+
"icon": "circle",
|
|
813
|
+
"textStyle": {"fontSize": 13},
|
|
814
|
+
},
|
|
815
|
+
"radar": {
|
|
816
|
+
"indicator": indicators,
|
|
817
|
+
"splitArea": {
|
|
818
|
+
"areaStyle": {
|
|
819
|
+
"color": ["rgba(0,0,0,0.02)", "rgba(0,0,0,0.04)"]
|
|
820
|
+
}
|
|
821
|
+
},
|
|
822
|
+
"axisLine": {"lineStyle": {"color": "rgba(0,0,0,0.1)"}},
|
|
823
|
+
"splitLine": {"lineStyle": {"color": "rgba(0,0,0,0.1)"}},
|
|
824
|
+
},
|
|
825
|
+
"series": series,
|
|
826
|
+
}
|
|
827
|
+
|
|
828
|
+
if title is None:
|
|
829
|
+
del options["title"]
|
|
830
|
+
|
|
831
|
+
if custom_options:
|
|
832
|
+
_deep_update(options, custom_options)
|
|
833
|
+
|
|
834
|
+
super().__init__(
|
|
835
|
+
options=options,
|
|
836
|
+
width=width,
|
|
837
|
+
height=height,
|
|
838
|
+
renderer=renderer,
|
|
839
|
+
theme=theme,
|
|
840
|
+
**kwargs
|
|
841
|
+
)
|
notecharts/widget.py
ADDED
|
@@ -0,0 +1,283 @@
|
|
|
1
|
+
import json
|
|
2
|
+
import uuid
|
|
3
|
+
import urllib.parse
|
|
4
|
+
from IPython.display import display, HTML
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
class JSCode:
|
|
8
|
+
"""Wraps a raw JavaScript string to be inserted unquoted into the ECharts options.
|
|
9
|
+
|
|
10
|
+
Attributes:
|
|
11
|
+
js (str): The raw JavaScript code string.
|
|
12
|
+
"""
|
|
13
|
+
def __init__(self, js: str):
|
|
14
|
+
"""Initializes JSCode with the given JavaScript string.
|
|
15
|
+
|
|
16
|
+
Args:
|
|
17
|
+
js (str): The JavaScript code.
|
|
18
|
+
"""
|
|
19
|
+
self.js = js
|
|
20
|
+
|
|
21
|
+
def __repr__(self):
|
|
22
|
+
return f"JSCode({self.js!r})"
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class _EChartsEncoder(json.JSONEncoder):
|
|
26
|
+
def __init__(self, *args, **kwargs):
|
|
27
|
+
super().__init__(*args, **kwargs)
|
|
28
|
+
self.placeholders = {}
|
|
29
|
+
|
|
30
|
+
def default(self, obj):
|
|
31
|
+
if isinstance(obj, JSCode):
|
|
32
|
+
placeholder = f"__JS_{uuid.uuid4().hex}__"
|
|
33
|
+
self.placeholders[placeholder] = obj.js
|
|
34
|
+
return placeholder
|
|
35
|
+
return super().default(obj)
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
class Chart:
|
|
39
|
+
"""Renders Apache ECharts directly in a Jupyter notebook from a Python 'options' dict.
|
|
40
|
+
|
|
41
|
+
Features include automatic Google Fonts loading from any 'fontFamily' value found
|
|
42
|
+
inside the options dictionary and global font setting via `textStyle.fontFamily`.
|
|
43
|
+
|
|
44
|
+
Attributes:
|
|
45
|
+
options (dict): The ECharts option dictionary.
|
|
46
|
+
width (str): CSS width of the chart container.
|
|
47
|
+
height (str): CSS height of the chart container.
|
|
48
|
+
renderer (str): The renderer type ('canvas' or 'svg').
|
|
49
|
+
theme (str): The chart theme ('light' or 'dark').
|
|
50
|
+
fonts (list): List of discovered custom font families.
|
|
51
|
+
"""
|
|
52
|
+
|
|
53
|
+
# Generic CSS font families that should not be loaded from Google Fonts
|
|
54
|
+
_GENERIC_FONTS = {
|
|
55
|
+
"serif", "sans-serif", "monospace", "cursive", "fantasy",
|
|
56
|
+
"system-ui", "ui-serif", "ui-sans-serif", "ui-monospace",
|
|
57
|
+
"ui-rounded", "math", "emoji", "fangsong",
|
|
58
|
+
"inherit", "initial", "unset"
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
def __init__(
|
|
62
|
+
self,
|
|
63
|
+
options: dict,
|
|
64
|
+
width: str = "99%",
|
|
65
|
+
height: str = "500px",
|
|
66
|
+
renderer: str = "canvas",
|
|
67
|
+
theme: str = "light",
|
|
68
|
+
):
|
|
69
|
+
"""Initializes the Chart with options and display settings.
|
|
70
|
+
|
|
71
|
+
Args:
|
|
72
|
+
options (dict): The ECharts option dictionary.
|
|
73
|
+
width (str, optional): CSS width. Defaults to "99%".
|
|
74
|
+
height (str, optional): CSS height. Defaults to "500px".
|
|
75
|
+
renderer (str, optional): 'canvas' or 'svg'. Defaults to "canvas".
|
|
76
|
+
theme (str, optional): 'light' or 'dark'. Defaults to "light".
|
|
77
|
+
|
|
78
|
+
Raises:
|
|
79
|
+
TypeError: If options is not a dictionary.
|
|
80
|
+
ValueError: If renderer or theme is invalid.
|
|
81
|
+
"""
|
|
82
|
+
if not isinstance(options, dict):
|
|
83
|
+
raise TypeError(
|
|
84
|
+
f"Chart options must be a dictionary, got {type(options).__name__}."
|
|
85
|
+
)
|
|
86
|
+
self.options = options
|
|
87
|
+
self.width = width.strip() if isinstance(width, str) else str(width)
|
|
88
|
+
self.height = height.strip() if isinstance(height, str) else str(height)
|
|
89
|
+
|
|
90
|
+
self.renderer = renderer.lower().strip()
|
|
91
|
+
if self.renderer not in ["canvas", "svg"]:
|
|
92
|
+
raise ValueError(
|
|
93
|
+
f"Invalid renderer '{self.renderer}'. Supported: 'canvas', 'svg'."
|
|
94
|
+
)
|
|
95
|
+
|
|
96
|
+
self.theme = theme.lower().strip()
|
|
97
|
+
if self.theme not in ["light", "dark"]:
|
|
98
|
+
raise ValueError(
|
|
99
|
+
f"Invalid theme '{self.theme}'. Supported: 'light', 'dark'."
|
|
100
|
+
)
|
|
101
|
+
|
|
102
|
+
if self.theme == "light" and "backgroundColor" not in self.options:
|
|
103
|
+
self.options["backgroundColor"] = "white"
|
|
104
|
+
|
|
105
|
+
# Discover all custom font families from the options dict
|
|
106
|
+
self.fonts = list(self._discover_fonts(self.options))
|
|
107
|
+
|
|
108
|
+
# ------------------------------------------------------------------
|
|
109
|
+
# Font discovery
|
|
110
|
+
# ------------------------------------------------------------------
|
|
111
|
+
@classmethod
|
|
112
|
+
def _extract_font_families(cls, value):
|
|
113
|
+
"""Return a set of non‑generic font family names from a raw value."""
|
|
114
|
+
if isinstance(value, JSCode):
|
|
115
|
+
return set()
|
|
116
|
+
if isinstance(value, str):
|
|
117
|
+
candidates = [name.strip().strip("'\"") for name in value.split(",")]
|
|
118
|
+
elif isinstance(value, (list, tuple)):
|
|
119
|
+
candidates = []
|
|
120
|
+
for item in value:
|
|
121
|
+
if isinstance(item, str):
|
|
122
|
+
candidates.extend(
|
|
123
|
+
name.strip().strip("'\"") for name in item.split(",")
|
|
124
|
+
)
|
|
125
|
+
else:
|
|
126
|
+
return set()
|
|
127
|
+
|
|
128
|
+
families = set()
|
|
129
|
+
for candidate in candidates:
|
|
130
|
+
lower = candidate.lower()
|
|
131
|
+
# Keep only non‑generic names
|
|
132
|
+
if lower and lower not in cls._GENERIC_FONTS:
|
|
133
|
+
families.add(candidate)
|
|
134
|
+
return families
|
|
135
|
+
|
|
136
|
+
def _discover_fonts(self, obj, found=None):
|
|
137
|
+
"""Recursively walk the options dict to collect font families."""
|
|
138
|
+
if found is None:
|
|
139
|
+
found = set()
|
|
140
|
+
if isinstance(obj, dict):
|
|
141
|
+
for key, value in obj.items():
|
|
142
|
+
if key == "fontFamily":
|
|
143
|
+
found.update(self._extract_font_families(value))
|
|
144
|
+
else:
|
|
145
|
+
self._discover_fonts(value, found)
|
|
146
|
+
elif isinstance(obj, list):
|
|
147
|
+
for item in obj:
|
|
148
|
+
self._discover_fonts(item, found)
|
|
149
|
+
return found
|
|
150
|
+
|
|
151
|
+
# ------------------------------------------------------------------
|
|
152
|
+
# Serialisation
|
|
153
|
+
# ------------------------------------------------------------------
|
|
154
|
+
def _serialise_options(self) -> str:
|
|
155
|
+
encoder = _EChartsEncoder()
|
|
156
|
+
json_str = encoder.encode(self.options)
|
|
157
|
+
for placeholder, js_code in encoder.placeholders.items():
|
|
158
|
+
json_str = json_str.replace(f'"{placeholder}"', js_code)
|
|
159
|
+
return json_str
|
|
160
|
+
|
|
161
|
+
# ------------------------------------------------------------------
|
|
162
|
+
# HTML generation
|
|
163
|
+
# ------------------------------------------------------------------
|
|
164
|
+
def _make_chart_html(self, chart_id=None) -> str:
|
|
165
|
+
if chart_id is None:
|
|
166
|
+
chart_id = f"echart_{uuid.uuid4().hex}"
|
|
167
|
+
options_js = self._serialise_options()
|
|
168
|
+
|
|
169
|
+
font_link = ""
|
|
170
|
+
if self.fonts:
|
|
171
|
+
base_url = "https://fonts.googleapis.com/css2"
|
|
172
|
+
params = {"family": self.fonts, "display": "swap"}
|
|
173
|
+
query_string = urllib.parse.urlencode(params, doseq=True)
|
|
174
|
+
font_link = f'<link href="{base_url}?{query_string}" rel="stylesheet">'
|
|
175
|
+
|
|
176
|
+
has_fonts = "true" if self.fonts else "false"
|
|
177
|
+
|
|
178
|
+
return f"""
|
|
179
|
+
{font_link}
|
|
180
|
+
<div id="{chart_id}" style="width:{self.width};height:{self.height};"></div>
|
|
181
|
+
<script>
|
|
182
|
+
(function() {{
|
|
183
|
+
|
|
184
|
+
// ── wait for the div to exist in the DOM ──────────────────────────
|
|
185
|
+
function waitForDom(id, cb) {{
|
|
186
|
+
var dom = document.getElementById(id);
|
|
187
|
+
if (dom) {{ cb(dom); return; }}
|
|
188
|
+
var observer = new MutationObserver(function() {{
|
|
189
|
+
var el = document.getElementById(id);
|
|
190
|
+
if (el) {{ observer.disconnect(); cb(el); }}
|
|
191
|
+
}});
|
|
192
|
+
observer.observe(document.body || document.documentElement, {{
|
|
193
|
+
childList: true, subtree: true
|
|
194
|
+
}});
|
|
195
|
+
var attempts = 0;
|
|
196
|
+
var poll = setInterval(function() {{
|
|
197
|
+
var el = document.getElementById(id);
|
|
198
|
+
if (el) {{ clearInterval(poll); observer.disconnect(); cb(el); return; }}
|
|
199
|
+
if (++attempts > 100) {{
|
|
200
|
+
clearInterval(poll); observer.disconnect();
|
|
201
|
+
console.error('ECharts wrapper: #{chart_id} never appeared in DOM');
|
|
202
|
+
}}
|
|
203
|
+
}}, 100);
|
|
204
|
+
}}
|
|
205
|
+
|
|
206
|
+
// ── chart init ─────
|
|
207
|
+
function initChart(ec) {{
|
|
208
|
+
waitForDom('{chart_id}', function(dom) {{
|
|
209
|
+
var chart = ec.init(dom, '{self.theme}', {{
|
|
210
|
+
renderer: '{self.renderer}', devicePixelRatio: 3
|
|
211
|
+
}});
|
|
212
|
+
chart.setOption({options_js});
|
|
213
|
+
window.addEventListener('resize', function() {{ chart.resize(); }});
|
|
214
|
+
}});
|
|
215
|
+
}}
|
|
216
|
+
|
|
217
|
+
// ── plain <script> loader (Colab / plain Jupyter) ─────────────────
|
|
218
|
+
function loadScript(url, cb) {{
|
|
219
|
+
var s = document.createElement('script');
|
|
220
|
+
s.src = url;
|
|
221
|
+
s.onload = cb;
|
|
222
|
+
s.onerror = function() {{ console.error('ECharts wrapper: failed to load ' + url); }};
|
|
223
|
+
document.head.appendChild(s);
|
|
224
|
+
}}
|
|
225
|
+
|
|
226
|
+
function loadViaScript() {{
|
|
227
|
+
loadScript('https://cdn.jsdelivr.net/npm/echarts/dist/echarts.min.js', function() {{
|
|
228
|
+
loadScript('https://cdn.jsdelivr.net/npm/echarts-gl/dist/echarts-gl.min.js', function() {{
|
|
229
|
+
initChart(window.echarts);
|
|
230
|
+
}});
|
|
231
|
+
}});
|
|
232
|
+
}}
|
|
233
|
+
|
|
234
|
+
// ── RequireJS loader (VS Code webview) ────────────────────────────
|
|
235
|
+
function loadViaRequire() {{
|
|
236
|
+
// Reset any cached failed/partial module state
|
|
237
|
+
require.undef('echarts');
|
|
238
|
+
require.undef('echarts-gl');
|
|
239
|
+
require.config({{
|
|
240
|
+
paths: {{
|
|
241
|
+
'echarts': 'https://cdn.jsdelivr.net/npm/echarts/dist/echarts.min',
|
|
242
|
+
'echarts-gl': 'https://cdn.jsdelivr.net/npm/echarts-gl/dist/echarts-gl.min'
|
|
243
|
+
}}
|
|
244
|
+
}});
|
|
245
|
+
require(['echarts'], function(ec) {{
|
|
246
|
+
require(['echarts-gl'], function() {{
|
|
247
|
+
initChart(ec);
|
|
248
|
+
}});
|
|
249
|
+
}}, function(err) {{
|
|
250
|
+
console.error('ECharts wrapper: RequireJS failed to load', err);
|
|
251
|
+
}});
|
|
252
|
+
}}
|
|
253
|
+
|
|
254
|
+
// ── font gate → then load echarts ─────────────────────────────────
|
|
255
|
+
function loadEchartsAndInit() {{
|
|
256
|
+
if (typeof require !== 'undefined' && typeof require.config === 'function') {{
|
|
257
|
+
loadViaRequire();
|
|
258
|
+
}} else {{
|
|
259
|
+
loadViaScript();
|
|
260
|
+
}}
|
|
261
|
+
}}
|
|
262
|
+
|
|
263
|
+
if ({has_fonts}) {{
|
|
264
|
+
if (document.fonts && document.fonts.ready) {{
|
|
265
|
+
document.fonts.ready.then(loadEchartsAndInit);
|
|
266
|
+
}} else {{
|
|
267
|
+
loadEchartsAndInit();
|
|
268
|
+
}}
|
|
269
|
+
}} else {{
|
|
270
|
+
loadEchartsAndInit();
|
|
271
|
+
}}
|
|
272
|
+
}})();
|
|
273
|
+
</script>
|
|
274
|
+
"""
|
|
275
|
+
|
|
276
|
+
# ------------------------------------------------------------------
|
|
277
|
+
# Display
|
|
278
|
+
# ------------------------------------------------------------------
|
|
279
|
+
def display(self):
|
|
280
|
+
display(HTML(self._make_chart_html()))
|
|
281
|
+
|
|
282
|
+
def _repr_html_(self):
|
|
283
|
+
return self._make_chart_html()
|
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: notecharts
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Beautiful, interactive charts in notebooks with Apache ECharts' powerful declarative API
|
|
5
|
+
Author-email: Danish Munib <danishmunibcontact@gmail.com>
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
Project-URL: Homepage, https://github.com/dmunish/notecharts
|
|
8
|
+
Project-URL: Repository, https://github.com/dmunish/notecharts.git
|
|
9
|
+
Project-URL: Issues, https://github.com/dmunish/notecharts/issues
|
|
10
|
+
Keywords: echarts,jupyter,visualization,charts,notebook
|
|
11
|
+
Classifier: Development Status :: 4 - Beta
|
|
12
|
+
Classifier: Framework :: Jupyter
|
|
13
|
+
Classifier: Intended Audience :: Developers
|
|
14
|
+
Classifier: Programming Language :: Python :: 3
|
|
15
|
+
Classifier: Topic :: Scientific/Engineering :: Visualization
|
|
16
|
+
Requires-Python: >=3.8
|
|
17
|
+
Description-Content-Type: text/markdown
|
|
18
|
+
License-File: LICENSE
|
|
19
|
+
License-File: NOTICE
|
|
20
|
+
Requires-Dist: IPython
|
|
21
|
+
Dynamic: license-file
|
|
22
|
+
|
|
23
|
+
# notecharts
|
|
24
|
+
|
|
25
|
+
[](https://pypi.org/project/notecharts/)
|
|
26
|
+
[](https://opensource.org/licenses/MIT)
|
|
27
|
+
[](https://pypi.org/project/notecharts/)
|
|
28
|
+
|
|
29
|
+
**notecharts** is an ultra-lightweight, zero-config wrapper for Apache ECharts in Jupyter environments. It brings the full power of ECharts' declarative JSON-like API directly into Python notebooks without the bloat.
|
|
30
|
+
|
|
31
|
+
## Why notecharts?
|
|
32
|
+
|
|
33
|
+
If you've used ECharts in Python before, you likely encountered two extremes:
|
|
34
|
+
- **pyecharts:** Powerful, but wraps the API in a deep "Pythonic" abstraction that often deviates from the official ECharts documentation, making it hard to translate JS examples to Python.
|
|
35
|
+
- **ipecharts:** Often lacks the interactivity or ease of use, API is buggy or unclear sometimes.
|
|
36
|
+
|
|
37
|
+
**notecharts** bridges this gap. It provides a thin layer that allows you to write ECharts options exactly as they appear in the official docs, while handling the heavy lifting of library loading, font injection, and serialization.
|
|
38
|
+
|
|
39
|
+
## Key Features
|
|
40
|
+
|
|
41
|
+
- **Declarative API:** Pass a dictionary, get a chart. No complex class hierarchies to learn.
|
|
42
|
+
- **`JSCode` Support:** Inject raw JavaScript functions for formatters, tooltips, and custom logic.
|
|
43
|
+
- **Smart Font Discovery:** Automatically detect `fontFamily` declarations in your options fetch the corresponding fonts (if available) from Google Fonts.
|
|
44
|
+
- **Pre-built Modern Charts:** Includes high-level classes like `Bar`, `Line`, `Scatter`, `Donut`, and `Radar` with beautiful default harmonies.
|
|
45
|
+
- **Environment Agnostic:** Works seamlessly in VS Code, JupyterLab, and Google Colab.
|
|
46
|
+
|
|
47
|
+
## Installation
|
|
48
|
+
|
|
49
|
+
```bash
|
|
50
|
+
pip install notecharts
|
|
51
|
+
```
|
|
52
|
+
|
|
53
|
+
## Usage
|
|
54
|
+
|
|
55
|
+
### The Declarative Way (Total Control)
|
|
56
|
+
If you can find an example on the [ECharts Gallery](https://echarts.apache.org/examples/en/index.html), you can run it in `notecharts`.
|
|
57
|
+
|
|
58
|
+
```python
|
|
59
|
+
from notecharts import Chart, JSCode
|
|
60
|
+
|
|
61
|
+
options = {
|
|
62
|
+
"title": {"text": "Basic Chart"},
|
|
63
|
+
"xAxis": {"data": ["Mon", "Tue", "Wed", "Thu", "Fri"]},
|
|
64
|
+
"yAxis": {},
|
|
65
|
+
"series": [{
|
|
66
|
+
"type": "bar",
|
|
67
|
+
"data": [23, 24, 18, 25, 27], # or any other object/variable
|
|
68
|
+
"label": {
|
|
69
|
+
"show": True,
|
|
70
|
+
"formatter": JSCode("function(p) { return p.value + ' units'; }")
|
|
71
|
+
}
|
|
72
|
+
}],
|
|
73
|
+
"textStyle": {
|
|
74
|
+
"fontFamily": "Inter" # Automatically loaded from Google Fonts!
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
Chart(options).display()
|
|
79
|
+
```
|
|
80
|
+
|
|
81
|
+
### The Quick Way (Pre-built Charts)
|
|
82
|
+
Use the pre-configured classes for common visualizations with aesthetic defaults.
|
|
83
|
+
|
|
84
|
+
```python
|
|
85
|
+
import pandas as pd
|
|
86
|
+
from notecharts import Bar
|
|
87
|
+
|
|
88
|
+
df = pd.DataFrame({ # or a list-of-lists, list-of-dicts format
|
|
89
|
+
"Day": ["Mon", "Tue", "Wed"],
|
|
90
|
+
"Sales": [150, 230, 224]
|
|
91
|
+
})
|
|
92
|
+
|
|
93
|
+
Bar(df, x="Day", y="Sales", title="Weekly Sales", theme="dark").display()
|
|
94
|
+
```
|
|
95
|
+
|
|
96
|
+
## Important Considerations
|
|
97
|
+
|
|
98
|
+
- **Security:** Use of `JSCode` allows for arbitrary JavaScript execution in the browser/notebook context. Always ensure you are passing trusted code and data to your charts.
|
|
99
|
+
- **Connectivity:** This library is ultra-lightweight because it does not ship with the ECharts binaries. It fetches them from `cdn.jsdelivr.net` at runtime, so an active internet connection is required to render charts.
|
|
100
|
+
|
|
101
|
+
## License & Attribution
|
|
102
|
+
|
|
103
|
+
- **notecharts** is licensed under the [MIT License](LICENSE).
|
|
104
|
+
- **Apache ECharts**: This library is a wrapper for [Apache ECharts](https://echarts.apache.org/en/index.html) (incubating), which is licensed under the [Apache License 2.0](https://www.apache.org/licenses/LICENSE-2.0).
|
|
105
|
+
- *Apache ECharts, ECharts, Apache, the Apache feather, and the Apache ECharts project logo are either registered trademarks or trademarks of the Apache Software Foundation.*
|
|
106
|
+
|
|
107
|
+
## References
|
|
108
|
+
See the [ECharts gallery](https://echarts.apache.org/examples/en/index.html) for bespoke examples, or the [official docs](https://echarts.apache.org/en/option.html) for an in-depth exaplanation of the options available.
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
notecharts/__init__.py,sha256=h1VZfPx-fHwLo2l0iP9SSEe0Vci4_03tAAq5Bzlr9mM,187
|
|
2
|
+
notecharts/charts.py,sha256=eg0j1tEqpGmzWpkaliM7gCr3t87yiB0ZgCwjyQh10sk,28760
|
|
3
|
+
notecharts/widget.py,sha256=ZtVmdwLHHSv8KvA2g6htuT_Ao7SPBP0lCntmDklIfQA,11513
|
|
4
|
+
notecharts-0.1.0.dist-info/licenses/LICENSE,sha256=yANfqZOnU8lIR8tMZUb-OXpgyLGc45Ylj2bMo7tT5P8,1090
|
|
5
|
+
notecharts-0.1.0.dist-info/licenses/NOTICE,sha256=vo0eaMGEOBbYs5ItJDuBH47ICpXVkRe0bcRoDCrbj7Y,217
|
|
6
|
+
notecharts-0.1.0.dist-info/METADATA,sha256=ndjPBnTw1D3cUa4rsWkE2_8oRh7-rh6te3jAoEgFPpQ,5149
|
|
7
|
+
notecharts-0.1.0.dist-info/WHEEL,sha256=aeYiig01lYGDzBgS8HxWXOg3uV61G9ijOsup-k9o1sk,91
|
|
8
|
+
notecharts-0.1.0.dist-info/top_level.txt,sha256=3jxe7NoyPdB9lCntHLeaMWsTh-5KDCBjkQKE7C5R77o,11
|
|
9
|
+
notecharts-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Danish Munib
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
notecharts
|