Klipfolio gets cozy with Plotly

Published 2015-12-17, updated 2023-02-01

klipfolio image

Summary - In this article, we show how Klipfolio integrates with the Plotly visualization library.


Blog updated February 9th, 2017 - Please use plotly version 1.5.0 or earlier.

Plotly is a comprehensive visualization library with tons of flexibility and rich features. You can create a number of different visualization types including basic, statistical and financial visualizations. Plotly also provides a great deal of flexibility with respect to layout options of the visualizations. Furthermore, the library not only supports a good level of interactivity on the visualizations (for example,. pan and zoom) but also allows you to define more interactive controls that interact with components of the visualization like dropdowns and slider filters. Last but not least, the Plotly library is open source and available to use for free.

At Klipfolio we always look for opportunities to extend and complement our app by integrating with other libraries and services. In a previous blog post I explain in detail how you can use the Klipfolio’s “HTML template” to build a customized visualization using the Vega visualization library. If you have not read that post or are not familiar with the basics of using the HTML template, I recommend you have a quick read through the post or at least our tutorial on the HTML Template. In this post I assume you are familiar with some of the basic concepts of our HTML template.

Your first Plotly visualization in Klipfolio

To create your first Plotly visualization in Klipfolio, start by setting up a new HTML template Klip. For this first example, we use hard-coded data so don’t worry about selecting or creating data sources when building the Klip.

Next, add the JavaScript code (see below) required to load Plotly.js and render the visualization. All you need to do is copy and paste the following code into the Script section of the HTML Template. To expose the Script section, first click on the HTML Template component in the tree and then click on “Use JavaScript with this HTML Template” in the properties pane at the bottom.


//Define the path configurations to the JS module that you want to load

var vizmodules = {
    plotly               : 'https://cdn.plot.ly/plotly-1.5.0.min.js?noext'
};

// Get the Klipfolio data model from the component context 
var _dataModel = this.dataModel;

//Pass in the configurations to requirejs  
requirejs.config({
    paths: vizmodules
});

//Load the libraries 
require([vizmodules.plotly], 
    function(PlotlyEngine) { 
            
      // Define the data array expected by Plotly 
      // Using hard coded data (as the first step)  
      var data = [{
            x: [1, 2, 3],
            y: [4, 5, 2]
        }];
       
       //Define the layout object and layout object 
        var layout = {
            title: 'Simple line chart'
        };
      
      // Pass call the plot method with the appropriate parameters:
 
      // 1: The HTML element that the chart will be plotted in
      // 2: Data that will be rendered 
      // 3: The layout specification  
      PlotlyEngine.plot('plotly-div-simple', data, layout);
});

Finally, to be able to render the visualization you also need to add the following HTML code to the HTML section of your HTML Template Klip. The JavaScript code references the HTML element that is defined in this HTML code. The id attribute of the HTML element has to have the same value as the first parameter passed to the plot function in the last line of the above JavaScript code (see text in red).

<div id="plotly-div-simple"></>

Tip: If you are building several custom visualizations, make sure they each have a unique id in the HTML element. In other words, do not reuse the same id.

After updating the HTML template, you should see the following visualization rendered in the Klip editor:

Plotly Dashboard Simple Chart

Using Klipfolio data

Now that you are familiar with the HTML template and you can render a visualization using Plotly in the Klip editor, it’s time to plot some real data! In this scenario, you will use the data that’s provided by the Klipfolio data layer and pass it to Plotly to render. For this, we are going to use the following sample data:

https://static.klipfolio.com/images/saas/Training-Sample-Data.csv

Create a data source using the sample data and add it to your Klip. Then define two data series using the following names and formulas:

NameFormula
citySLICE(B:B)
scoreSLICE(C:C)

After defining the above series, your component tree should look like the following:

Plotly Dashboard Klip Editor

Finally, replace the hard-coded data definition in the JavaScript code that you used above:


//Define the layout object and layout object      
 var data = [{
      x: [1, 2, 3],
      y: [4, 5, 2]
 }];
 

