Hello !

Je suis entrain de faire une CGI qui va me permettre d'afficher des courbes à partir de données récoltées.

J'utilise les libraires ipywidgets, pandas et plotly.express. Mon but est de créer une page qui affichera un graphique et qui prosera deux boutons : un pour afficher la courbe de tendance, un autre pour ré-afficher le graphique sans la courbe de tendance.

Voici mon code pour le moment ( je précie que je débute en python ) :

Code : Sélectionner tout - Visualiser dans une fenêtre à part
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
import ipywidgets as widgets
import pandas as pd
import plotly.express as px
 
####### Button 1 ########
 
button = widgets.Button(description="graph")
display(button)
 
def graph():
    df = pd.read_csv('/home/tim/Bureau/Test1.txt')
    df.head()
    fig = px.line(df, x = 'Date', y ='Total Used', title='DF command graph')
    fig.update_traces(mode='markers')
    fig.show();
 
output = widgets.Output()
 
@output.capture()
def on_button_clicked(b):
    graph()
 
button.on_click(on_button_clicked)
display(output)
 
 
####### Button 2 #########
 
button2 = widgets.Button(description='trend')
display(button2)
 
def trend():
    df = pd.read_csv('/home/tim/Bureau/Test1.txt')
    df.head()
    fig = px.scatter(df, x="Date", y="Total Used", trendline="ols")
    fig.show()
 
output2 = widgets.Output()
 
@output2.capture()
def on_button2_clicked(b):
    trend()
 
button2.on_click(on_button2_clicked)
display(output2)
 
graph()
Le résultat est celui-ci :

Nom : Screenshot from 2020-01-17 15-23-08.png
Affichages : 389
Taille : 23,0 Ko

J'ai bien mes deux boutons. Si je clique sur le bouton Graph, il m'affiche le graphique normal, mais si j'appuis sur le bouton Trend, voicil l'erreur qui s'affiche :

Code : Sélectionner tout - Visualiser dans une fenêtre à part
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
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
~/.local/lib/python3.7/site-packages/ipywidgets/widgets/widget_output.py in inner(*args, **kwargs)
    101                     self.clear_output(*clear_args, **clear_kwargs)
    102                 with self:
--> 103                     return func(*args, **kwargs)
    104             return inner
    105         return capture_decorator
 
<ipython-input-14-bc7c0aeca03e> in on_button2_clicked(b)
     40 @output2.capture()
     41 def on_button2_clicked(b):
---> 42     trend()
     43 
     44 button2.on_click(on_button2_clicked)
 
<ipython-input-14-bc7c0aeca03e> in trend()
     33     df = pd.read_csv('/home/tim/Bureau/Test1.txt')
     34     df.head()
---> 35     fig = px.scatter(df, x="Date", y="Total Used", trendline="ols")
     36     fig.show()
     37 
 
~/.local/lib/python3.7/site-packages/plotly/express/_chart_types.py in scatter(data_frame, x, y, color, symbol, size, hover_name, hover_data, custom_data, text, facet_row, facet_col, facet_col_wrap, error_x, error_x_minus, error_y, error_y_minus, animation_frame, animation_group, category_orders, labels, color_discrete_sequence, color_discrete_map, color_continuous_scale, range_color, color_continuous_midpoint, symbol_sequence, symbol_map, opacity, size_max, marginal_x, marginal_y, trendline, trendline_color_override, log_x, log_y, range_x, range_y, render_mode, title, template, width, height)
     53     mark in 2D space.
     54     """
---> 55     return make_figure(args=locals(), constructor=go.Scatter)
     56 
     57 
 
~/.local/lib/python3.7/site-packages/plotly/express/_core.py in make_figure(args, constructor, trace_patch, layout_patch)
   1315 
   1316             patch, fit_results = make_trace_kwargs(
-> 1317                 args, trace_spec, group, mapping_labels.copy(), sizeref
   1318             )
   1319             trace.update(patch)
 
~/.local/lib/python3.7/site-packages/plotly/express/_core.py in make_trace_kwargs(args, trace_spec, g, mapping_labels, sizeref)
    234                         hover_header = "<b>LOWESS trendline</b><br><br>"
    235                     elif v == "ols":
--> 236                         fit_results = sm.OLS(y.values, sm.add_constant(x.values)).fit()
    237                         result["y"] = fit_results.predict()
    238                         hover_header = "<b>OLS trendline</b><br>"
 
~/.local/lib/python3.7/site-packages/statsmodels/tools/tools.py in add_constant(data, prepend, has_constant)
    303         raise ValueError('Only implementd 2-dimensional arrays')
    304 
--> 305     is_nonzero_const = np.ptp(x, axis=0) == 0
    306     is_nonzero_const &= np.all(x != 0.0, axis=0)
    307     if is_nonzero_const.any():
 
<__array_function__ internals> in ptp(*args, **kwargs)
 
~/.local/lib/python3.7/site-packages/numpy/core/fromnumeric.py in ptp(a, axis, out, keepdims)
   2541         else:
   2542             return ptp(axis=axis, out=out, **kwargs)
-> 2543     return _methods._ptp(a, axis=axis, out=out, **kwargs)
   2544 
   2545 
 
~/.local/lib/python3.7/site-packages/numpy/core/_methods.py in _ptp(a, axis, out, keepdims)
    230         umr_maximum(a, axis, None, out, keepdims),
    231         umr_minimum(a, axis, None, None, keepdims),
--> 232         out
    233     )
    234 
 
TypeError: unsupported operand type(s) for -: 'str' and 'str'
Je me suis inspiré de ce bout de code pour le faire :

Code : Sélectionner tout - Visualiser dans une fenêtre à part
1
2
3
4
5
import plotly.express as px
 
df = px.data.tips()
fig = px.scatter(df, x="total_bill", y="tip", trendline="ols")
fig.show()

Mais apparemment, ça ne fonctionne pas... Sauriez-vous me dire pourquoi ?


Merci d'avance !