Creating Custom JavaScript Visualizations in Data Studio
By: Tij Tech Private Limited
Tags: Google Data Studio, Visualization, Machine Learning, Data Science, AI

For more details and information, you can watch the YouTube video on Google Data Studio.

Video URL : https://youtu.be/U2CIh1SfkXI Overview

In this tutorial, you will learn on How a Google Data Studio community visualization works, How to build a community visualization using the ds-component helper library and How to integrate your community visualization into a Data Studio dashboard.

Introduction

Google Data Studio allows users to build live, interactive dashboards with beautiful data visualizations, and can fetch the data from a variety of sources, create reports in Data Studio and also allows to build and use our own custom JavaScript visualizations in Data Studio.

Data Studio community visualizations allows us to create and use custom JavaScript visualizations that integrate into your dashboards. The below given image is an example of Data Studio Dashboard.

Community Visualization Development Work Flow

To create a community visualization, we need the following files in a Google Cloud Platform storage bucket.

Note that: The manifest is the only file that has a required name. The other files can be named differently, as long as their name/location is specified in your manifest file.

Now, we will learn to handle data, style changes, and visualization rendering into your JavaScript file.

Step 1: Download the dscc.min.js file from the Data Studio Community Component Library and copy it to your working directory.

Step 2: Copy the following code into a text editor and save it as myVizSource.js in your local working directory.

function drawViz(data) {



// set margins + canvas size

const margin = { top: 10, bottom: 50, right: 10, left: 10 };

const height = dscc.getHeight() - margin.top - margin.bottom;

const width = dscc.getWidth() - margin.left - margin.right;



// remove the svg if it already exists

if (document.querySelector("svg")) {

let oldSvg = document.querySelector("svg");

oldSvg.parentNode.removeChild(oldSvg);

}



const svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");

svg.setAttribute("height", `${height}px`);

svg.setAttribute("width", `${width}px`);



const rect = document.createElementNS("http://www.w3.org/2000/svg", "rect");

rect.setAttribute('width', `${width/2}px`);

rect.setAttribute('height', `${height/2}px`);

rect.style.fill = 'blue';



svg.append(rect);



document.body.appendChild(svg);

}

// subscribe to data and style changes

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

Step 3: Combine all JavaScript required into a single file by copying the contents of the visualization helper library ( dscc.min.js ) and your myVizSource.js file into a new file named myViz.js .

Or else Run the following codes:

//For Windows del myViz.js

type nul > myViz.js

type dscc.min.js >> myViz.js

echo.>> myViz.js

type myVizSource.js >> myViz.js //Linux/Mac cat dscc.min.js > myViz.js

echo >> myViz.js

cat myVizSource.js >> myViz.js

Next defining the CSS file for styling for your visualization.

Copy the following code and save it as myViz.css.

#myVizTitle {

color: black;

font-size: 24px;

text-align: center;

margin: 0 auto;

}

The visualization config json file defines the data and style attributes supported and required by your visualization.

Copy the following code and save it as myViz.json.

{

"data": [

{

"id": "concepts",

"label": "Concepts",

"elements": [

{

"id": "barDimension",

"label": "Dimension",

"type": "DIMENSION",

"options": {

"min": 1,

"max": 1

}

},

{

"id": "barMetric",

"label": "Metric",

"type": "METRIC",

"options": {

"min": 1,

"max": 1

}

}

]

}

],

"style": [

{

"id": "color",

"label": "Colors",

"elements": [

{

"type": "FONT_COLOR",

"id": "barColor",

"label": "Bar Color",

"defaultValue": "#222222"

}

]

}

]

}

Create a cloud storage project and bucket

Step 1: Create a Google Cloud Platform (GCP) Project

Step 2: Create a GCP bucket.

Step 3: Take note of your bucket name/path, beginning with the section after Buckets/…. Data Studio calls this the “component ID”, and it will be used to identify and deploy.

The manifest file provides information about your visualization location and resources. It must be named “ manifest.json ", and it must be located in the bucket created in the previous step.

Copy the following code into a text editor and save it as manifest.json.

{

"name": "Community Visualization",

"logoUrl": "https://raw.githubusercontent.com/googledatastudio/community-visualizations/master/docs/codelab/img/bar_chart.png",

"organization": "Data Studio Codelab",

"organizationUrl": "https://url",

"termsOfServiceUrl": "https://url",

"supportUrl": "https://url",

"packageUrl": "https://url",

"privacyPolicyUrl": "https://url",

"description": "Community Visualization Codelab",

"devMode": true,

"components": [{

"id": "barChart",

"name": "Bar Chart",

"iconUrl": "https://raw.githubusercontent.com/googledatastudio/community-visualizations/master/docs/codelab/img/bar_chart.png",

"description": "Bar chart written in d3.js",

"resource": {

"js": "gs://MY_GOOGLE_CLOUD_STORAGE_BUCKET/myViz.js",

"config": "gs://MY_GOOGLE_CLOUD_STORAGE_BUCKET/myViz.json",

"css": "gs://MY_GOOGLE_CLOUD_STORAGE_BUCKET/myViz.css"

}

}]

}

