Categories
Chart.js

Chart.js — Options

We can make creating charts on a web page easy with Chart.js.

In this article, we’ll look at how to create charts with Chart.js.

Printing Resizable Charts

We can add an event handler for the beforeprint event to trigger the resizing of the charts before we print them.

For example, we can write:

window.onbeforeprint = () => {
  for (const id in Chart.instances) {
    Chart.instances[id].resize();
  }
}

to add the beforeprint handler and resize all the chart instances that are found with Chart.instances .

Events

We can set which events a chart responds to.

For example, we can add the options.event property with an array of event name strings to set the events it responds to:

var ctx = document.getElementById('myChart').getContext('2d');
var myChart = new Chart(ctx, {
  type: 'bar',
  data: {
    labels: ['Red', 'Blue', 'Yellow'],
    datasets: [{
      label: '# of Votes',
      data: [12, 19, 3],
      backgroundColor: [
        'rgba(255, 99, 132, 0.2)',
        'rgba(54, 162, 235, 0.2)',
        'rgba(255, 206, 86, 0.2)',
      ],
      borderColor: [
        'rgba(255, 99, 132, 1)',
        'rgba(54, 162, 235, 1)',
        'rgba(255, 206, 86, 1)',
      ],
      borderWidth: 1
    }]
  },
  options: {
    events: ['click'],
    scales: {
      yAxes: [{
        ticks: {
          beginAtZero: true
        }
      }]
    }
  }
});

We have the ['click'] array so that it only respond to click events.

Interaction Modes

We can configure the interaction of tooltips.

For example, we can write:

var ctx = document.getElementById('myChart').getContext('2d');
var myChart = new Chart(ctx, {
  type: 'bar',
  data: {
    labels: ['Red', 'Blue', 'Yellow'],
    datasets: [{
      label: '# of Votes',
      data: [12, 19, 3],
      backgroundColor: [
        'rgba(255, 99, 132, 0.2)',
        'rgba(54, 162, 235, 0.2)',
        'rgba(255, 206, 86, 0.2)',
      ],
      borderColor: [
        'rgba(255, 99, 132, 1)',
        'rgba(54, 162, 235, 1)',
        'rgba(255, 206, 86, 1)',
      ],
      borderWidth: 1
    }]
  },
  options: {
    tooltips: {
      mode: 'point'
    },
    scales: {
      yAxes: [{
        ticks: {
          beginAtZero: true
        }
      }]
    }
  }
});

to find all the items that intersect the point.

We can get the items that are nearest to the point with the 'nearest' value.

This means that the tooltip is only triggered when the mouse position intersects an item in the graph.

Scriptable Options

We can set scriptable options with a function.

For example, we can change the color option dynamically by writing:

var ctx = document.getElementById('myChart').getContext('2d');
var myChart = new Chart(ctx, {
  type: 'bar',
  data: {
    labels: ['Red', 'Blue', 'Yellow'],
    datasets: [{
      label: '# of Votes',
      data: [-1, 19, 3],
      backgroundColor(context) {
        var index = context.dataIndex;
        var value = context.dataset.data[index];
        return value < 0 ? 'red' :
          index % 2 ? 'blue' :
          'green';
      },
      borderColor: [
        'rgba(255, 99, 132, 1)',
        'rgba(54, 162, 235, 1)',
        'rgba(255, 206, 86, 1)',
      ],
      borderWidth: 1
    }]
  },
  options: {
    scales: {
      yAxes: [{
        ticks: {
          beginAtZero: true
        }
      }]
    }
  }
});

We changed the background colors of the bars with the backgroundColor options.

index has the index of the graph.

value has the value of the y-axis.

So if value , we show red.

Otherwise, we alternate between blue and green.

Conclusion

We can change various options with Chart.js.

Also, we can resize charts to fit when we print them.

Categories
Chart.js

Chart.js — Fonts and Performance

We can make creating charts on a web page easy with Chart.js.

In this article, we’ll look at how to create charts with Chart.js.

Fonts

We can change the font settings by setting the options.legend.labels.fontColor properties.

For example, we can write:

Chart.defaults.global.defaultFontColor = 'red';

