Debian Codegraph @

examples/DataGrid.ipynb

raw
1 {
2 "cells": [
3 {
4 "cell_type": "markdown",
5 "metadata": {},
6 "source": [
7 "# ipydatagrid"
8 ]
9 },
10 {
11 "cell_type": "code",
12 "execution_count": null,
13 "metadata": {},
14 "outputs": [],
15 "source": [
16 "from ipydatagrid import DataGrid, TextRenderer, BarRenderer, Expr, ImageRenderer"
17 ]
18 },
19 {
20 "cell_type": "code",
21 "execution_count": null,
22 "metadata": {},
23 "outputs": [],
24 "source": [
25 "from json import load\n",
26 "import pandas as pd\n",
27 "\n",
28 "with open(\"./cars.json\") as fobj:\n",
29 " data = load(fobj)\n",
30 "df = pd.DataFrame(data[\"data\"]).set_index(\"index\")\n",
31 "df = df[sorted(df.columns)]"
32 ]
33 },
34 {
35 "cell_type": "markdown",
36 "metadata": {},
37 "source": [
38 "## Custom cell renderers\n",
39 "\n",
40 "Custom cell renderers can be defined for the entire grid or column-wise.\n",
41 "\n",
42 "Two types of cell renderers are currently available: `TextRenderer` and `BarRenderer`.\n",
43 "\n",
44 "Most of the `TextRenderer`/`BarRenderer` attributes (`background_color`, `text_color` etc.) can either be a __value__, a __bqplot scale__ or a __`VegaExpr`__ or __`Expr`__ instance.\n",
45 "\n",
46 "\n",
47 "### Vega expressions\n",
48 "The `VegaExpr` class allows you to define an attribute value as a result of a Vega-expression (see https://vega.github.io/vega/docs/expressions/). _e.g._ `background_color = VegaExpr(\"value < 150 ? 'red' : 'green'\")`.\n",
49 " \n",
50 "You can look at the vega-expression documentation for more information about available constants and functions. In the scope of the expression are also available: `value`: cell value, `x` and `y`: cell position in pixel, `width` and `height` of the cell, `row` and `column`: cell position.\n",
51 "\n",
52 "### Python expressions\n",
53 "If you prefer writing those expressions in Python, we provide an `Expr` class which takes a Python expression as input string or a Python function, and generates the equivalent vega-expression for you using [py2vega](https://github.com/QuantStack/py2vega)."
54 ]
55 },
56 {
57 "cell_type": "code",
58 "execution_count": null,
59 "metadata": {},
60 "outputs": [],
61 "source": [
62 "from bqplot import LinearScale, ColorScale, OrdinalColorScale, OrdinalScale\n",
63 "from py2vega.functions.color import rgb\n",
64 "\n",
65 "\n",
66 "def horsepower_coloring(cell):\n",
67 " if cell.value < 100:\n",
68 " return \"red\"\n",
69 " elif cell.value < 150:\n",
70 " return \"orange\"\n",
71 " else:\n",
72 " return \"green\"\n",
73 "\n",
74 "\n",
75 "def weight_coloring(cell):\n",
76 " scaled_value = 1 if cell.value > 4500 else cell.value / 4500\n",
77 " color_value = scaled_value * 255\n",
78 "\n",
79 " return rgb(color_value, 0, 0)\n",
80 "\n",
81 "\n",
82 "renderers = {\n",
83 " \"Acceleration\": BarRenderer(\n",
84 " horizontal_alignment=\"center\",\n",
85 " bar_color=ColorScale(min=0, max=20, scheme=\"viridis\"),\n",
86 " bar_value=LinearScale(min=0, max=20),\n",
87 " ),\n",
88 " \"Cylinders\": TextRenderer(\n",
89 " background_color=Expr('\"grey\" if cell.row % 2 else default_value')\n",
90 " ),\n",
91 " \"Displacement\": TextRenderer(\n",
92 " text_color=ColorScale(min=97, max=455),\n",
93 " font=Expr(\n",
94 " \"'16px sans-serif' if cell.value > 400 else '12px sans-serif'\"\n",
95 " ),\n",
96 " ),\n",
97 " \"Horsepower\": TextRenderer(\n",
98 " text_color=\"black\", background_color=Expr(horsepower_coloring)\n",
99 " ),\n",
100 " \"Miles_per_Gallon\": TextRenderer(\n",
101 " background_color=Expr('\"grey\" if cell.value is None else default_value')\n",
102 " ),\n",
103 " \"Name\": TextRenderer(\n",
104 " background_color=Expr(\n",
105 " 'rgb(0, 100, 255) if \"chevrolet\" in cell.value or \"ford\" in cell.value else default_value'\n",
106 " )\n",
107 " ),\n",
108 " \"Origin\": TextRenderer(\n",
109 " text_color=\"black\",\n",
110 " background_color=OrdinalColorScale(domain=[\"USA\", \"Japan\", \"Europe\"]),\n",
111 " horizontal_alignment=Expr(\n",
112 " \"'right' if cell.value in ['USA', 'Japan'] else 'left'\"\n",
113 " ),\n",
114 " ),\n",
115 " \"Weight_in_lbs\": TextRenderer(\n",
116 " text_color=\"black\", background_color=Expr(weight_coloring)\n",
117 " ),\n",
118 " \"Year\": TextRenderer(text_color=\"black\", background_color=\"green\"),\n",
119 " \"Image\": ImageRenderer(),\n",
120 "}\n",
121 "\n",
122 "datagrid = DataGrid(\n",
123 " df, base_row_size=124, base_column_size=250, renderers=renderers\n",
124 ")\n",
125 "datagrid"
126 ]
127 },
128 {
129 "cell_type": "code",
130 "execution_count": null,
131 "metadata": {},
132 "outputs": [],
133 "source": [
134 "renderers[\n",
135 " \"Name\"\n",
136 "].background_color.value = '\"green\" if \"pontiac\" in cell.value or \"citroen\" in cell.value else default_value'"
137 ]
138 },
139 {
140 "cell_type": "code",
141 "execution_count": null,
142 "metadata": {},
143 "outputs": [],
144 "source": [
145 "renderers[\"Year\"].background_color = \"yellow\""
146 ]
147 },
148 {
149 "cell_type": "code",
150 "execution_count": null,
151 "metadata": {},
152 "outputs": [],
153 "source": [
154 "datagrid.transform(\n",
155 " [\n",
156 " {\n",
157 " \"type\": \"filter\",\n",
158 " \"operator\": \"=\",\n",
159 " \"column\": \"Origin\",\n",
160 " \"value\": \"Europe\",\n",
161 " },\n",
162 " {\"type\": \"sort\", \"column\": \"Horsepower\", \"desc\": True},\n",
163 " ]\n",
164 ")"
165 ]
166 },
167 {
168 "cell_type": "code",
169 "execution_count": null,
170 "metadata": {},
171 "outputs": [],
172 "source": [
173 "datagrid.revert()"
174 ]
175 },
176 {
177 "cell_type": "code",
178 "execution_count": null,
179 "metadata": {},
180 "outputs": [],
181 "source": [
182 "datagrid.transform(\n",
183 " [\n",
184 " {\"type\": \"filter\", \"operator\": \"=\", \"column\": \"Origin\", \"value\": \"USA\"},\n",
185 " {\"type\": \"filter\", \"operator\": \"<\", \"column\": \"Horsepower\", \"value\": 130},\n",
186 " {\"type\": \"sort\", \"column\": \"Acceleration\"},\n",
187 " ]\n",
188 ")"
189 ]
190 },
191 {
192 "cell_type": "markdown",
193 "metadata": {},
194 "source": [
195 "# Performance test: A million cells with ipydatagrid"
196 ]
197 },
198 {
199 "cell_type": "code",
200 "execution_count": null,
201 "metadata": {},
202 "outputs": [],
203 "source": [
204 "from random import uniform\n",
205 "\n",
206 "\n",
207 "def create_random_data(n_rows=100, n_columns=100):\n",
208 " data = {\"data\": [], \"schema\": {}}\n",
209 "\n",
210 " data[\"data\"] = [\n",
211 " [uniform(0, 1) for c in range(n_columns)] for r in range(n_rows)\n",
212 " ]\n",
213 " data[\"schema\"][\"fields\"] = [\n",
214 " {\"name\": str(c), type: \"number\"} for c in range(n_columns)\n",
215 " ]\n",
216 "\n",
217 " return data\n",
218 "\n",
219 "\n",
220 "def update_random_data(old_data):\n",
221 " data = {\"data\": [], \"schema\": {}}\n",
222 "\n",
223 " n_columns = len(old_data[\"data\"])\n",
224 " n_rows = len(old_data[\"data\"][0])\n",
225 "\n",
226 " data[\"data\"] = [\n",
227 " [uniform(-0.1, 0.1) + old_data[\"data\"][r][c] for c in range(n_columns)]\n",
228 " for r in range(n_rows)\n",
229 " ]\n",
230 " data[\"schema\"][\"fields\"] = [\n",
231 " {\"name\": str(c), type: \"number\"} for c in range(n_columns)\n",
232 " ]\n",
233 "\n",
234 " return data"
235 ]
236 },
237 {
238 "cell_type": "code",
239 "execution_count": null,
240 "metadata": {},
241 "outputs": [],
242 "source": [
243 "from py2vega.constants import SQRT1_2\n",
244 "\n",
245 "huge_data = create_random_data(1000, 1000)\n",
246 "\n",
247 "\n",
248 "def renderer_function(cell, default_value):\n",
249 " return \"#fc8403\" if cell.value < SQRT1_2 else default_value\n",
250 "\n",
251 "\n",
252 "conditional_expression = Expr(renderer_function)\n",
253 "\n",
254 "default_renderer = TextRenderer(\n",
255 " background_color=conditional_expression, format=\".3f\"\n",
256 ")\n",
257 "\n",
258 "huge_df = pd.DataFrame(huge_data[\"data\"])\n",
259 "\n",
260 "conditional_huge_datagrid = DataGrid(huge_df, default_renderer=default_renderer)\n",
261 "conditional_huge_datagrid"
262 ]
263 },
264 {
265 "cell_type": "code",
266 "execution_count": null,
267 "metadata": {},
268 "outputs": [],
269 "source": [
270 "from ipywidgets import FloatSlider, Dropdown, ColorPicker, HBox, VBox\n",
271 "\n",
272 "operator_dropdown = Dropdown(options=[\"<\", \">\"], value=\"<\")\n",
273 "reference_slider = FloatSlider(value=0.5, min=0, max=1)\n",
274 "output_colorpicker = ColorPicker(value=\"#fc8403\")\n",
275 "\n",
276 "\n",
277 "def on_change(*args, **kwargs):\n",
278 " conditional_expression.value = \"'{color}' if cell.value {operator} {reference} else default_value\".format(\n",
279 " operator=operator_dropdown.value,\n",
280 " reference=reference_slider.value,\n",
281 " color=output_colorpicker.value,\n",
282 " )\n",
283 "\n",
284 "\n",
285 "operator_dropdown.observe(on_change, \"value\")\n",
286 "reference_slider.observe(on_change, \"value\")\n",
287 "output_colorpicker.observe(on_change, \"value\")\n",
288 "\n",
289 "hbox = HBox((operator_dropdown, reference_slider, output_colorpicker))\n",
290 "VBox([conditional_huge_datagrid, hbox])"
291 ]
292 },
293 {
294 "cell_type": "markdown",
295 "metadata": {},
296 "source": [
297 "## Bar renderer"
298 ]
299 },
300 {
301 "cell_type": "code",
302 "execution_count": null,
303 "metadata": {},
304 "outputs": [],
305 "source": [
306 "from bqplot import LinearScale, ColorScale\n",
307 "from ipydatagrid import DataGrid, BarRenderer\n",
308 "\n",
309 "linear_scale = LinearScale(min=0, max=1)\n",
310 "color_scale = ColorScale(min=0, max=1)\n",
311 "bar_renderer = BarRenderer(\n",
312 " bar_color=color_scale,\n",
313 " bar_value=linear_scale,\n",
314 " bar_horizontal_alignment=\"center\",\n",
315 " show_text=False,\n",
316 ")\n",
317 "\n",
318 "huge_df2 = pd.DataFrame(create_random_data()[\"data\"])\n",
319 "\n",
320 "huge_datagrid = DataGrid(huge_df2, default_renderer=bar_renderer)"
321 ]
322 },
323 {
324 "cell_type": "code",
325 "execution_count": null,
326 "metadata": {},
327 "outputs": [],
328 "source": [
329 "huge_datagrid"
330 ]
331 },
332 {
333 "cell_type": "code",
334 "execution_count": null,
335 "metadata": {},
336 "outputs": [],
337 "source": [
338 "from ipywidgets import FloatSlider, link\n",
339 "\n",
340 "slider = FloatSlider(\n",
341 " description=\"Scale: \", value=linear_scale.max, min=0, max=1, step=0.01\n",
342 ")\n",
343 "link((color_scale, \"min\"), (slider, \"value\"))\n",
344 "link((linear_scale, \"min\"), (slider, \"value\"))\n",
345 "\n",
346 "slider"
347 ]
348 },
349 {
350 "cell_type": "code",
351 "execution_count": null,
352 "metadata": {},
353 "outputs": [],
354 "source": [
355 "color_scale.scheme = \"magma\""
356 ]
357 }
358 ],
359 "metadata": {
360 "kernelspec": {
361 "display_name": "Python 3 (ipykernel)",
362 "language": "python",
363 "name": "python3"
364 },
365 "language_info": {
366 "codemirror_mode": {
367 "name": "ipython",
368 "version": 3
369 },
370 "file_extension": ".py",
371 "mimetype": "text/x-python",
372 "name": "python",
373 "nbconvert_exporter": "python",
374 "pygments_lexer": "ipython3",
375 "version": "3.12.3"
376 }
377 },
378 "nbformat": 4,
379 "nbformat_minor": 4
380 }