-
Notifications
You must be signed in to change notification settings - Fork 2
/
patches.py
63 lines (51 loc) · 1.73 KB
/
patches.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
import builtins
oldimport = builtins.__import__
patches_complete = []
def patch_save_fig():
from matplotlib.figure import Figure
from js import document
if "savefig" not in patches_complete:
original_savefig = Figure.savefig
def savefig(fig, id, *a, **kw):
import os
import base64
el = document.getElementById(id)
if el is None:
el = document.createElement("div")
document.body.append(el)
original_savefig(fig, "temp.png", *a, **kw)
with open("temp.png", "rb") as image_file:
encoded_string = base64.b64encode(image_file.read()).decode()
os.remove("temp.png")
src = "data:image/png;charset=utf-8;base64," + encoded_string
if id:
el = document.getElementById(id)
if el is None:
el = document.createElement("img")
el.id = id
document.body.append(el)
el.src = src
return src
Figure.savefig = savefig
patches_complete.append("savefig")
def patch_plot():
if "plot" not in patches_complete:
import matplotlib
patch_save_fig()
original_plot = matplotlib.pyplot.plot
def plot(*a, id="mpl", **kw):
r = original_plot(*a, **kw)
fig = matplotlib.pyplot.gcf()
fig.savefig(id)
return r
matplotlib.pyplot.plot = plot
patches_complete.append("plot")
patches = {
"matplotlib.pyplot": patch_plot
}
def newimport(*a, **kw):
r = oldimport(*a, **kw)
if len(a) and a[0] in patches:
patches[a[0]]()
return r
builtins.__import__ = newimport