Skip to main content

Create a Plotly view

New in v12.10.0

Plotly is a free and open source package that simplifies the creation of interactive graphs, such as line plots, scatter plots, histograms, etc. A Plotly graph can be incorporated in your VIKTOR app by making use of a PlotlyView.

Example of how an interactive visualization in the PlotlyView could look like (source: plot.ly)

The Plotly graph can either be passed to a PlotlyResult as a (JSON) str representation (e.g. by creating a Plotly Figure object and calling to_json on it), or as a valid Plotly dict:

import plotly.graph_objects as gofrom viktor import ViktorControllerfrom viktor.views import PlotlyView, PlotlyResultclass Controller(ViktorController):    ...    @PlotlyView("Plotly view", duration_guess=1)    def get_plotly_view(self, params, **kwargs):        fig = go.Figure(            data=[go.Bar(x=[1, 2, 3], y=[1, 3, 2])],            layout=go.Layout(title=go.layout.Title(text="A Figure Specified By A Graph Object"))        )        return PlotlyResult(fig.to_json())
from viktor import ViktorControllerfrom viktor.views import PlotlyView, PlotlyResultclass Controller(ViktorController):    ...    @PlotlyView("Plotly view", duration_guess=1)    def get_plotly_view(self, params, **kwargs):        fig = {            "data": [{"type": "bar", "x": [1, 2, 3], "y": [1, 3, 2]}],            "layout": {"title": {"text": "A Figure Specified By Python Dictionary"}}        }        return PlotlyResult(fig)

A Plotly view can be combined with a data view using a PlotlyAndDataView

Testing

New in v13.3.0

Methods decorated with @PlotlyView or @PlotlyAndDataView need to be mocked within the context of (automated) testing.

import unittestfrom viktor.testing import mock_Viewfrom app.my_entity_type.controller import MyEntityTypeControllerclass TestMyEntityTypeController(unittest.TestCase):    @mock_View(MyEntityTypeController)    def test_plotly_view(self):        params = ...        result = MyEntityTypeController().plotly_view(params=params)        self.assertEqual(result.figure, ...)