Zepl Blog Background Image

JavaScript in DataRobot Notebooks: Leverage the Power of Modern Browsers

March 2, 2022
by
· 7 min read

Add interactive components to Notebooks using JavaScript

JavaScript dashboard created with a Notebook 

Every data scientist’s workflow requires visualizing data. There are a lot of tools for this purpose and each tool has its pros and cons, depending on the phase of the project or the purpose of the visualization. Typically, at the beginning of a project, we visualize data in a way that provides insights into data types, patterns, distributions, or availability. However, at the end of a project, we create visualizations that end users and executives can leverage to consume our model’s insights. These visualizations usually require more customization to be useful. Data science notebooks, in general, are much more useful at the beginning of projects, but by the time we need to create a dashboard or report for the end user, this usefulness fades.

Notebooks provide intuitive in-line data viz tools through the z.show(df) function. This is great for when we want to quickly peek into our data or spot-check our data after certain data prep steps. Most of the time, it will alleviate the extra work integrating Python packages (matplotlib) or exporting data to another tool (Excel, Tableau) for visualization. Yet, while this functionality is useful for early-project data visualization, it doesn’t give us the user input and visual control required for advanced visualization in late-project dashboards and reports. For this purpose, we can leverage the power of modern browsers and the technologies that make using web-based applications seamless and fast.

JavaScript is a powerful programming language that allows us to make HTML elements in a browser interactive. There are countless libraries and resources available for developers to leverage in their own projects. Here, we will only touch a small sample of what is available, but it should be enough to provide a foundation for data scientists to begin integrating JavaScript into their Notebooks.

The Hello, World! of JavaScript in Notebooks

To get started, let’s run a very small snippet of JavaScript code from within a Notebook. This code will tell our browser how to handle a user event to manipulate an HTML element.

Create a new Notebook and add the following code snippet:

%python
print(" ")
print('''%html
<p><b>Hello, World!</b></p>
''')

This code snippet uses the Python print function to add HTML elements to the output of our Notebook’s paragraph. Here we use the <p> and <b> HTML tags to tell the browser how to interpret the text (Hello, World!) found in between the tags. Next, we will add some simple styling to the elements that will later be manipulated by a piece of JavaScript code.

Add styling to the <p> tag:

<p style=”color: red;”><b>Hello, World!</b></p>

Hello, World! should be printed to the output in red text. Now, let’s write a piece of JavaScript code that will change the color of the text to green when the user clicks the text.

First, create a <script></script> tag to encapsulate our JavaScript code. This tag tells the browser to interpret the text inside it as JavaScript. Here we can define our JavaScript function that will manipulate the color of the text inside the <p> tag. 

<script>
	</script>

Inside our new <script> tag, let’s define a function named ‘handleTextClick()’. This function will be called when the user clicks the text inside the <p> tag. 

<script>
		function handleTextClick() {
			// code to change color of text
		}
	</script>

Add a line of code inside this function that will change the color of the text to green.

<script>
		function handleTextClick() {
			document.getElementById(“myText”).style.color = “green”;
		}
	</script>

At this point, we have written some JavaScript code to tell the browser what to do when the function is triggered. However, we have not yet provided a way for this function to be triggered. 

Let’s go back to our <p> tag and define an identifier (id) so the browser knows which HTML element to modify as well as an event (onclick) to trigger the function that does the modifying. Our new <p> tag should look like this now:

<p id=”myText” onclick=”handleTextClick()” style=”color: red;”><b>Hello, World!</b></p>

Now our browser knows to run the JavaScript function, defined in our <script> tag, when the ‘onclick’ event is triggered on the <p> tag. The ‘id’ of the <p> tag allows JavaScript to find the HTML element that we want to modify.

We can run the paragraph and see a bold, red Hello, World! printed in the output of our paragraph. If the code was implemented properly, this red text will turn green when we click on the text.

This simple piece of code demonstrates something very important and useful: we can add HTML elements as well as JavaScript to manipulate those elements based on user actions directly to our Notebooks. This augments the capabilities of notebooks quite a bit as there are countless JavaScript libraries for visualization, user-interface tools, maps, dashboards, and even filters. However, before we discuss how to import and leverage these libraries, we will first discuss how we can import data from Python into our JavaScript code. 

