Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Plotly

import plotly.graph_objects as go
import numpy as np

Plotly

Graph Objects : low-level interface

Simple example

x = np.linspace(0, 4*np.pi, 500)

fig = go.Figure(go.Scatter(x=x, y=np.sin(x)))
fig.show()
Loading...

Multiple plots on same figure

x = np.linspace(0, 4*np.pi, 500)

fig = go.Figure()
fig.add_trace(go.Scatter(x=x, y=np.sin(x), name='sin(x)'))
fig.add_trace(go.Scatter(x=x, y=np.cos(x), name='cos(x)'))
fig.show()
Loading...

Subplots

from plotly.subplots import make_subplots

x = np.linspace(0, 4*np.pi, 100)

fig = make_subplots(rows=2, cols=1)

fig.add_trace(go.Scatter(x=x, y=np.sin(x), name='sin(x)'), row=1, col=1)
fig.add_trace(go.Scatter(x=x, y=np.cos(x), name='cos(x)'), row=2, col=1)
fig.show()
Loading...

Slider using the visible attribute of traces

x = np.linspace(0, 1, 1000)

f = np.linspace(1, 16, 16)

fig = go.Figure()

# Add invisible traces, one for each slider step
for i, fi in enumerate(f):
    fig.add_trace(go.Scatter(visible=False, x=x, y=np.sin(2*np.pi*fi*x), name=f"f={fi}"))

# Make first trace visible
fig.data[0].visible = True

# Create and add slider
steps = []
for i, fi in enumerate(f):
    args = [{"visible": [(el==i) for el in range(len(fig.data))]}]
    step = dict(method="update", label = f"{fi}", args=args)
    steps.append(step)
sliders = [dict(currentvalue={'prefix': 'Frequency  f = '}, steps=steps)]

fig.update_layout(sliders=sliders, title = 'f(x) = sin(2 pi f x)')
fig.show()
Loading...

Slider (another way)

x = np.linspace(0, 1, 1000)

f = np.linspace(1, 16, 16)

fig = go.Figure()
fig.add_trace(go.Scatter(x=x, y=np.sin(2*np.pi*x), name='sin(x)'))

# Create and add slider
steps = []
for fi in f:
    args = [{"y": [np.sin(2*np.pi*fi*x)]}]
    step = dict(method="update", label=f"{fi}", args=[{"y": [np.sin(2*np.pi*fi*x)]}])
    steps.append(step)
sliders = [dict(currentvalue={'prefix': 'Frequency  f = '}, steps=steps)]

fig.update_layout(sliders=sliders)
#print(fig)
fig.show()
Loading...

Slider on subplots

x = np.linspace(0, 1, 500)

f = np.linspace(1, 16, 16)

fig = make_subplots(rows=2, cols=1)

fig.add_trace(go.Scatter(x=x, y=np.sin(2*np.pi*x), name='sin(x)'), row=1, col=1)
fig.add_trace(go.Scatter(x=x, y=np.cos(2*np.pi*x), name='cos(x)'), row=2, col=1)

# Create and add slider
steps = []
for fi in f:
    args = [{"y": [np.sin(2*np.pi*fi*x), np.cos(2*np.pi*fi*x)]}]
    step = dict(method="update", label = f"{fi}", args=[{"x": [x, x], "y": [np.sin(2*np.pi*fi*x), np.cos(2*np.pi*fi*x)]}])
    steps.append(step)
sliders = [dict(currentvalue={'prefix': 'Frequency  f = '}, steps=steps)]

fig.update_layout(sliders=sliders, height=500, title = 'Slider on subplots')
fig.show()
Loading...

Custom buttons

x = np.linspace(0, 3*np.pi, 100)

fig = go.Figure(go.Scatter(x=x, y=np.sin(x), line=dict(dash='dash')))

buttons=[dict(label="sin", method="update", args=[{"y": [np.sin(x)]}, {"title": "f(x) = sin(2 pi f x)"}]),
         dict(label="cos", method="update", args=[{"y": [np.cos(x)]}, {"title": "f(x) = cos(2 pi f x)"}])]

fig.update_layout(updatemenus=[dict(type="buttons", direction="down", buttons=buttons)], title = 'f(x) = sin(2 pi f x)')

fig.show()
Loading...

Animation (play and stop button)

def gaussian(x):
    return  np.exp(-50*(x+0.5)*(x+0.5))

x = np.linspace(-1, 1, 200)

a = 0.5

frames = [go.Frame(data=[go.Scatter(x=x, y=gaussian(x-a*t))]) for t in np.arange(0.0, 2.1, 0.1)]

fig = go.Figure()

fig.add_trace(go.Scatter(x=x, y=gaussian(x)))

animate_opts = dict(fromcurrent=True, frame={"duration": 100})
       
buttons=[dict(label="▶", method="animate", args=[None, animate_opts]),
         dict(label="◼", method="animate", args=[[None], dict(mode="immediate")])]

fig.update_layout(updatemenus=[dict(type="buttons", buttons=buttons)], title='Linear 1D advection equation')
fig.update(frames=frames)

