11. Graph interaction (updatemenus)

This Python script creates an interactive Plotly scatter plot with buttons that allow a user to dynamically change the colors of the plotted points.

Note

How to include buttons in the graph using update menus

13 import plotly
14 import plotly.graph_objs as go
15
16 from plotly.io import show
17
18 try:
19     __file__
20     TERMINAL = True
21 except:
22     TERMINAL = False
23
24
25 def get_color_set(color_set_id):
26     """Get color set."""
27     if color_set_id == 1:
28         marker_color = ['red', 'green', 'blue']
29     elif color_set_id == 2:
30         marker_color = ['black', 'blue', 'red']
31     return [{'marker.color': [marker_color]}];
32
33
34 # Define trace
35 trace = go.Scatter(
36     x=[0,1,1],
37     y=[1,0,1],
38     marker=dict(color=['green','black','red']),
39     mode='markers'
40 )
41
42 # Define updatemenus
43 updatemenus=list([
44     dict(
45         buttons=list([
46             dict(label = 'Color Set 1',
47                  method = 'update',
48                  args=get_color_set(1)
49             ),
50             dict(label = 'Color Set 2',
51                  method = 'update',
52                  args=get_color_set(2)
53             ),
54         ]),
55         direction = 'left',
56         pad = {'r': 10, 't': 10},
57         showactive = True,
58         type = 'buttons',
59         x = 0.1,
60         xanchor = 'left',
61         y = 1.1,
62         yanchor = 'top'
63     )
64 ])
65
66 # Define layout
67 layout = go.Layout(
68     title='Scatter Color Switcher',
69     updatemenus = updatemenus
70 )
71
72 # Create Figure
73 fig = go.Figure(data=[trace], layout=layout)
74
75 # ----------------------------
76 # Save
77 # ----------------------------
78 # Libraries
79 import time
80 from pathlib import Path
81
82 # Define pipeline path
83 path = Path('./objects') / 'plot_main11_updatemenus'
84 filename = '%s.html' % time.strftime("%Y%m%d-%H%M%S")
85
86 # Create folder (if it does not exist)
87 path.mkdir(parents=True, exist_ok=True)
88
89 # Save
90 fig.write_html("%s/%s" % (path, filename))
91
92 # Show
93 show(fig)

Total running time of the script: ( 0 minutes 1.710 seconds)

Gallery generated by Sphinx-Gallery