Interacting with Plotly Chart

This example shows how to change a Plotly Chart when a user changes an Input that affect it. The example assumes you already understand the basics of Charts as well as how to refresh Widgets in response to user interaction.

The example displays a line graph with two lines. One of the lines changes its values based on a factor, which the user can select from a SelectInput.

Add a Field on ChartForm to keep track of the factor:

    @exposed
    def fields(self, fields):
        fields.factor = ChoiceField([Choice(i, IntegerField(label=str(i))) for i in range(1, 10)])

The factor attribute of ChartForm will only be updated in response to user changes once an Input is created for it.

This means that you first initialise factor, then create the SelectInput to possibly update the default value of factor. After the creation of the SelectInput, create the Chart (which uses factor). Lastly, call set_refresh_widget() to make the SelectInput change the contents of the Chart:

Note

Refreshing only the contents of the Chart instead of the entire Chart updates the screen faster.

    def __init__(self, view):
        super().__init__(view, 'chartform')
        self.factor = 1
        self.use_layout(FormLayout())

        select_input = self.layout.add_input(SelectInput(self, self.fields.factor))  # Creating the input, sets self.factor
        chart = self.create_chart(self.factor)
        select_input.set_refresh_widget(chart.contents)

Here is the entire example:

class ChartForm(Form):
    def __init__(self, view):
        super().__init__(view, 'chartform')
        self.factor = 1
        self.use_layout(FormLayout())

        select_input = self.layout.add_input(SelectInput(self, self.fields.factor))  # Creating the input, sets self.factor
        chart = self.create_chart(self.factor)
        select_input.set_refresh_widget(chart.contents)

    def create_chart(self, factor):
        fig = self.create_line_chart_figure(factor)
        return self.add_child(Chart(self.view, fig, 'changing-chart'))

    @exposed
    def fields(self, fields):
        fields.factor = ChoiceField([Choice(i, IntegerField(label=str(i))) for i in range(1, 10)])

    def create_line_chart_figure(self, factor):
        x = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
        fig = go.Figure()
        fig.add_trace(go.Scatter(x=x, y=[1000, 1500, 1360, 1450, 1470, 1500, 1700], name='first line'))
        fig.add_trace(go.Scatter(x=x, y=[i*factor for i in [100, 200, 300, 450, 530, 570, 600, 640, 630, 690, ]], name='second line'))
        fig.update_layout(
            title="Line chart",
            hovermode="x unified",
            xaxis_title="X Axis Title",
            yaxis_title="Y Axis Title"
        )
        return fig