SnippetWednesday - MatplotlibView

I often struggle with converting a matplotlib plot from a script to a functioning view in VIKTOR. How i normally do this:

  • copy paste the example from the docs
  • modify for my needs

Allthough this doesn’t take very much time, it feels unnecessarily difficult. What if I would have a dedicated MatplotlibView?

Inspired by the TableView, I created the following code that enables this:

from io import StringIO

import numpy as np
import matplotlib.pyplot as plt

from viktor import ViktorController
from viktor.parametrization import ViktorParametrization
from viktor.parametrization import NumberField
from viktor.views import ImageResult, ImageView


class MatplotlibView(ImageView):
    pass


class MatplotlibResult(ImageResult):
    def __init__(self, plt_):
        fig = plt_.gcf()
        svg_data = StringIO()
        fig.savefig(svg_data, format='svg')
        super().__init__(svg_data)


class Parametrization(ViktorParametrization):
    constant_a = NumberField('A',default=1)
    constant_b = NumberField('B', default=1)
    constant_c = NumberField('C', default=1)


class Controller(ViktorController):
    label = 'My Entity Type'
    parametrization = Parametrization
    
    @MatplotlibView("Plot", duration_guess=1)
    def createPlot(self, params, **kwargs):

        # standard matplotlib code
        x = np.arange(-10, 10, 1)
        y = params.constant_a * x ** 2 + params.constant_b * x + params.constant_c
        plt.plot(x, y)
        plt.show()  # this is not necessary here but often part of examples

        return MatplotlibResult(plt)
4 Likes