-
Notifications
You must be signed in to change notification settings - Fork 0
/
d3plus.py
347 lines (290 loc) · 9.62 KB
/
d3plus.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
from IPython.core.display import display, HTML, Javascript
import json
import random
import pandas as pd
import pprint
import os
path = os.path.dirname(__file__)
def rgb2hexcolor(r, g, b):
"""Convert 3 integer r, g, b values into hexadecimal #ff00ac format color."""
return "#" + "".join("{:02x}".format(a) for a in [int(r), int(g), int(b)])
class RawJavascript(str):
"""Placeholder class that's the same as a string BUT is treated specially
by format_js_value and not quoted."""
pass
def format_js_value(thing):
if type(thing) == str:
return "'{}'".format(thing)
if type(thing) == bool:
return "{}".format(thing).lower()
if type(thing) == int:
return "{}".format(thing)
if type(thing) == int:
return "{}".format(thing)
if type(thing) == list:
return "[" + ",".join(format_js_value(x) for x in thing) + "]"
if type(thing) == dict:
return (
"{"
+ ",".join(
format_js_value(k) + ": " + format_js_value(v) for k, v in thing.items()
)
+ "}"
)
elif type(thing) == RawJavascript:
return str(thing)
else:
raise ValueError(
"""Object you passed in must either be a string or
Javascript() object."""
)
class D3PlusViz(object):
JS_LIBS = ["https://cdn.jsdelivr.net/npm/d3", "https://cdn.jsdelivr.net/npm/[email protected]/d3plus.full.min.js"]
def generate_container_id(self):
return "d3plus_div_{id}".format(id=random.randint(0, 100000))
def create_container(self):
container_id = self.generate_container_id()
container = """<div id='{id}' style='height:600px;'></div>""".format(
id=container_id
)
display(HTML(container))
return container_id
def handle_data(self, data):
if type(data) == list and len(data) > 0 and type(data[0]) == dict:
return json.dumps(data)
elif type(data) == pd.DataFrame:
return data.to_json(orient="records")
else:
raise ValueError()
def validate_data(self, data):
raise NotImplementedError()
def preprocess_data(self, data):
return data
def draw(self, data):
"""Draw a visualization in an ipython notebook."""
self.container_id = self.create_container()
data = self.preprocess_data(data)
json_data = self.handle_data(data)
display(self.generate_js(json_data))
def dump_html(self, data, container_id=None):
"""Dump a single-file self-contained html string designed to be loaded
up into the browser on its own or embedded in a page."""
data = self.preprocess_data(data)
json_data = self.handle_data(data)
html_template = """
<div id='{container_id}'></div>
{scripts}
<script>
{code}
</script>
"""
script_template = "<script src='{src}' type='text/javascript'></script>"
if container_id is None:
self.container_id = self.generate_container_id()
code = self.generate_js(json_data).data
scripts = "".join([script_template.format(src=x) for x in self.JS_LIBS])
return html_template.format(
container_id=self.container_id, scripts=scripts, code=code
)
def generate_js(self, json_data):
raise NotImplementedError()
class Treemap(D3PlusViz):
def __init__(
self, id=["group", "id"], value="value", name=None, color=None, tooltip=[]
):
super().__init__()
self.id = id
if name is None:
self.name = id
else:
self.name = name
if color is None:
if isinstance(id, list):
self.color = id[0]
else:
self.color = id
else:
self.color = color
self.value = value
self.tooltip = tooltip
def generate_js(self, json_data):
js = """
(function (){{
debugger;
var viz_data = {viz_data};
var visualization = d3plus.viz()
.legend(false)
.container({container})
.type("tree_map")
.size({{
'value': {value},
'threshold': false
}})
.id({id})
.color({color})
.text({text})
.tooltip({tooltip})
.depth(1)
.data(viz_data)
.draw();
}})();
""".format(
viz_data=json_data,
container=format_js_value("#" + self.container_id),
id=format_js_value(self.id),
value=format_js_value(self.value),
color=format_js_value(self.color),
text=format_js_value(self.name),
tooltip=format_js_value(self.tooltip),
)
return Javascript(lib=self.JS_LIBS, data=js)
class Scatterplot(D3PlusViz):
def __init__(
self, x="x", y="y", id="id", name=None, color=None, size=10, tooltip=[]
):
super().__init__()
self.id = id
self.x = x
self.y = y
if name is None:
self.name = id
else:
self.name = name
if color is None:
self.color = id
else:
self.color = color
self.size = size
self.tooltip = tooltip
def generate_js(self, json_data):
js = """
(function (){{
var viz_data = {viz_data};
var visualization = d3plus.viz()
.legend(false)
.container({container})
.data(viz_data)
.type("scatter")
.id({id})
.color({color})
.text({text})
.tooltip({tooltip})
.x({x})
.y({y})
.depth(1)
.size({size})
.draw();
}})();
""".format(
viz_data=json_data,
container=format_js_value("#" + self.container_id),
id=format_js_value(self.id),
size=format_js_value(self.size),
color=format_js_value(self.color),
text=format_js_value(self.name),
x=format_js_value(self.x),
y=format_js_value(self.y),
tooltip=format_js_value(self.tooltip),
)
return Javascript(lib=self.JS_LIBS, data=js)
class ProductSpace(D3PlusViz):
def __init__(
self,
id="id",
name=None,
color=None,
size=10,
graph_data=None,
presence="M",
spotlight=True,
tooltip=[],
node_property="nodes",
edge_property="edges",
network_id="id",
):
super().__init__()
HS_GRAPH_DATA = open(
os.path.join(
path,
"../classifications/atlas_international_product_space_hs4_codes.json",
)
).read()
SITC_GRAPH_DATA = open(
os.path.join(
path,
"../classifications/atlas_international_product_space_sitc_codes.json",
)
).read()
self.id = id
if name is None:
self.name = id
else:
self.name = name
if color is None:
self.color = id
else:
self.color = color
if graph_data is None:
self.graph_data = self.HS_GRAPH_DATA
else:
self.graph_data = graph_data
self.size = size
self.presence = presence
self.spotlight = spotlight
self.tooltip = tooltip
self.node_property = node_property
self.edge_property = edge_property
self.network_id = network_id
def preprocess_data(self, data):
return data.rename_axis({self.id: self.network_id}, axis=1)
def network_help(self):
net_obj = json.loads(self.graph_data)
nodes = net_obj[self.node_property]
edges = net_obj[self.edge_property]
print("ID key: ", self.id)
print("Network ID key: ", self.network_id)
print("Node example: \n", pprint.pformat(nodes[0]))
print("Edge example: \n", pprint.pformat(edges[0]))
print("Node values: \n", [x[self.id] for x in nodes])
def generate_js(self, json_data):
js = """
(function (){{
debugger;
var viz_data = {viz_data};
var graph_data = {graph_data};
var visualization = d3plus.viz()
.legend(false)
.labels(false)
.container({container})
.type("network")
.nodes(graph_data.{node_property})
.edges(graph_data.{edge_property})
.size({size})
.active({{
"value": function(d){{
return d.{presence} == 1;
}},
"spotlight":{spotlight}
}})
.id({id})
.color({color})
.text({text})
.tooltip({tooltip})
.data(viz_data)
.draw();
}})();
""".format(
viz_data=format_js_value(RawJavascript(json_data)),
graph_data=format_js_value(RawJavascript(self.graph_data)),
container=format_js_value("#" + self.container_id),
size=format_js_value(self.size),
id=format_js_value(self.network_id),
presence=format_js_value(RawJavascript(self.presence)),
spotlight=format_js_value(self.spotlight),
color=format_js_value(self.color),
text=format_js_value(self.name),
tooltip=format_js_value(self.tooltip),
node_property=format_js_value(RawJavascript(self.node_property)),
edge_property=format_js_value(RawJavascript(self.edge_property)),
)
return Javascript(lib=self.JS_LIBS, data=js)