fig.show()
Loading...

Animation and sliders

def gaussian(x):
    return  np.exp(-50*(x+0.5)*(x+0.5))

x = np.linspace(-1, 1, 1000)

a = 0.5
frames = [go.Frame(data=[go.Scatter(x=x, y=gaussian(x-a*t))], name=f"{t:.1f}") for t in np.arange(0.0, 2.0, 0.1)]

fig = go.Figure()

fig.add_trace(go.Scatter(x=x, y=gaussian(x)))

steps=[]    
for t in np.arange(0.0, 1.6, 0.1):
    name = f"{t:.1f}"
    step = dict(method="animate", label = name, 
                args=[[name], {"frame": {"redraw": False, "duration": 100}, 
                               "mode": "immediate",
                               "transition": {"duration": 300}}])
    steps.append(step)
    
animate_opts = dict(fromcurrent=True, frame={"duration": 100})
       
buttons=[dict(label="▶", method="animate", args=[None, animate_opts]),
         dict(label="◼", method="animate", args=[[None], dict(mode="immediate")])]
    
sliders = [dict(currentvalue={'prefix': 't = '}, active=0, visible=True, steps=steps)]

fig.update(frames=frames)
fig.update_layout(sliders=sliders, updatemenus=[dict(type="buttons", buttons=buttons)], title='Linear 1D advection equation')

fig.show()
Loading...

Theme, color, style ...

Theme

x = np.linspace(0, 4*np.pi, 500)

fig = go.Figure()

fig.add_trace(go.Scatter(x=x, y=np.sin(x), name='sin(x)'))
fig.add_trace(go.Scatter(x=x, y=np.cos(x), name='cos(x)'))

fig.update_layout(template='seaborn')

fig.show()
Loading...

Specify default theme

import plotly.io as pio
pio.templates.default = "seaborn"
from plotly import colors

x = np.linspace(0, 4*np.pi, 500)
fig = go.Figure()
fig.add_trace(go.Scatter(x=x, y=np.sin(x), name='sin(x)'))
fig.add_trace(go.Scatter(x=x, y=np.cos(x), name='cos(x)'))
Loading...

Marker style

x = np.linspace(0, 4*np.pi, 500)

fig = go.Figure()

marker01=dict(size=5, symbol='x-thin', line=dict(width=2, color='rgb(76,114,176)'))
marker02=dict(size=5, symbol='x-thin', line=dict(width=1, color='rgb(221,132,82)'))
marker03=dict(size=5, symbol='x')
marker04=dict(symbol='x', maxdisplayed=x.size/5)
marker05=dict(symbol='x-thin', line=dict(width=2), maxdisplayed=x.size/5)

fig.add_trace(go.Scatter(x=x, y=np.sin(x),   mode='markers', marker=marker01, name='sin(x)'))
fig.add_trace(go.Scatter(x=x, y=np.cos(x),   mode='markers', marker=marker02, name='cos(x)'))
fig.add_trace(go.Scatter(x=x, y=np.cos(x+1), mode='markers', marker=marker03, name='cos(x+1)'))
fig.add_trace(go.Scatter(x=x, y=np.cos(x-1), mode='markers', marker=marker04, name='cos(x-1)'))
fig.add_trace(go.Scatter(x=x, y=np.cos(x-2), mode='markers', marker=marker05, name='cos(x-2)'))
fig.show()
Loading...
x = np.linspace(0, 4*np.pi, 500)

fig = go.Figure()

for i in range(11):
    fig.add_trace(go.Scatter(x=x, y=np.sin(x+i)))
fig.show()
Loading...

Color

# default color 
import plotly.express as px
color = px.colors.qualitative.Plotly

max_color_displayed = 10

x = np.arange(max_color_displayed)
y = np.ones(max_color_displayed)

fig = go.Figure([go.Bar(x=x, y=y, marker_color=color)])
#fig = go.Figure([go.Bar(x=x, y=y, marker_color=color)])
fig.show()
Loading...
from plotly import colors

color = colors.DEFAULT_PLOTLY_COLORS

max_color_displayed = 10

x = np.arange(max_color_displayed)
y = np.ones(max_color_displayed)

fig = go.Figure([go.Bar(x=x, y=y, marker_color=color)])
fig.show()
Loading...
# seaborn theme color

max_color_displayed = 10

x = np.arange(max_color_displayed)
y = np.ones(max_color_displayed)

fig = go.Figure()
fig.layout.template = 'seaborn'
color = fig.layout.template.layout.colorway
print(color)

fig.add_trace(go.Bar(x=x, y=y, marker_color=color))
fig.show()
('rgb(76,114,176)', 'rgb(221,132,82)', 'rgb(85,168,104)', 'rgb(196,78,82)', 'rgb(129,114,179)', 'rgb(147,120,96)', 'rgb(218,139,195)', 'rgb(140,140,140)', 'rgb(204,185,116)', 'rgb(100,181,205)')
Loading...