PlotlyΒΆ

Examples of visualizing plotly plots in Viser.

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