Plotly

Plotly is a graphing library that can be used to create interactive graphs. Use the rx.plotly component to wrap Plotly as a component for use in your web page. Checkout Plotly for more information.

When integrating Plotly graphs into your UI code, note that the method for displaying the graph differs from a regular Python script. Instead of using fig.show(), use rx.plotly(data=fig) within your UI code to ensure the graph is properly rendered and displayed within the user interface

Basic Example

Let's create a line graph of life expectancy in Canada.

import plotly.express as px

df = px.data.gapminder().query("country=='Canada'")
fig = px.line(
    df,
    x="year",
    y="lifeExp",
    title="Life expectancy in Canada",
)


def line_chart():
    return rx.center(
        rx.plotly(data=fig),
    )

3D graphing example

Let's create a 3D surface plot of Mount Bruno. This is a slightly more complicated example, but it wraps in Reflex using the same method. In fact, you can wrap any figure using the same approach.

import plotly.graph_objects as go
import pandas as pd

# Read data from a csv
z_data = pd.read_csv(
    "https://raw.githubusercontent.com/plotly/datasets/master/api_docs/mt_bruno_elevation.csv"
)

fig = go.Figure(data=[go.Surface(z=z_data.values)])
fig.update_traces(
    contours_z=dict(
        show=True,
        usecolormap=True,
        highlightcolor="limegreen",
        project_z=True,
    )
)
fig.update_layout(
    scene_camera_eye=dict(x=1.87, y=0.88, z=-0.64),
    margin=dict(l=65, r=50, b=65, t=90),
)


def mountain_surface():
    return rx.center(
        rx.plotly(data=fig),
    )

Plot as State Var

If the figure is set as a state var, it can be updated during run time.

import plotly.express as px


class PlotlyState(rx.State):
    df = px.data.gapminder().query(f"country=='Canada'")
    figure = px.line(
        df,
        x="year",
        y="lifeExp",
        title="Life expectancy in Canada",
    )

    def set_selected_country(self, country):
        self.df = px.data.gapminder().query(
            f"country=='{country}'"
        )
        self.figure = px.line(
            self.df,
            x="year",
            y="lifeExp",
            title=f"Life expectancy in {country}",
        )


def line_chart_with_state():
    return rx.vstack(
        rx.select(
            [
                "China",
                "France",
                "United Kingdom",
                "United States",
                "Canada",
            ],
            default_value="Canada",
            on_change=PlotlyState.set_selected_country,
        ),
        rx.plotly(data=PlotlyState.figure),
    )

Adding Styles and Layouts

Use update_layout() method to update the layout of your chart. Checkout Plotly Layouts for all layouts props.

df = px.data.gapminder().query("country=='Canada'")
fig_1 = px.line(
    df,
    x="year",
    y="lifeExp",
    title="Life expectancy in Canada",
)
fig_1.update_layout(
    title_x=0.5,
    plot_bgcolor="#c3d7f7",
    paper_bgcolor="rgba(128, 128, 128, 0.1)",
    showlegend=True,
    title_font_family="Open Sans",
    title_font_size=25,
)


def add_styles():
    return rx.center(
        rx.plotly(data=fig_1),
        width="100%",
        height="100%",
    )

API Reference

rx.plotly

Display a plotly graph.

PropType | ValuesDefault
data
Figure
layout
Dict[Any, Any]
template
Template
config
Dict[Any, Any]
use_resize_handler
bool
LiteralVar.create(True)

Event Triggers

See the full list of default event triggers
TriggerDescription
on_click Fired when the plot is clicked.
on_double_click Fired when the plot is double clicked.
on_after_plot Fired after the plot is redrawn.
on_animated Fired after the plot was animated.
on_animating_frame Fired while animating a single frame (does not currently pass data through).
on_animation_interrupted Fired when an animation is interrupted (to start a new animation for example).
on_autosize Fired when the plot is responsively sized.
on_before_hover Fired whenever mouse moves over a plot.
on_button_clicked Fired when a plotly UI button is clicked.
on_deselect Fired when a selection is cleared (via double click).
on_hover Fired when a plot element is hovered over.
on_relayout Fired after the plot is layed out (zoom, pan, etc).
on_relayouting Fired while the plot is being layed out.
on_restyle Fired after the plot style is changed.
on_redraw Fired after the plot is redrawn.
on_selected Fired after selecting plot elements.
on_selecting Fired while dragging a selection.
on_transitioning Fired while an animation is occuring.
on_transition_interrupted Fired when a transition is stopped early.
on_unhover Fired when a hovered element is no longer hovered.