In recent years data visualization has become one of the primary tools for decision making in healthcare, not-for-profits, and many other sectors. By using data visualization, such as charts and maps, we can represent data graphically. It helps people to make quick judgments based on trends and patterns.
There are many data visualization tools available on the internet. Out of the extensive list of these tools, plotly.js is one of them. It’s a JavaScript open-source graphing library built on top of d3.js and stack.gl. This library comes with a wide variety of chart types, including 3D charts, graphs, and SVG maps.
I’ve used plotly.js to create dashboards to visualize data with interactive charts from its affluent graphing library. I prefer Plotly.js over other libraries because it’s easy to use and has robust documentation. From this post, you’ll learn some basic concepts and commands of plotly.js that will teach you how to visualize data.
First, we need to add the plotly.js in the HTML file. You can either download the file or use a CDN link. Here, we will use the CDN link for convenience. After that, we need an empty DIV called **test **to attach the chart. Last, we need to add some JavaScript code that will draw the chart. Now save the following code inside an HTML file, like test.html
.
<!DOCTYPE html>
<html>
<head>
<title>Plotly</title>
<script src="https://cdn.plot.ly/plotly-latest.min.js"></script>
</head>
<body>
<div id="test"></div>
<script>
var data = [{
x: [0, 10, 20, 30, 40, 50],
y: [0, 10, 20, 30, 40, 50] }];
var layout = {font: {size: 18}};
var config = {responsive: true};
TESTER = document.getElementById('test');
Plotly.newPlot(TESTER, data, layout, config);
</script>
</body>
</html>
view raw
medium_plotly.html hosted with ❤ by GitHub
By loading this file on your browser, you can see a line graph like the one below. In case you do not see anything, try opening the developer console of the browser. It will help you debug the problem.
A line chart
Now let’s break down the script tag to the individual pieces. First, we have the data
array that contains a hash. Inside the hash, we have two key-value pairs x
and y
representing the value for the x-axis
and y-axis
. Followed by a layout
hash, where we have defined the font size for the chart. The config
hash is used to add extra configurations to the chart. Since we want the chart to be responsive, we set responsive to true. You can find more information about configurations here. Now we need to add our chart to an HTML element. In this case, it’s a DIV with id test
. Finally, we can create our chart using Plotly.newPlot
method by passing the DIV DOM element, data array, layout, and config hash as arguments.
Let’s look at a few more examples.
#javascript #software-engineering #plotly #programming #data-science #data analysis