Use the following code that employs Klipfolio’s HTML Template Data Model and transforms the data into the format that is expected by Plotly.


   // helper variables  

    var _x = [];
    var _y = [];

  // Push the Klipfolio data model data points into the helper variables
    _.each(_dataModel.data, function(element){
      _x.push(element.city);
      _y.push(element.score); 
    });

  // Define the data array in the format expected by Plotly
  // Use the helper variables that were populated with Klipfolio data above

      var data = [{
            x: _x,
            y: _y,
            type: 'bar' //Choose to use a bar visualization 
        }];
        
        

The result is the following bar visualization:

Plotly Dashboard Bar Visualization

Update the layout options

In the next step you will update the visualization layout options. As you may have noticed, the title of the above visualization is no longer accurate since it’s not a line chart. Plotly allows you to change the title, font and more properties using the layout options (Read more here).

For the next step, replace the layout definition in the above JavaScript:


 //Define the layout object and layout object 
 var layout = {
     title: 'Simple line chart'
 };
 

Use the following code snippet that defines the new title and font options.

The result after the visualization is rendered looks like this:

Plotly Dashboard Bar Visualization Rendered

Toolbar configuration options

Plotly visualizations render with an interactive toolbar by default. While there are some really cool features included such as Save as Image, Compare and Pan, a dashboard designer may not want to include it on a dashboard that is mostly meant to be used for monitoring purposes. The good news is Plotly has a set of configuration options that allow you to hide or customize the toolbar by passing the config options when calling the plot method.

To completely hide the Plotly toolbar, use: displayModeBar:false and pass it as an object and the fourth parameter in the plot call (see red text below).

PlotlyEngine.plot('plotly-div', data, layout, {displayModeBar: false});

If you want to customize the toolbar but keep some of the functionality, you can list the buttons that you want to exclude. For instance, to hide both the Plotly logo and “send to Plotly Cloud” button, use the following config properties:

{modeBarButtonsToRemove: ['sendDataToCloud'], displaylogo: false}

Summing up + Bonus visualizations

In this post, we covered how you can very quickly use Plotly in Klipfolio to build custom visualizations. While Klipfolio supports many visualizations natively, being able to use other libraries and extend the visualization capabilities is one of the strengths of our flexible platform that we are proud of and we’d like our customers to be aware of and use. We covered a few examples in this post but there are many more to explore and have fun with for you visualization geeks out there.

Thanks for reading this far. As a bonus, here are a few visualizations (Plotly supports a long list of visualizations.) that may be useful for your dashboards if you follow the above instructions and transform and feed them the Klipfolio data model as they expect.

Waterfall

The Waterfall visualization is used to plot the cumulative impact of positive and negative values and their total (Read more here).

Plotly Dashboard Waterfall Visualization

Reference: https://plot.ly/javascript/bar-charts/

Box plot

Shows a groups of numerical data via their quartiles (Read more here).

Plotly Dashboard Boxplot Visualization

Reference: https://plot.ly/javascript/box-plots/

Histograms

A Histogram is a visualization used to show the distribution of numerical data (Read more here).

Plotly Dashboard Histogram Visualization

Reference: https://plot.ly/javascript/histograms/

Appendix: For your convenience, the complete JavaScript code used in the example above.


var vizmodules = {
    plotly               : 'https://cdn.plot.ly/plotly-1.5.0.min.js?noext'
};

requirejs.config({
    paths: vizmodules
});

var _dataModel = this.dataModel;

require([vizmodules.plotly], 
    function(PlotlyEngine) { 

    var _x = [];
    var _y = [];

    _.each(_dataModel.data, function(element){
      _x.push(element.city);
      _y.push(element.score); 
    });

        var data = [{
            x: _x,
            y: _y,
            type: 'bar'
        }];
       
        var layout = {
            title: 'Score by cities',
            font: {
             family: 'Courier New, monospace',
             size: 12,
             color: '#7f7f7f'
           }
        };

      PlotlyEngine.plot('plotly-div-simple', data, layout, {modeBarButtonsToRemove: ['sendDataToCloud'], displaylogo: false}
);
});

Related Articles

Level up your decision makingTrack all your metrics in one place.Get PowerMetrics Free