[tutorial] This is why you should use gradient charts with chart.js

Valeria Cortez
4 min readAug 1, 2017

--

Gradient chart with chart.js

After a long period of flat colours for UIs, gradients have become the attractive and joyful side of new interfaces 🙌🏽. If you’re planning some data visualisation, you can now apply some beautiful gradients to charts using chart.js to create a memorable and unique experience for your users. After all, who doesn’t like some colour.

Creating beautiful gradient charts with chart.js

Chart.js is a javascript library that allows you to build beautiful and responsive charts in a short amount of time. Did I also mention it is open source?

During this tutorial, we’ll create a line chart with a gradient composed by four colours (feel free to add more!). The live demo is available here.

Installing Chart.js

Install chart.js by adding its CDN link to the <head> of your code.

https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.min.js">

Creating the container for your graph in the HTML

Chart.js uses canvases to add the graphs. Start by including a <canvas> tag in your .html with an id.

<canvas id="myChart"></canvas>

Selecting your data

For this tutorial, we’ll be using a json file with time series data about visits to a website.

var results = [
{
date: "Jan 17",
visits: 234
},
{
date: "Feb 17",
visits: 345
},
{
date: "Mar 17",
visits: 321
},
{
date: "Apr 17",
visits: 412
},
{
date: "May 17",
visits: 435
},
{
date: "June 17",
visits: 543
},
{
date: "July 17",
visits: 567
},
{
date: "Aug 17",
visits: 480
}
];

Creating the recipe for your gradient chart in JS

It is now time to specify the type of chart we’ll be creating with chart.js. We’ll create a function that can generate different charts in different places of your html.

function drawLineChart(div_id, results, yColumn, yLabel, xAxes, firstColour, secondColour, thirdColour, fourthColour) {

your code will be here
}

drawLineChart accepts the following parameters:

  • div_id: the id of your canvas where your chart will be placed.
  • results: the data we’ll use to plot the chart.
  • yColumn: the value for the y-axis. In our example, it is visits from the results dataset.
  • yLabel: the label for the corresponding data point in the y-axis. In this example, we’ll use “Number of visits” for describing “visits”. When you hover over the datapoint, you’ll be able to see it.
  • xAxes: these are the values for the x-axis of your chart.
  • firstColour, secondColour, thirdColour, fourthColour: these are the four colours to create the gradient.

Building your line chart

Now that we have the structure of drawLineChart function ready, we’ll start adding some code t0 it.

Let’s create the gradient

We first need a variable to store our gradient, so let’s add the following:

var ctx = document.getElementById(div_id).getContext("2d");

getContext("2d") will return an object that provides methods and properties for drawing on the right canvas based on thediv_id.

Now you can add:

var width = window.innerWidth || document.body.clientWidth;
var gradientStroke = ctx.createLinearGradient(0, 0, width, 0);

The createLinearGradient(x0, y0, x1, y1) method creates a linear gradient object. It has four parameters: (x0,y0), the coordinates of the start point of the gradient and (x1,y1), the coordinates for the end point.

We use (0,0) for the start point, as the graph starts at the beginning of the left hand side.

We then need to set the (x1,y1) coordinates. The gradient finishes at the end of the graph. Given that our graph is responsive and covers most of the screen’s width, we’ll use the screen’s width as the x1 end point.

Let’s now add the colours:

gradientStroke.addColorStop(0, firstColour);
gradientStroke.addColorStop(0.3, secondColour);
gradientStroke.addColorStop(0.6, thirdColour);
gradientStroke.addColorStop(1, fourthColour);

The addColorStop(stop, colour) method specifies the colours and their position (0–1) in the gradient object.

Formatting the data

We currently have a json for our data, but we need to map it to the following arrays:

var labels = results.map(function(item) {
return item[xAxes];
});
var data = results.map(function(item) {
return item[yColumn];
});

We can now add the details for our chart

var myChart = new Chart(ctx, {
type: "line",
data: {
labels: labels,
datasets: [
{
label: yLabel,
borderColor: gradientStroke,
pointBorderColor: gradientStroke,
pointBackgroundColor: gradientStroke,
pointHoverBackgroundColor: gradientStroke,
pointHoverBorderColor: gradientStroke,
pointBorderWidth: 8,
pointHoverRadius: 8,
pointHoverBorderWidth: 1,
pointRadius: 3,
fill: false,
borderWidth: 4,
data: data
}
]
},
options: {
responsive: true,
maintainAspectRatio: false,
legend: {
position: "none"
},
scales: {
yAxes: [
{
ticks: {
fontFamily: "Roboto Mono",
fontColor: "#556F7B",
fontStyle: "bold",
beginAtZero: true,
maxTicksLimit: 5,
padding: 20
},
gridLines: {
drawTicks: false,
display: false,
drawBorder: false
}
}
],
xAxes: [
{
gridLines: {
zeroLineColor: "transparent"
},
ticks: {
padding: 20,
fontColor: "#556F7B",
fontStyle: "bold",
fontFamily: "Roboto Mono"
},
gridLines: {
drawTicks: false,
display: false,
drawBorder: false
}
}
]
}
}
});
}

The final result

In the final demo, I created two canvas (id = lineChartBlueGreen and id = lineChartPinkOrange) to plot two line charts using the same data, but with two different gradients.

To initialise the charts, I used the following code triggered when the page is loaded:

Html:<body onload="drawCharts()">...</body>JS:
function drawCharts() {
drawLineChart(
"lineChartBlueGreen",
results,
"visits",
"Number of visits",
"date",
"#7C4DFF",
"#448AFF",
"#00BCD4",
"#1DE9B6"
);
drawLineChart(
"lineChartPinkOrange",
results,
"visits",
"Number of visits",
"date",
"#F44336",
"#F50057",
"#FF4081",
"#FF9100"
);
}

I hope you enjoyed this tutorial ❤.

If you have any questions, please use the comments section below.

Thanks!

About the author

I’m Valeria and I am passionate about data discovery via beautiful visualisations and analytics. I hope you enjoyed this post!

You can find me on Twitter and Instagram, or visit my page at valeria.io.

--

--