Getting started with Plotly.js

In this lesson, we'll learn the basics of drawing charts with Plotly.js

Often, in real world applications, there’s some third party library that needs to be used, or maybe some legacy code that needs to be bridged. To showcase how one would go about doing that, we’ll be using Plotly to draw a beautiful temperature forecast graph!

Plotly

We’ll explore the Plotly.js API and draw a scatter chart.

To use plotly.js, we need to add it to our application. Copy and paste the following line into your HTML:

<script src="https://cdn.plot.ly/plotly-1.8.0.min.js"></script>

Including this script gives us access to the Plotly variable in our code. Using Plotly.newPlot, we can easily create graphs to showcase the weather data:

Plotly.newPlot();

Let’s look at the newPlot function in a little bit more detail:

  1. The first argument is the id of the DOM element we want to render our plot into.
  2. The second argument is an array of objects with a few properties for our plot, with x, y and type being the most relevant for us.

Plotly.js makes it easy to create a wide variety of plots, the one we care about the most at the moment is a scatter plot. See the documentation here for some examples.

This is what our Plotly.newPlot call will look like:

Plotly.newPlot('someDOMElementId', [{
  x: ourXAxisData,
  y: ourYAxisData,
  type: 'scatter'
}], {
  margin: {
    t: 0, r: 0, l: 30
  },
  xaxis: {
    gridcolor: 'transparent'
  }
}, {
  displayModeBar: false
});

As you can see, we also pass in some styling information as the third argument (we specify a few margins and hide the xaxis grid lines), and some options as the fourth argument. (we hide the mode bar).

Plotly.js has tons of options, I encourage you to check out the excellent documentation and play around with a few of them!

For getting our feet wet, we’ll draw a chart of 9 numbers [-4, 4], their squares and their cubes. Here’s the data that we will use for our chart:

x-axis: [-4, -3, -2, -1, 0, 1, 2, 3, 4]

y-axis-1: [16, 9, 4, 1, 0, 1, 4, 9, 16];

y-axis-2: [-64, -27, -8, -1, 0, 1, 8,27, 64];

Get hands-on with 1400+ tech skills courses.