Skip to main content

Dive into data visualizations

Read this first
  • Make sure you completed the installation process, if you ran into issues try following the installation guide.
  • Did you already create an app template in one of the previous tasks? Then you can continue to implementing the data analysis.

Set up the app template

When you start creating a new app the first thing you need to do is to create an app template. The required steps depend on the chosen installation method.

Would you like to watch a short video?

  1. Create a new folder for your app

    Add a new folder in your filesystem (e.g. C:\Users\<username>\viktor-apps\my-app) and open it in your code editor of choice

  1. In your terminal enter the following command and hit enter:

    viktor-cli create-app --app-type editor

    This will make all the necessary files in your app folder for you.

  2. Install the app and it's dependencies and start it in your development workspace by using the following command in the terminal:

    viktor-cli clean-start

    If all went well, your app is installed and running in your development workspace:

    INFO    :  __      __ __  __  __
    INFO : \ \ / / | | | |/ /
    INFO : \ \ / / | | | ' /
    INFO : \ \/ / | | | <
    INFO : \ / | | | . \
    INFO : \/ |_| |_|\_\
    INFO : _______ ____ _____
    INFO : |__ __| / __ \ | __ \
    INFO : | | | | | | | |__) |
    INFO : | | | | | | | _ /
    INFO : | | | |__| | | | \ \
    INFO : |_| \____/ |_| \_\
    INFO : VIKTOR connector vX.Y.Z
    INFO : Connecting to platform...
    INFO : Connection is established: <URL> <---- here you can see your app
    INFO : The connection can be closed using Ctrl+C
    INFO : App is ready

    Do not close the terminal as this will break the connection with your app.

  3. Open your development workspace if you are not in it yet

    You can now navigate to the URL shown in the terminal (as highlighted above), and enter your Development workspace by clicking the open button.

Define the input fields

Restarting your app
  • The app will update automatically after adding your code and saving the file, as long as you don't close the terminal.
  • Did you close your code editor? Use viktor-cli start to start the app again. No need to run the install and clear commands.
  • Once your app is started you will be able to interact with it in your Development workspace

During this task you will learn how to add graphs to your app. We will be creating a visualization to determine rental prices for a real estate development.

Open, this is where we will place all the code for our app. We will begin by adding all the imports that we will need to the top of the file:

import numpy as np 
import matplotlib.pyplot as plt
from io import StringIO

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

To add the graph we will use Matplotlib, a well-known Python visualization library.

As we already determined that the materials and the ratio of offices to residential spaces will be our parameters of choice, let's add them to the Parametrization class. You only need to add the highlighted lines of code.

class Parametrization(ViktorParametrization):
text_graph = Text('## Graph inputs')
percentage_green_energy = NumberField('Percentage green energy', variant='slider', min=0, max=100, default=50)
weight_sustainable_materials = NumberField('Weight of sustainable materials', variant='slider', min=0, max=100, default=70)

As you can see the Text parameter became a nice title for our parameters and the two NumberFields are modified to be sliders and can be between 0 and 100.

Open or refresh your app in the browser, it will look something like this:

Let's add the graph

In our Controller class, add the highlighted lines of code:

class Controller(ViktorController):
label = 'My Entity Type'
parametrization = Parametrization

@ImageView("Graph", duration_guess=1)
def starter_guide_graph(self, params, **kwargs):
fig = plt.figure()
svg_data = StringIO()
fig.savefig(svg_data, format='svg')
return ImageResult(svg_data)

We now have a template to make our graph. When you open or refresh your app in the browser, this will show up as a blank canvas. To make the graph we will first use numpy (another well-known Python library for scientific computing) to define the range and then use an equation to calculate the potential revenue. You only need to add the highlighted lines of code.

    @ImageView("Graph", duration_guess=1)
def starter_guide_graph(self, params, **kwargs):
fig = plt.figure()

# Define the ranges for office and sustainability
office = np.linspace(0, 100, 101)
sustainability = np.linspace(0, 100, 101)
x, y = np.meshgrid(office, sustainability)

# Calculate revenue per square meter
rev_per_sqm = x + params.weight_sustainable_materials / 100 * y + 0.5 * params.percentage_green_energy

# Plot the surface
plt.imshow(rev_per_sqm, extent=(0, 100, 0, 100), origin='lower', cmap='RdBu', aspect='auto', vmin=40 ,vmax=240)
plt.colorbar(label='Avg. revenue per m²')

# Set title and axis labels
plt.title('Average rent per square meter')
plt.xlabel('Percentage offices')
plt.ylabel('Percentage sustainable materials')

svg_data = StringIO()
fig.savefig(svg_data, format='svg')
return ImageResult(svg_data)

As you may have noticed, we have added a title, axis labels, and a legend to inform the user. Change some of the input values to see the effect on the resulting visualization! How does this work? The inputs you defined on the Parametrization are passed to the ImageView method with the params argument. For example, to use the percentage of green energy in the revenue calculation you reference it by its variable name params.percentage_green_energy.

Nice! You now know the basics of adding matplotlib graphs to your apps. Do you want to learn how to add an interactive graph? Check out this tutorial.

Continue the next section or come back tomorrow to spread the workload!