Upload your visualization files to Google Cloud Storage

Upload the manifest.json , myViz.js , myViz.json, and myViz.css files to the Google Cloud Storage bucket.

Test your Community Visualization in Data Studio

Step 1: Copy the URL or download the data set file in your google drive for the Community Visualization sample data set.

Step 2: Visit Data Studio and click Blank under Start a new report.

Step 3: Select the Google Sheets connector.

Step 4: Then Click on Open From Google Drive and select the Data set File.

Step 5: In the drop-down, click + Explore more to open the Community Gallery shade.

Step 6: Click Build your own visualization.

Step 7: Paste your bucket name prefixed by gs:// ( for example: gs://community-viz-docs/myViz) into the text input for "Manifest Path" and click Submit. This should render one visualization card.

Step 8: Click the visualization icon to add it to your report.

Use the color selector style element, Render the data as a bar chart and Dynamically add a title and apply a CSS style

Step 1: Replace the code in your myVizSource.js file with the code below.

// create a title element

var titleElement = document.createElement('div');

titleElement.id = 'myVizTitle';

document.body.appendChild(titleElement);



function drawViz(data) {

let rowData = data.tables.DEFAULT;



// set margins + canvas size

const margin = { top: 10, bottom: 50, right: 10, left: 10 };

const padding = { top: 15, bottom: 15 };

const height = dscc.getHeight() - margin.top - margin.bottom;

const width = dscc.getWidth() - margin.left - margin.right;



const fillColor = data.style.barColor.value

? data.style.barColor.value.color

: data.style.barColor.defaultValue;



// remove the svg if it already exists

if (document.querySelector("svg")) {

let oldSvg = document.querySelector("svg");

oldSvg.parentNode.removeChild(oldSvg);

}



const svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");

svg.setAttribute("height", `${height}px`);

svg.setAttribute("width", `${width}px`);



const maxBarHeight = height - padding.top - padding.bottom;

const barWidth = width / (rowData.length * 2);



// obtain the maximum bar metric value for scaling purposes

let largestMetric = 0;



rowData.forEach(function (row) {

largestMetric = Math.max(largestMetric, row["barMetric"][0]);

});



rowData.forEach(function (row, i) {

// 'barDimension' and 'barMetric' come from the id defined in myViz.json

// 'dimId' is Data Studio's unique field ID, used for the filter interaction

const barData = {

dim: row["barDimension"][0],

met: row["barMetric"][0],

dimId: data.fields["barDimension"][0].id

};



// calculates the height of the bar using the row value, maximum bar

// height, and the maximum metric value calculated earlier

let barHeight = Math.round((barData["met"] * maxBarHeight) / largestMetric);



// normalizes the x coordinate of the bar based on the width of the convas

// and the width of the bar

let barX = (width / rowData.length) * i + barWidth / 2;



// create the "bar"

let rect = document.createElementNS("http://www.w3.org/2000/svg", "rect");

rect.setAttribute("x", barX);

rect.setAttribute("y", maxBarHeight - barHeight);

rect.setAttribute("width", barWidth);

rect.setAttribute("height", barHeight);

rect.setAttribute("data", JSON.stringify(barData));

// use style selector from Data Studio

rect.style.fill = fillColor;

svg.appendChild(rect);



// add text labels

let text = document.createElementNS("http://www.w3.org/2000/svg", "text");

let textX = barX + barWidth / 2;

text.setAttribute("x", textX);

text.setAttribute("text-anchor", "middle");

let textY = maxBarHeight + padding.top;

text.setAttribute("y", textY);

text.setAttribute("fill", fillColor)

text.innerHTML = barData["dim"];



svg.appendChild(text);

});



document.body.appendChild(svg);



// Get the human-readable name of the metric and dimension



var metricName = data.fields['barMetric'][0].name;

var dimensionName = data.fields['barDimension'][0].name;



titleElement.innerText = metricName + ' by ' + dimensionName;



}



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

Step 2: Create the combined JavaScript file, then re-upload your visualization files to Google Cloud Storage.

Step 3: Refresh the Data Studio report where you tested your community visualization. You should have a bar chart with a title generated from the data and styled using your myViz.css file.

Congratulations! You have created a community visualization in Data Studio.