var ctx = document.getElementById('myChart').getContext('2d');
var myChart = new Chart(ctx, {
  type: 'bar',
  data: {
    labels: ['Red', 'Blue', 'Yellow'],
    datasets: [{
      label: '# of Votes',
      data: [2, 19, 3],
      backgroundColor: [
        'rgba(255, 99, 132, 1)',
        'rgba(54, 162, 235, 1)',
        'rgba(255, 206, 86, 1)',
      ],
      borderColor: [
        'rgba(255, 99, 132, 1)',
        'rgba(54, 162, 235, 1)',
        'rgba(255, 206, 86, 1)',
      ],
      borderWidth: 1
    }]
  },
  options: {
    scales: {
      yAxes: [{
        ticks: {
          beginAtZero: true
        }
      }]
    },
    legend: {
      labels: {
        fontColor: 'green'
      }
    }
  }
});

to change the color globally with the Chart.defaults.global.defaultFontColor property.

And we change the legend text’s color with the options.legend.labels.fontColor property.

Rotation

We can set the minRotation and maxRotation properties to the same value to avoid charts from having to automatically determine a value to use.

Sampling

Also, we can set the ticks.sampleSize option to determine how large our labels are by looking at a subset of them to render the axes faster.

Disable Animations

We can disable animations with the animation , responsiveAnimationDuration, and hover options.

For example, we can write;

var ctx = document.getElementById('myChart').getContext('2d');
var myChart = new Chart(ctx, {
  type: 'bar',
  data: {
    labels: ['Red', 'Blue', 'Yellow'],
    datasets: [{
      label: '# of Votes',
      data: [2, 19, 3],
      backgroundColor: [
        'rgba(255, 99, 132, 1)',
        'rgba(54, 162, 235, 1)',
        'rgba(255, 206, 86, 1)',
      ],
      borderColor: [
        'rgba(255, 99, 132, 1)',
        'rgba(54, 162, 235, 1)',
        'rgba(255, 206, 86, 1)',
      ],
      borderWidth: 1
    }]
  },
  options: {
    scales: {
      yAxes: [{
        ticks: {
          beginAtZero: true
        }
      }]
    },
    animation: {
      duration: 0
    },
    hover: {
      animationDuration: 0
    },
    responsiveAnimationDuration: 0
  }
});

to disable all the animations with the options property.

Disable Bezier Curves in Line Charts

We can disable bezier curves in a line charts since drawing a straight line is faster than with a bezier curve.

We can do that with:

var ctx = document.getElementById('myChart').getContext('2d');
var myChart = new Chart(ctx, {
  type: 'line',
  options: {
    elements: {
      line: {
        tension: 0
      }
    }
  },
  data: {
    labels: ['Red', 'Blue', 'Yellow'],
    datasets: [{
      label: '# of Votes',
      data: [2, 19, 3],
      borderColor: [
        'rgba(255, 99, 132, 1)',
        'rgba(54, 162, 235, 1)',
        'rgba(255, 206, 86, 1)',
      ],
      borderWidth: 1
    }]
  },
  options: {
    scales: {
      yAxes: [{
        ticks: {
          beginAtZero: true
        }
      }]
    }
  }
});

The options.eleemnts.line.tension property disables drawing a bezier curve.

Disable Line Drawing

We can also disable lien drawing with the showLines property in the datasets or options properties.

For example, we can write:

var ctx = document.getElementById('myChart').getContext('2d');
var myChart = new Chart(ctx, {
  type: 'line',
  data: {
    labels: ['Red', 'Blue', 'Yellow'],
    datasets: [{
      showLine: false,
      label: '# of Votes',
      data: [2, 19, 3],
      borderColor: [
        'rgba(255, 99, 132, 1)',
        'rgba(54, 162, 235, 1)',
        'rgba(255, 206, 86, 1)',
      ],
      borderWidth: 1
    }]
  },
  options: {
    scales: {
      yAxes: [{
        ticks: {
          beginAtZero: true
        }
      }]
    }
  }
});

to disable it for a dataset.

Conclusion

We can change the fonts with Chart.js.

Also, we can disable various animations and drawing to increase rendering performance.

Categories
Chart.js

Chart.js — Color Options

We can make creating charts on a web page easy with Chart.js.

In this article, we’ll look at how to create charts with Chart.js.

Indexable Options

Indexable options are options that are arrays.

For example, we can write:

var ctx = document.getElementById('myChart').getContext('2d');
var myChart = new Chart(ctx, {
  type: 'bar',
  data: {
    labels: ['Red', 'Blue', 'Yellow'],
    datasets: [{
      label: '# of Votes',
      data: [-1, 19, 3],
      backgroundColor: [
        'rgba(255, 99, 132, 0.2)',
        'rgba(54, 162, 235, 0.2)',
        'rgba(255, 206, 86, 0.2)',
      ],
      borderColor: [
        'rgba(255, 99, 132, 1)',
        'rgba(54, 162, 235, 1)',
        'rgba(255, 206, 86, 1)',
      ],
      borderWidth: 1
    }]
  },
  options: {
    scales: {
      yAxes: [{
        ticks: {
          beginAtZero: true
        }
      }]
    }
  }
});

