Writing your visualization

Writing the visualization code

The Data Studio helper library provides an interface between you and Data Studio. To use the library, provide a callback function that renders the visualization.

The most salient function in the library is subscribeToData, which takes two arguments: a callback function that renders the visualization, and an options object that specifies what kind of transform you'd like your data to take. To learn more, review the library reference.

The following provides an outline of what your visualization JavaScript could look like.

function drawViz(vizData){
  var height = dscc.getHeight();
  var width = dscc.getWidth();
  console.log(vizData);
  // this is where you write your viz code
}

dscc.subscribeToData(drawViz, {transform: dscc.objectTransform})

There are a few key things to keep in mind when writing a community visualization.

Updates from the subscribeToData function occur when the data, styling, or iframe size changes.

For example:

// create and add the canvas
// do this one time
var canvasElement = document.createElement('canvas');
var ctx = canvasElement.getContext('2d');
canvasElement.id = 'myViz';
document.body.appendChild(canvasElement);

function drawViz(data){
  // clear the canvas
  var ctx = canvasElement.getContext('2d');
  ctx.clearRect(0, 0, canvasElement.width, canvasElement.height);

  // viz code goes here

}

Data Studio loads and runs JavaScript files, not HTML. All DOM manipulation needs to happen through JavaScript.

For example: the following code defines and appends a div to the DOM.

// create and add the canvas
var chartElement = document.createElement('div');
chartElement.id = 'myViz';
document.body.appendChild(chartElement);

Bundling the code

Data Studio community visualizations only allow you to load one JavaScript file. The uploaded code should be a single file that includes the dscc helper library, any JavaScript visualization libraries, and your visualization code.

To do this in bash, you can use the cat command, like below.

cat dscc.min.js vizLibrary.js myVizSource.js > myViz.js

Defining the manifest

The visualization manifest file provides metadata about the visualization, as well as information about the location of visualization resources. The location of the manifest file is referred to as the "component ID", and used to load a community visualization.

Review the manifest reference to see a sample manifest.

The devMode parameter of the manifest determines the caching behavior of the visualization. While developing the visualization, devMode should be true to ensure that hard refreshes load the latest version of the resources. Once the code is stable, devMode should be false to ensure that reports with community visualizations load quickly. To learn more about caching, see the caching advanced guide.

Next steps

Now that you have the code for your visualization written, learn how to host your visualization.