-
-
Notifications
You must be signed in to change notification settings - Fork 324
/
Copy pathmatplotlib_plot.py
85 lines (62 loc) · 2.01 KB
/
matplotlib_plot.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
from io import BytesIO
import matplotlib.pyplot as plt
import idom
from idom.widgets import image
@idom.component
def PolynomialPlot():
coefficients, set_coefficients = idom.hooks.use_state([0])
x = [n for n in linspace(-1, 1, 50)]
y = [polynomial(value, coefficients) for value in x]
return idom.html.div(
plot(f"{len(coefficients)} Term Polynomial", x, y),
ExpandableNumberInputs(coefficients, set_coefficients),
)
@idom.component
def ExpandableNumberInputs(values, set_values):
inputs = []
for i in range(len(values)):
def set_value_at_index(event, index=i):
new_value = float(event["target"]["value"] or 0)
set_values(values[:index] + [new_value] + values[index + 1 :])
inputs.append(poly_coef_input(i + 1, set_value_at_index))
def add_input():
set_values(values + [0])
def del_input():
set_values(values[:-1])
return idom.html.div(
idom.html.div(
"add/remove term:",
idom.html.button({"on_click": lambda event: add_input()}, "+"),
idom.html.button({"on_click": lambda event: del_input()}, "-"),
),
inputs,
)
def plot(title, x, y):
fig, axes = plt.subplots()
axes.plot(x, y)
axes.set_title(title)
buffer = BytesIO()
fig.savefig(buffer, format="png")
plt.close(fig)
return image("png", buffer.getvalue())
def poly_coef_input(index, callback):
return idom.html.div(
{"style": {"margin-top": "5px"}, "key": index},
idom.html.label(
"C",
idom.html.sub(index),
" × X",
idom.html.sup(index),
),
idom.html.input({"type": "number", "on_change": callback}),
)
def polynomial(x, coefficients):
return sum(c * (x ** (i + 1)) for i, c in enumerate(coefficients))
def linspace(start, stop, n):
if n == 1:
yield stop
return
h = (stop - start) / (n - 1)
for i in range(n):
yield start + h * i
idom.run(PolynomialPlot)