Importing a Python Dataframe to JavaScript

Pulling Python data into JavaScript is actually really simple. However, the amount of data that can be loaded into JavaScript is limited by the user’s browser. Use some caution for very large dataframes and aggregate the data as needed to avoid overloading the browser. Additionally, JavaScript data operates differently than Python data, and a tutorial on this nuance is outside of the scope of this article. Luckily, there are a ton of resources available online to explore working with data in JavaScript.

First, let’s create a very simple, small Python DataFrame in a new blank paragraph within our Notebook:

%python

import pandas as pd

df = pd.DataFrame([['alec', 10], ['zack', 15], ['rick', 14]], columns=['Name', 'Score'])

Now that we have our dataframe data loaded into the ‘df’ Python variable, we can use this variable to load the data into JavaScript. Create a new <script> tag encapsulation within a Python print statement so we can tell the browser to interpret the code as JavaScript:

print(" ")
print('''%html
    <script>
        // JavaScript code here
    </script>
''')

Within the <script> tag, create a JavaScript variable named ‘data’ and print the output of the Python DataFrame’s ‘to_json()’ method immediately after the assignment operator (=):

<script>
        	data = ''', df.to_json(orient="records"),'''
</script>

In order for JavaScript to see the Python output, we simply “turn off” the string encapsulation operator (”’)  for a moment. This prints the output of ‘df.to_json()’ inside the <script> tag in a format that JavaScript can interpret (JSON). I prefer to work with data in the format generated by setting the ‘orient’ parameter to ‘records’ which defines the data as a JavaScript array of objects where each object is a row/record from the Python DataFrame. This is a matter of personal preference, so feel free to use whatever JSON format works for you.

At this point, we have successfully loaded the data into JavaScript and can run JavaScript code based on or with the data. Let’s verify this by using a useful JavaScript function after the assignment that will print its contents to our browser’s console:

console.log(data)

You may notice that nothing really seems to happen on the web page itself. The browser’s console is, by default, hidden from the user. So, let’s open up the console and see the JavaScript output of our data.

FOR CHROME: Right-click anywhere on the Notebook’s webpage and select the “Inspect” option at the bottom of the list. In the new window (or side-window) that pops up, select the ‘Console” tab at the top of the window. You should see some output written to the console at this point. You can ignore most of the console’s contents as it is Web App output and irrelevant to our purposes here. 

Importing JavaScript Packages into Notebooks

We are now able to run HTML and JavaScript from our Notebooks, as well as read data into JavaScript that is generated from Python. These two capabilities allow us to build countless visualizations and user interfaces within our notebooks. We could build these visualizations and user interfaces from scratch, but why would we try to reinvent the wheel? There are a lot of open and easy-to-use libraries for these purposes available. Just to name a few:

  • Chart.js
  • Bootstrap
  • jQuery
  • DateRangePicker
  • D3.js

Importing these packages into our Notebooks is very easy. I use a CDN (Content Delivery Network) which is basically a set of servers available to provide the source code to these packages on request. To request a package/library simply find a domain that hosts the code and use the following JavaScript encapsulation at the beginning of your Python ‘print’ statement (but after %html).

<script src="https://cdn.jsdelivr.net/npm/chart.js@3.6.2/dist/chart.min.js"></script>

This code snippet pulls source code for chart.js directly into our Notebook browser, making the functionality available in our own Javascript. Some modern web apps use this same approach for importing libraries, so if you get stuck, there should be plenty of resources available to find more information about importing JavaScript libraries using a CDN.

Ready to Advance Your Data Science Toolkit with DataRobot Notebooks?

You can start today! Tour the DataRobot AI Platform. Check out the public documentation and library of Notebook Accelerators that we have collected for you. Learn how Embrace Home Loans utilizes DataRobot Notebooks to improve their team’s efficiency and maximize ROI from the marketing efforts. 

Demo
See DataRobot in Action
Request a demo
About the author
Alec Siems

Solutions Architect

Alec Siems is an award-winning data scientist who has developed multiple high-value predictive analytics models and dashboards for the transportation industry. He is passionate about augmenting our productivity when solving difficult problems through computing.

Meet Alec Siems
  • Listen to the blog
     
  • Share this post
    Subscribe to DataRobot Blog
    Newsletter Subscription
    Subscribe to our Blog