We have the backgroundColor and borderColor options which are indexable options.

The values are set on the bars according to the bars’ indexes.

Option Context

The option content gives us contextual information when we resolving options.

They are used only with scriptable options.

The properties of the context object include:

  • chart — the chart we’re modifying
  • dataIndex — index of the current data
  • dataset — dataset at index datasetIndex
  • datasetIndex — index of the current dataset
  • hover — true if hovered

Colors

We can set the color options in various ways.

One way is to change the background color to a fill pattern.

For example, we can write:

var img = new Image();
img.src = 'https://www.toptal.com/designers/subtlepatterns/patterns/more-leaves.png';

img.onload = function() {
  var ctx = document.getElementById('myChart').getContext('2d');
  var fillPattern = ctx.createPattern(img, 'repeat');
  var myChart = new Chart(ctx, {
    type: 'bar',
    data: {
      labels: ['Red', 'Blue', 'Yellow'],
      datasets: [{
        label: '# of Votes',
        data: [2, 19, 3],
        backgroundColor: fillPattern,
        borderColor: [
          'rgba(255, 99, 132, 1)',
          'rgba(54, 162, 235, 1)',
          'rgba(255, 206, 86, 1)',
        ],
        borderWidth: 1
      }]
    },
    options: {
      scales: {
        yAxes: [{
          ticks: {
            beginAtZero: true
          }
        }]
      }
    }
  });
};

We created an Image instance and we called the createPattern method of the context to create a fill pattern that we can use in our chart bars.

'repeat' makes the pattern repeat to fill the bars.

Then we set that as the value of backgroundColor and it’ll show as the bar color.

Also, we can use the Patternomaly library to create our patterns.

We can use it with the following HTML:

<script src='https://cdn.jsdelivr.net/npm/chart.js@2.9.3/dist/Chart.min.js'></script>

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

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

Then we can create a chart by writing:

var ctx = document.getElementById('myChart').getContext('2d');
var myChart = new Chart(ctx, {
  type: 'bar',
  data: {
    labels: ['Red', 'Blue', 'Yellow'],
    datasets: [{
      label: '# of Votes',
      data: [2, 19, 3],
      backgroundColor: [
        pattern.draw('square', '#ff6384'),
        pattern.draw('circle', '#36a2eb'),
        pattern.draw('diamond', '#cc65fe'),
      ],
      borderColor: [
        'rgba(255, 99, 132, 1)',
        'rgba(54, 162, 235, 1)',
        'rgba(255, 206, 86, 1)',
      ],
      borderWidth: 1
    }]
  },
  options: {
    scales: {
      yAxes: [{
        ticks: {
          beginAtZero: true
        }
      }]
    }
  }
});

The pattern.draw method comes from the Patternomaly library.

'square' makes a square repeating pattern.

'circle' makes a circle repeating pattern.

And 'diamond' makes a diamond repeating pattern.

The 2nd argument is the background color.

Now we should see bars with the given background patterns.

Conclusion

We can create charts with various color options with Chart.js.

Categories
Chart.js

Getting Started with Chart.js

We can make creating charts on a web page easy with Chart.js.

In this article, we’ll look at how to create charts with Chart.js.

Installation

We can add the Chart.js library from CDN.

To do that, we write:

<script src='https://cdn.jsdelivr.net/npm/chart.js@2.9.3/dist/Chart.min.js'></script>

in our HTML.

Also, we can install the NPM package version by running:

npm install chart.js --save

The Bower package can be installed by running:

bower install chart.js --save

Creating a Chart

We can then create a chart by creating our canvas element:

<canvas id="myChart" width="400" height="400"></canvas>

And then we can add our JavaScript code for the graph:

var ctx = document.getElementById('myChart').getContext('2d');
var myChart = new Chart(ctx, {
  type: 'bar',
  data: {
    labels: ['Red', 'Blue', 'Yellow'],
    datasets: [{
      label: '# of Votes',
      data: [12, 19, 3],
      backgroundColor: [
        'rgba(255, 99, 132, 0.2)',
        'rgba(54, 162, 235, 0.2)',
        'rgba(255, 206, 86, 0.2)',
      ],
      borderColor: [
        'rgba(255, 99, 132, 1)',
        'rgba(54, 162, 235, 1)',
        'rgba(255, 206, 86, 1)',
      ],
      borderWidth: 1
    }]
  },
  options: {
    scales: {
      yAxes: [{
        ticks: {
          beginAtZero: true
        }
      }]
    }
  }
});

