Plotly.#
Examples of visualizing plotly plots in Viser.
1import time
2
3import numpy as onp
4import plotly.express as px
5import plotly.graph_objects as go
6import viser
7from PIL import Image
8
9
10def create_sinusoidal_wave(t: float) -> go.Figure:
11 """Create a sinusoidal wave plot, starting at time t."""
12 x_data = onp.linspace(t, t + 6 * onp.pi, 50)
13 y_data = onp.sin(x_data) * 10
14
15 fig = px.line(
16 x=list(x_data),
17 y=list(y_data),
18 labels={"x": "x", "y": "sin(x)"},
19 title="Sinusoidal Wave",
20 )
21
22 # this sets the margins to be tight around the title.
23 fig.layout.title.automargin = True # type: ignore
24 fig.update_layout(
25 margin=dict(l=20, r=20, t=20, b=20),
26 ) # Reduce plot margins.
27
28 return fig
29
30
31def main() -> None:
32 server = viser.ViserServer()
33
34 # Plot type 1: Line plot.
35 line_plot_time = 0.0
36 line_plot = server.add_gui_plotly(figure=create_sinusoidal_wave(line_plot_time))
37
38 # Plot type 2: Image plot.
39 fig = px.imshow(Image.open("assets/Cal_logo.png"))
40 fig.update_layout(
41 margin=dict(l=20, r=20, t=20, b=20),
42 )
43 server.add_gui_plotly(figure=fig, aspect=1.0)
44
45 # Plot type 3: 3D Scatter plot.
46 fig = px.scatter_3d(
47 px.data.iris(),
48 x="sepal_length",
49 y="sepal_width",
50 z="petal_width",
51 color="species",
52 )
53 fig.update_layout(legend=dict(yanchor="top", y=0.99, xanchor="left", x=0.01))
54 fig.update_layout(
55 margin=dict(l=20, r=20, t=20, b=20),
56 )
57 server.add_gui_plotly(figure=fig, aspect=1.0)
58
59 while True:
60 # Update the line plot.
61 line_plot_time += 0.1
62 line_plot.figure = create_sinusoidal_wave(line_plot_time)
63
64 time.sleep(0.01)
65
66
67if __name__ == "__main__":
68 main()