We get the canvas element’s context.

Then we use the Chart constructor to create our chart.

type has the chart type.

label has the legend label.

The labels property has the x-axis labels.

datasets has the data for the chart.

data has the y-axis cooredinates.

backgroundColor has the background color for the bars.

borderColor has the border color for the bars.

borderWidth has the border width.

options has some options for the graph.

scales has the graph scales.

We have the beginAtZero option set to true so that the y-axis starts at 0.

Accessible Charts

We can make our charts accessible with the aria-label and role attributes.

For example, we can write:

<canvas id="myChart" width="400" height="400" aria-label="bar chart" role="img"></canvas>

We can add fallback content with:

<canvas id="myChart" width="400" height="400" aria-label="bar chart" role="img">
  <p>fallback</p>
</canvas>

Responsive Charts

Charts can be made responsive with a wrapper element.

We style that remove the height and width from the canvas and put that in the wrapper element.

For instance, we can write:

<div class="chart-container" style="position: relative; height:40vh; width:80vw">
  <canvas id="myChart"></canvas>
</div>

We put the styles in the div instead of the canvas.

Now the chart should resize when we resize the screen.

The chart can also be programmatically resized:

var ctx = document.getElementById('myChart').getContext('2d');
var myChart = new Chart(ctx, {
  type: 'bar',
  data: {
    labels: ['Red', 'Blue', 'Yellow'],
    datasets: [{
      label: '# of Votes',
      data: [12, 19, 3],
      backgroundColor: [
        'rgba(255, 99, 132, 0.2)',
        'rgba(54, 162, 235, 0.2)',
        'rgba(255, 206, 86, 0.2)',
      ],
      borderColor: [
        'rgba(255, 99, 132, 1)',
        'rgba(54, 162, 235, 1)',
        'rgba(255, 206, 86, 1)',
      ],
      borderWidth: 1
    }]
  },
  options: {
    scales: {
      yAxes: [{
        ticks: {
          beginAtZero: true
        }
      }]
    }
  }
});

myChart.canvas.parentNode.style.height = '428px';
myChart.canvas.parentNode.style.width = '428px';

We changed the canvas’ parent node’s height and width.

Conclusion

We can create a simple chart with Chart.js with some JavaScript code.

Categories
Chart.js JavaScript React

Create a Line Chart with react-chartjs-2 – an Example

react-chartjs-2 is an easy to use library for creating all kinds of charts.

It’s based on Chart.js, which renders chart in an HTML canvas element.

We can use it to render charts in a canvas inside a React app.

To get started, we install Chart.js and react-chartjs-2 by running:

npm install --save react-chartjs-2 chart.js moment

We also installed moments to create dates for the x-axis labels.

Then we can write the following code:

import React from "react";
import { Line } from "react-chartjs-2";
import moment from "moment";

const startDate = new Date(2020, 0, 1);
const labels = [];
for (let i = 0; i < 6; i++) {
  const date = moment(startDate)
    .add(i, "days")
    .format("YYYY-MM-DD");
  labels.push(date.toString());
}

const data = canvas => {
  const ctx = canvas.getContext("2d");
  const gradient = ctx.createLinearGradient(0, 0, 100, 0);
  return {
    backgroundColor: gradient,
    labels,
    datasets: [
      {
        label: "# of Votes",
        data: [12, 19, 3, 5, 2, 3],
        borderWidth: 3,
        fill: false,
        borderColor: "green"
      }
    ]
  };
};

export default function App() {
  return (
    <div className="App">
      <Line data={data} />
    </div>
  );
}

We first create the x-axis labels and populate them in the labels array/

We did that by using the moment function and call add on it to add 1 day in each iteration of the for loop.

Then we create a data function, which takes the canvas object, which has the canvas element as the parameter.

Then we get the canvas from it and change the items that we want.

The function returns the options for our graph, including the data.

The object we return in data has various options.

It has the labels property to populate the x-axis labels.

backgroundColor has the color for our graph.

datasets has an array with an object with the data and some options for the line.

data has the y-axis values for each x-axis value.

borderWidth specifies the thickness of the line in pixels.

fill is set to false means that we don’t have any colors between the x-axis and our line.

label is the text label for our legend.

borderColor is the color of our line.

Once we have that code, we’ll see the following graph:

https://thewebdev.info/wp-content/uploads/2020/05/react-chartjs-2.png