Chart.js

API Documentation

Getting started

Download Chart.js

To download a zip, go to Chart.js on Github and choose the version that is right for your application.

To install via npm / bower:

npm install chart.js --save
bower install Chart.js --save

Installation

To import Chart.js using an old-school script tag:

<script src="Chart.js"></script>
<script>
    var myChart = new Chart({...})
</script>

To import Chart.js using an awesome module loader:


// Using CommonJS
var Chart = require('src/chart.js')
var myChart = new Chart({...})

// ES6
import Chart from 'src/chart.js'
let myChart = new Chart({...})

// Using requirejs
require(['path/to/Chartjs'], function(Chart){
 var myChart = new Chart({...})
})

Creating a Chart

To create a chart, we need to instantiate the Chart class. To do this, we need to pass in the node, jQuery instance, or 2d context of the canvas of where we want to draw the chart. Here's an example.

<canvas id="myChart" width="400" height="400"></canvas>
// Any of the following formats may be used
var ctx = document.getElementById("myChart");
var ctx = document.getElementById("myChart").getContext("2d");
var ctx = $("#myChart");

Once you have the element or context, you're ready to instantiate a pre-defined chart-type or create your own!

The following example instantiates a bar chart showing the number of votes for different colors and the y-axis starting at 0.

<canvas id="myChart" width="400" height="400"></canvas>
<script>
var ctx = document.getElementById("myChart");
var myChart = new Chart(ctx, {
    type: 'bar',
    data: {
        labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
        datasets: [{
            label: '# of Votes',
            data: [12, 19, 3, 5, 2, 3]
        }]
    },
    options: {
        scales: {
            yAxes: [{
                ticks: {
                    beginAtZero:true
                }
            }]
        }
    }
});
</script>

It's that easy to get started using Chart.js! From here you can explore the many options that can help you customise your charts with scales, tooltips, labels, colors, custom actions, and much more.

Global chart configuration

This concept was introduced in Chart.js 1.0 to keep configuration DRY, and allow for changing options globally across chart types, avoiding the need to specify options for each instance, or the default for a particular chart type.

Chart.js merges configurations and options in a few places with the global defaults using chart type defaults and scales defaults. This way you can be as specific as you want in your individual chart configs, or change the defaults for Chart.js as a whole.

The global options are defined in Chart.defaults.global.

Name Type Default Description
responsive Boolean true Resizes when the canvas container does.
responsiveAnimationDuration Number 0 Duration in milliseconds it takes to animate to new size after a resize event.
maintainAspectRatio Boolean true Maintain the original canvas aspect ratio (width / height) when resizing
events Array[String] ["mousemove", "mouseout", "click", "touchstart", "touchmove", "touchend"] Events that the chart should listen to for tooltips and hovering
hover Object - -
hover.onHover Function null Called when any of the events fire. Called in the context of the chart and passed an array of active elements (bars, points, etc)
hover.mode String 'single' Sets which elements hover. Acceptable options are 'single', 'label', or 'dataset'. single highlights the closest element. label highlights elements in all datasets at the same X value. dataset highlights the closest dataset.
hover.animationDuration Number 400 Duration in milliseconds it takes to animate hover style changes
onClick Function null Called if the event is of type 'mouseup' or 'click'. Called in the context of the chart and passed an array of active elements
defaultColor Color 'rgba(0,0,0,0.1)'
defaultFontColor Color '#666' Default font color for all text
defaultFontFamily String "'Helvetica Neue', 'Helvetica', 'Arial', sans-serif" Default font family for all text
defaultFontSize Number 12 Default font size (in px) for text. Does not apply to radialLinear scale point labels
defaultFontStyle String 'normal' Default font style. Does not apply to tooltip title or footer. Does not apply to chart title
legendCallback Function function (chart) { } Function to generate a legend. Receives the chart object to generate a legend from. Default implementation returns an HTML string.

The global options for the chart title is defined in Chart.defaults.global.title

Name Type Default Description
display Boolean false Show the title block
position String 'top' Position of the title. 'top' or 'bottom' are allowed
fullWidth Boolean true Marks that this box should take the full width of the canvas (pushing down other boxes)
fontColor Color '#666' Text color
fontFamily String 'Helvetica Neue'
fontSize Number 12
fontStyle String 'bold'
padding Number 10 Number of pixels to add above and below the title text
text String '' Title text

The global options for the chart legend is defined in Chart.defaults.global.legend

Name Type Default Description
display Boolean true Is the legend displayed
position String 'top' Position of the legend. Options are 'top' or 'bottom'
fullWidth Boolean true Marks that this box should take the full width of the canvas (pushing down other boxes)
onClick Function function(event, legendItem) {} A callback that is called when a click is registered on top of a label item
labels Object - -
labels.boxWidth Number 40 Width of coloured box
labels.fontSize Number 12 Font size
labels.fontStyle String "normal"
labels.fontColor Color "#666"
labels.fontFamily String "Helvetica Neue"
labels.padding Number 10 Padding between rows of colored boxes
labels.generateLabels: Function function(data) { } Generates legend items for each thing in the legend. Default implementation returns the text + styling for the color box. Styles that can be returned are fillStyle, strokeStyle, lineCap, lineDash, lineDashOffset, lineWidth, lineJoin. Return a hidden attribute to indicate that the label refers to something that is not visible. A strikethrough style will be given to the text in this case.

The global options for tooltips are defined in Chart.defaults.global.tooltips.

Name Type Default Description
enabled Boolean true
custom null
mode String 'single' Sets which elements appear in the tooltip. Acceptable options are 'single' or 'label'. single highlights the closest element. label highlights elements in all datasets at the same X value.
backgroundColor Color 'rgba(0,0,0,0.8)' Background color of the tooltip
Label There are three labels you can control. title, body, footer the star (*) represents one of these three. (i.e. titleFontFamily, footerSpacing)
*FontFamily String "'Helvetica Neue', 'Helvetica', 'Arial', sans-serif"
*FontSize Number 12
*FontStyle String title - "bold", body - "normal", footer - "bold"
*Spacing Number 2
*Color Color "#fff"
*Align String "left" text alignment. See MDN Canvas Documentation
titleMarginBottom Number 6 Margin to add on bottom of title section
footerMarginTop Number 6 Margin to add before drawing the footer
xPadding Number 6 Padding to add on left and right of tooltip
yPadding Number 6 Padding to add on top and bottom of tooltip
caretSize Number 5 Size, in px, of the tooltip arrow
cornerRadius Number 6 Radius of tooltip corner curves
multiKeyBackground Color "#fff" Color to draw behind the colored boxes when multiple items are in the tooltip
callbacks Object - V2.0 introduces callback functions as a replacement for the template engine in v1. The tooltip has the following callbacks for providing text. For all functions, 'this' will be the tooltip object create from the Chart.Tooltip constructor
Callback Functions All functions are called with the same arguments
xLabel String or Array[Strings] This is the xDataValue for each item to be displayed in the tooltip
yLabel String or Array[Strings] This is the yDataValue for each item to be displayed in the tooltip
index Number Data index.
data Object Data object passed to chart.
return String or Array[Strings] All functions must return either a string or an array of strings. Arrays of strings are treated as multiple lines of text.
callbacks.beforeTitle Function none Text to render before the title
callbacks.title Function function(tooltipItems, data) { //Pick first xLabel } Text to render as the title
callbacks.afterTitle Function none Text to render after the ttiel
callbacks.beforeBody Function none Text to render before the body section
callbacks.beforeLabel Function none Text to render before an individual label
callbacks.label Function function(tooltipItem, data) { // Returns "datasetLabel: tooltipItem.yLabel" } Text to render as label
callbacks.afterLabel Function none Text to render after an individual label
callbacks.afterBody Function none Text to render after the body section
callbacks.beforeFooter Function none Text to render before the footer section
callbacks.footer Function none Text to render as the footer
callbacks.afterFooter Function none Text to render after the footer section

The global options for animations are defined in Chart.defaults.global.animation.

Name Type Default Description
duration Number 1000 The number of milliseconds an animation takes.
easing String "easeOutQuart" Easing function to use.
onProgress Function none Callback called on each step of an animation. Passed a single argument, an object, containing the chart instance and an object with details of the animation.
onComplete Function none Callback called at the end of an animation. Passed the same arguments as onProgress

The global options for elements are defined in Chart.defaults.global.elements.

Name Type Default Description
arc Object - -
arc.backgroundColor Color Chart.defaults.global.defaultColor Default fill color for arcs
arc.borderColor Color "#fff" Default stroke color for arcs
arc.borderWidth Number 2 Default stroke width for arcs
line Object - -
line.lineTension Number 0.4 Default bezier curve tension. Set to 0 for no bezier curves.
line.backgroundColor Color Chart.defaults.global.defaultColor Default line fill color
line.borderWidth Number 3 Default line stroke width
line.borderColor Color Chart.defaults.global.defaultColor Default line stroke color
line.borderCapStyle String 'butt' Default line cap style. See MDN
line.borderDash Array [] Default line dash. See MDN
line.borderDashOffset Number 0.0 Default line dash offset. See MDN
line.borderJoinStyle String 'miter' Default line join style. See MDN
line.fill Boolean true
point Object - -
point.radius Number 3 Default point radius
point.pointStyle String 'circle' Default point style
point.backgroundColor Color Chart.defaults.global.defaultColor Default point fill color
point.borderWidth Number 1 Default point stroke width
point.borderColor Color Chart.defaults.global.defaultColor Default point stroke color
point.hitRadius Number 1 Extra radius added to point radius for hit detection
point.hoverRadius Number 4 Default point radius when hovered
point.hoverBorderWidth Number 1 Default stroke width when hovered
rectangle Object - -
rectangle.backgroundColor Color Chart.defaults.global.defaultColor Default bar fill color
rectangle.borderWidth Number 0 Default bar stroke width
rectangle.borderColor Color Chart.defaults.global.defaultColor Default bar stroke color
rectangle.borderSkipped String 'bottom' Default skipped (excluded) border for rectangle. Can be one of bottom, left, top, right

If for example, you wanted all charts created to be responsive, and resize when the browser window does, the following setting can be changed:

Chart.defaults.global.responsive = true;

Now, every time we create a chart, options.responsive will be true.

Colors

When supplying colors to Chart options, you can use a number of formats. You can specify the color as a string in hexadecimal, RGB, or HSL notations.

You can also pass a CanvasGradient object. You will need to create this before passing to the chart, but using it you can achieve some interesting effects.

The final option is to pass a CanvasPattern object. For example, if you wanted to fill a dataset with a pattern from an image you could do the following.

var img = new Image();
img.src = 'https://example.com/my_image.png';
img.onload = function() {
    var ctx = document.getElementById('canvas').getContext('2d');
    var fillPattern = ctx.CreatePattern(img, 'repeat');

    var chart = new Chart(ctx, {
        data: {
            labels: ['Item 1', 'Item 2', 'Item 3'],
            datasets: [{
                data: [10, 20, 30],
                backgroundColor: fillPattern
            }]
        }
    })
}

Line Chart

Introduction

A line chart is a way of plotting data points on a line.

Often, it is used to show trend data, and the comparison of two data sets.

Example usage

var myLineChart = new Chart(ctx, {
    type: 'line',
    data: data,
    options: options
});

Alternatively a line chart can be created using syntax similar to the v1.0 syntax

var myLineChart = Chart.Line(ctx, {
    data: data,
    options: options
});

Data structure

The following options can be included in a line chart dataset to configure options for that specific dataset.

All point* properties can be specified as an array. If these are set to an array value, the first value applies to the first point, the second value to the second point, and so on.

Property Type Usage
data Array<Number> The data to plot in a line
label String The label for the dataset which appears in the legend and tooltips
xAxisID String The ID of the x axis to plot this dataset on
yAxisID String The ID of the y axis to plot this dataset on
fill Boolean If true, fill the area under the line
lineTension Number Bezier curve tension of the line. Set to 0 to draw straightlines. Note This was renamed from 'tension' but the old name still works.
backgroundColor Color The fill color under the line. See Colors
borderWidth Number The width of the line in pixels
borderColor Color The color of the line.
borderCapStyle String Cap style of the line. See MDN
borderDash Array<Number> Length and spacing of dashes. See MDN
borderDashOffset Number Offset for line dashes. See MDN
borderJoinStyle String Line joint style. See MDN
pointBorderColor Color or Array<Color> The border color for points.
pointBackgroundColor Color or Array<Color> The fill color for points
pointBorderWidth Number or Array<Number> The width of the point border in pixels
pointRadius Number or Array<Number> The radius of the point shape. If set to 0, nothing is rendered.
pointHoverRadius Number or Array<Number> The radius of the point when hovered
pointHitRadius Number or Array<Number> The pixel size of the non-displayed point that reacts to mouse events
pointHoverBackgroundColor Color or Array<Color> Point background color when hovered
pointHoverBorderColor Color or Array<Color> Point border color when hovered
pointHoverBorderWidth Number or Array<Number> Border width of point when hovered
pointStyle String or Array<String> The style of point. Options include 'circle', 'triangle', 'rect', 'rectRot', 'cross', 'crossRot', 'star', 'line', and 'dash'

An example data object using these attributes is shown below.

var data = {
    labels: ["January", "February", "March", "April", "May", "June", "July"],
    datasets: [
        {
            label: "My First dataset",
            fill: false,
            lineTension: 0.1,
            backgroundColor: "rgba(75,192,192,0.4)",
            borderColor: "rgba(75,192,192,1)",
            borderCapStyle: 'butt',
            borderDash: [],
            borderDashOffset: 0.0,
            borderJoinStyle: 'miter',
            pointBorderColor: "rgba(75,192,192,1)",
            pointBackgroundColor: "#fff",
            pointBorderWidth: 1,
            pointHoverRadius: 5,
            pointHoverBackgroundColor: "rgba(75,192,192,1)",
            pointHoverBorderColor: "rgba(220,220,220,1)",
            pointHoverBorderWidth: 2,
            pointRadius: 1,
            pointHitRadius: 10,
            data: [65, 59, 80, 81, 56, 55, 40],
        }
    ]
};

The line chart requires an array of labels. This labels are shown on the X axis. There must be one label for each data point. More labels than datapoints are allowed, in which case the line ends at the last data point. The data for line charts is broken up into an array of datasets. Each dataset has a colour for the fill, a colour for the line and colours for the points and strokes of the points. These colours are strings just like CSS. You can use RGBA, RGB, HEX or HSL notation.

The label key on each dataset is optional, and can be used when generating a scale for the chart.

Chart options

These are the customisation options specific to Line charts. These options are merged with the global chart configuration options, and form the options of the chart.

The default options for line chart are defined in Chart.defaults.line.

Name Type Default Description
showLines Boolean true If false, the lines between points are not drawn
stacked Boolean false If true, lines stack on top of each other along the y axis.
hover.mode String "label" Label's hover mode. "label" is used since the x axis displays data by the index in the dataset.
elements Object - -
elements.point Object - -
elements.point.radius Number 3 Defines the size of the Point shape. Can be set to zero to skip rendering a point.
scales Object - -
scales.xAxes Array [{type:"category","id":"x-axis-0"}] Defines all of the x axes used in the chart. See the scale documentation for details on the available options.
Options for xAxes
type String "category" As defined in "Category".
id String "x-axis-0" Id of the axis so that data can bind to it.
scales.yAxes Array [{type:"linear","id":"y-axis-0"}] Defines all of the y axes used in the chart. See the scale documentation for details on the available options.
Options for yAxes
type String "linear" As defined in "Linear".
id String "y-axis-0" Id of the axis so that data can bind to it.

You can override these for your Chart instance by passing a member options into the Line method.

For example, we could have a line chart display without an x axis by doing the following. The config merge is smart enough to handle arrays so that you do not need to specify all axis settings to change one thing.

new Chart(ctx, {
    type: 'line',
    data: data,
    options: {
        xAxes: [{
            display: false
        }]
    }
});
// This will create a chart with all of the default options, merged from the global config,
// and the Line chart defaults, but this particular instance will have the x axis not displaying.

We can also change these defaults values for each Line type that is created, this object is available at Chart.defaults.line.

Bar Chart

Introduction

A bar chart is a way of showing data as bars.

It is sometimes used to show trend data, and the comparison of multiple data sets side by side.

Example usage

var myBarChart = new Chart(ctx, {
    type: 'bar',
    data: data,
    options: options
});

Data structure

The following options can be included in a bar chart dataset to configure options for that specific dataset.

Some properties can be specified as an array. If these are set to an array value, the first value applies to the first bar, the second value to the second bar, and so on.

Property Type Usage
data Array<Number> The data to plot as bars
label String The label for the dataset which appears in the legend and tooltips
xAxisID String The ID of the x axis to plot this dataset on
yAxisID String The ID of the y axis to plot this dataset on
backgroundColor Color or Array<Color> The fill color of the bars. See Colors
borderColor Color or Array<Color> Bar border color
borderWidth Number or Array<Number> Border width of bar in pixels
borderSkipped String or Array<String> Which edge to skip drawing the border for. Options are 'bottom', 'left', 'top', and 'right'
hoverBackgroundColor Color or Array<Color> Bar background color when hovered
hoverBorderColor Color or Array<Color> Bar border color when hovered
hoverBorderWidth Number or Array<Number> Border width of bar when hovered

An example data object using these attributes is shown below.

var data = {
    labels: ["January", "February", "March", "April", "May", "June", "July"],
    datasets: [
        {
            label: "My First dataset",
            backgroundColor: "rgba(255,99,132,0.2)",
            borderColor: "rgba(255,99,132,1)",
            borderWidth: 1,
            hoverBackgroundColor: "rgba(255,99,132,0.4)",
            hoverBorderColor: "rgba(255,99,132,1)",
            data: [65, 59, 80, 81, 56, 55, 40],
        }
    ]
};

The bar chart has the a very similar data structure to the line chart, and has an array of datasets, each with colours and an array of data. We have an array of labels too for display. In the example, we are showing the same data as the previous line chart example.

Chart Options

These are the customisation options specific to Bar charts. These options are merged with the global chart configuration options, and form the options of the chart.

The default options for bar chart are defined in Chart.defaults.bar.

Name Type Default Description
stacked Boolean false
hover.mode String "label" Label's hover mode. "label" is used since the x axis displays data by the index in the dataset.
scales Object - -
scales.xAxes Array The bar chart officially supports only 1 x-axis but uses an array to keep the API consistent. Use a scatter chart if you need multiple x axes.
Options for xAxes
type String "Category" As defined in Scales.
display Boolean true If true, show the scale.
id String "x-axis-1" Id of the axis so that data can bind to it
categoryPercentage Number 0.8 Percent (0-1) of the available width (the space between the gridlines for small datasets) for each data-point to use for the bars. Read More
barPercentage Number 0.9 Percent (0-1) of the available width each bar should be within the category percentage. 1.0 will take the whole category width and put the bars right next to each other. Read More
gridLines Object See Scales
gridLines.offsetGridLines Boolean true If true, the bars for a particular data point fall between the grid lines. If false, the grid line will go right down the middle of the bars.
scales.yAxes Array [{ type: "linear" }]
Options for xAxes
type String "linear" As defined in Scales.
display Boolean true If true, show the scale.
id String "y-axis-1" Id of the axis so that data can bind to it.

You can override these for your Chart instance by passing a second argument into the Bar method as an object with the keys you want to override.

For example, we could have a bar chart without a stroke on each bar by doing the following:

new Chart(ctx, {
    type: "bar",
    data: data,
    options: {
        scales: {
                xAxes: [{
                        stacked: true
                }],
                yAxes: [{
                        stacked: true
                }]
            }
        }
    }
});
// This will create a chart with all of the default options, merged from the global config,
//  and the Bar chart defaults but this particular instance will have `stacked` set to true
// for both x and y axes.

We can also change these defaults values for each Bar type that is created, this object is available at Chart.defaults.bar.

barPercentage vs categoryPercentage

The following shows the relationship between the bar percentage option and the category percentage option.

// categoryPercentage: 1.0
// barPercentage: 1.0
Bar:        | 1.0 | 1.0 |
Category:   |    1.0    |   
Sample:     |===========|

// categoryPercentage: 1.0
// barPercentage: 0.5
Bar:          |.5|  |.5|
Category:  |      1.0     |   
Sample:    |==============|

// categoryPercentage: 0.5
// barPercentage: 1.0
Bar:            |1.||1.|
Category:       |  .5  |   
Sample:     |==============|

Radar Chart

Introduction

A radar chart is a way of showing multiple data points and the variation between them.

They are often useful for comparing the points of two or more different data sets.

Example usage

var myRadarChart = new Chart(ctx, {
    type: 'radar',
    data: data,
    options: options
});

Data structure

The following options can be included in a radar chart dataset to configure options for that specific dataset.

All point* properties can be specified as an array. If these are set to an array value, the first value applies to the first point, the second value to the second point, and so on.

Property Type Usage
data Array<Number> The data to plot in a line
label String The label for the dataset which appears in the legend and tooltips
fill Boolean If true, fill the area under the line
lineTension Number Bezier curve tension of the line. Set to 0 to draw straightlines. Note This was renamed from 'tension' but the old name still works.
backgroundColor Color The fill color under the line. See Colors
borderWidth Number The width of the line in pixels
borderColor Color The color of the line.
borderCapStyle String Cap style of the line. See MDN
borderDash Array<Number> Length and spacing of dashes. See MDN
borderDashOffset Number Offset for line dashes. See MDN
borderJoinStyle String Line joint style. See MDN
pointBorderColor Color or Array<Color> The border color for points.
pointBackgroundColor Color or Array<Color> The fill color for points
pointBorderWidth Number or Array<Number> The width of the point border in pixels
pointRadius Number or Array<Number> The radius of the point shape. If set to 0, nothing is rendered.
pointHoverRadius Number or Array<Number> The radius of the point when hovered
hitRadius Number or Array<Number> The pixel size of the non-displayed point that reacts to mouse events
pointHoverBackgroundColor Color or Array<Color> Point background color when hovered
pointHoverBorderColor Color or Array<Color> Point border color when hovered
pointHoverBorderWidth Number or Array<Number> Border width of point when hovered
pointStyle String or Array<String> The style of point. Options include 'circle', 'triangle', 'rect', 'rectRot', 'cross', 'crossRot', 'star', 'line', and 'dash'

An example data object using these attributes is shown below.

var data = {
    labels: ["Eating", "Drinking", "Sleeping", "Designing", "Coding", "Cycling", "Running"],
    datasets: [
        {
            label: "My First dataset",
            backgroundColor: "rgba(179,181,198,0.2)",
            borderColor: "rgba(179,181,198,1)",
            pointBackgroundColor: "rgba(179,181,198,1)",
            pointBorderColor: "#fff",
            pointHoverBackgroundColor: "#fff",
            pointHoverBorderColor: "rgba(179,181,198,1)",
            data: [65, 59, 90, 81, 56, 55, 40]
        },
        {
            label: "My Second dataset",
            backgroundColor: "rgba(255,99,132,0.2)",
            borderColor: "rgba(255,99,132,1)",
            pointBackgroundColor: "rgba(255,99,132,1)",
            pointBorderColor: "#fff",
            pointHoverBackgroundColor: "#fff",
            pointHoverBorderColor: "rgba(255,99,132,1)",
            data: [28, 48, 40, 19, 96, 27, 100]
        }
    ]
};

For a radar chart, to provide context of what each point means, we include an array of strings that show around each point in the chart. For the radar chart data, we have an array of datasets. Each of these is an object, with a fill colour, a stroke colour, a colour for the fill of each point, and a colour for the stroke of each point. We also have an array of data values. The label key on each dataset is optional, and can be used when generating a scale for the chart.

Chart Options

These are the customisation options specific to Radar charts. These options are merged with the global chart configuration options, and form the options of the chart.

The default options for radar chart are defined in Chart.defaults.radar.

Name Type Default Description
scale Object See Scales and Defaults for Radial Linear Scale Options for the one scale used on the chart. Use this to style the ticks, labels, and grid lines.
scale.type String "radialLinear" As defined in "Radial Linear".
elements.line Object Options for all line elements used on the chart, as defined in the global elements, duplicated here to show Radar chart specific defaults.
elements.line.lineTension Number 0 Tension exhibited by lines when calculating splineCurve. Setting to 0 creates straight lines.

You can override these for your Chart instance by passing a second argument into the Radar method as an object with the keys you want to override.

For example, we could have a radar chart without a point for each on piece of data by doing the following:

new Chart(ctx, {
    type: "radar",
    data: data,
    options: {
            scale: {
                reverse: true,
                ticks: {
                    beginAtZero: true
                }
            }
    }
});
// This will create a chart with all of the default options, merged from the global config,
//  and the Radar chart defaults but this particular instance's scale will be reversed as
// well as the ticks beginning at zero.

We can also change these defaults values for each Radar type that is created, this object is available at Chart.defaults.radar.

Polar Area Chart

Introduction

Polar area charts are similar to pie charts, but each segment has the same angle - the radius of the segment differs depending on the value.

This type of chart is often useful when we want to show a comparison data similar to a pie chart, but also show a scale of values for context.

Example usage

new Chart(ctx, {
    data: data,
    type: 'polarArea',
    options: options
});

Data structure

The following options can be included in a polar area chart dataset to configure options for that specific dataset.

Some properties are specified as arrays. The first value applies to the first bar, the second value to the second bar, and so on.

Property Type Usage
data Array<Number> The data to plot as bars
label String The label for the dataset which appears in the legend and tooltips
backgroundColor Array<Color> The fill color of the arcs. See Colors
borderColor Array<Color> Arc border color
borderWidth Array<Number> Border width of arcs in pixels
hoverBackgroundColor Array<Color> Arc background color when hovered
hoverBorderColor Array<Color> Arc border color when hovered
hoverBorderWidth Array<Number> Border width of arc when hovered

An example data object using these attributes is shown below.

var data = {
    datasets: [{
        data: [
            11,
            16,
            7,
            3,
            14
        ],
        backgroundColor: [
            "#FF6384",
            "#4BC0C0",
            "#FFCE56",
            "#E7E9ED",
            "#36A2EB"
        ],
        label: 'My dataset' // for legend
    }],
    labels: [
        "Red",
        "Green",
        "Yellow",
        "Grey",
        "Blue"
    ]
};

As you can see, for the chart data you pass in an array of objects, with a value and a colour. The value attribute should be a number, while the color attribute should be a string. Similar to CSS, for this string you can use HEX notation, RGB, RGBA or HSL.

Chart options

These are the customisation options specific to Polar Area charts. These options are merged with the global chart configuration options, and form the options of the chart.

Name Type Default Description
scale Object See Scales and Defaults for Radial Linear Scale Options for the one scale used on the chart. Use this to style the ticks, labels, and grid.
scale.type String "radialLinear" As defined in "Radial Linear".
scale.lineArc Boolean true When true, lines are circular.
animateRotate Boolean true If true, will animate the rotation of the chart.
animateScale Boolean true If true, will animate scaling the chart.
legend.labels.generateLabels Function function(data) {} Returns labels for each the legend
legend.onClick Function function(event, legendItem) {} ` Handles clicking an individual legend item
legendCallback Function function(chart) Generates the HTML legend via calls to generateLegend

You can override these for your Chart instance by passing a second argument into the PolarArea method as an object with the keys you want to override.

For example, we could have a polar area chart with a black stroke on each segment like so:

new Chart(ctx, {
    data: data,
    type: "polarArea",
    options: {
        elements: {
            arc: {
                borderColor: "#000000"
            }
        }
    }
});
// This will create a chart with all of the default options, merged from the global config,
// and the PolarArea chart defaults but this particular instance will have `elements.arc.borderColor` set to `"#000000"`.

We can also change these defaults values for each PolarArea type that is created, this object is available at Chart.defaults.polarArea.

Pie & Doughnut Charts

Introduction

Pie and doughnut charts are probably the most commonly used chart there are. They are divided into segments, the arc of each segment shows the proportional value of each piece of data.

They are excellent at showing the relational proportions between data.

Pie and doughnut charts are effectively the same class in Chart.js, but have one different default value - their cutoutPercentage. This equates what percentage of the inner should be cut out. This defaults to 0 for pie charts, and 50 for doughnuts.

They are also registered under two aliases in the Chart core. Other than their different default value, and different alias, they are exactly the same.

Example usage

// For a pie chart
var myPieChart = new Chart(ctx,{
    type: 'pie',
    data: data,
    options: options
});
// And for a doughnut chart
var myDoughnutChart = new Chart(ctx, {
    type: 'doughnut',
    data: data,
    options: options
});

Data structure

Property Type Usage
data Array<Number> The data to plot as bars
label String The label for the dataset which appears in the legend and tooltips
backgroundColor Array<Color> The fill color of the arcs. See Colors
borderColor Array<Color> Arc border color
borderWidth Array<Number> Border width of arcs in pixels
hoverBackgroundColor Array<Color> Arc background color when hovered
hoverBorderColor Array<Color> Arc border color when hovered
hoverBorderWidth Array<Number> Border width of arc when hovered

An example data object using these attributes is shown below.

var data = {
    labels: [
        "Red",
        "Green",
        "Yellow"
    ],
    datasets: [
        {
            data: [300, 50, 100],
            backgroundColor: [
                "#FF6384",
                "#36A2EB",
                "#FFCE56"
            ],
            hoverBackgroundColor: [
                "#FF6384",
                "#36A2EB",
                "#FFCE56"
            ]
        }]
};

For a pie chart, datasets need to contain an array of data points. The data points should be a number, Chart.js will total all of the numbers and calculate the relative proportion of each. You can also add an array of background colors. The color attributes should be a string. Similar to CSS, for this string you can use HEX notation, RGB, RGBA or HSL.

Chart options

These are the customisation options specific to Pie & Doughnut charts. These options are merged with the global chart configuration options, and form the options of the chart.

Name Type Default Description
cutoutPercentage Number 50 - for doughnut, 0 - for pie The percentage of the chart that is cut out of the middle.
rotation Number -0.5 * Math.PI Starting angle to draw arcs from
circumference Number 2 * Math.PI Sweep to allow arcs to cover
animation.animateRotate Boolean true If true, will animate the rotation of the chart.
animation.animateScale Boolean false If true, will animate scaling the Doughnut from the centre.
legend.labels.generateLabels Function function(data) {} Returns labels for each the legend
legend.onClick Function function(event, legendItem) {} ` Handles clicking an individual legend item

You can override these for your Chart instance by passing a second argument into the Doughnut method as an object with the keys you want to override.

For example, we could have a doughnut chart that animates by scaling out from the centre like so:

new Chart(ctx,{
    type:"doughnut",
    animation:{
        animateScale:true
    }
});
// This will create a chart with all of the default options, merged from the global config,
// and the Doughnut chart defaults but this particular instance will have `animateScale` set to `true`.

We can also change these default values for each Doughnut type that is created, this object is available at Chart.defaults.doughnut. Pie charts also have a clone of these defaults available to change at Chart.defaults.pie, with the only difference being cutoutPercentage being set to 0.

Scales

Scales in v2.0 of Chart.js are significantly more powerful, but also different than those of v1.0.

  • Multiple x & y axes are now supported.
  • A built-in label auto-skip feature now detects would-be overlapping ticks and labels and removes every nth label to keep things displaying normally.
  • Scale titles are now supported
  • New scale types can be extended without writing an entirely new chart type

Every scale extends a core scale class with the following options:

Name Type Default Description
type String Chart specific. Type of scale being employed. Custom scales can be created and registered with a string key. Options: "category", "linear", "logarithmic", "time", "radialLinear"
display Boolean true If true, show the scale including gridlines, ticks, and labels. Overrides gridLines.display, scaleLabel.display, and ticks.display.
position String "left" Position of the scale. Possible values are top, left, bottom and right.
beforeUpdate Function undefined Callback called before the update process starts. Passed a single argument, the scale instance.
beforeSetDimensions Function undefined Callback that runs before dimensions are set. Passed a single argument, the scale instance.
afterSetDimensions Function undefined Callback that runs after dimensions are set. Passed a single argument, the scale instance.
beforeDataLimits Function undefined Callback that runs before data limits are determined. Passed a single argument, the scale instance.
afterDataLimits Function undefined Callback that runs after data limits are determined. Passed a single argument, the scale instance.
beforeBuildTicks Function undefined Callback that runs before ticks are created. Passed a single argument, the scale instance.
afterBuildTicks Function undefined Callback that runs after ticks are created. Useful for filtering ticks. Passed a single argument, the scale instance.
beforeTickToLabelConversion Function undefined Callback that runs before ticks are converted into strings. Passed a single argument, the scale instance.
afterTickToLabelConversion Function undefined Callback that runs after ticks are converted into strings. Passed a single argument, the scale instance.
beforeCalculateTickRotation Function undefined Callback that runs before tick rotation is determined. Passed a single argument, the scale instance.
afterCalculateTickRotation Function undefined Callback that runs after tick rotation is determined. Passed a single argument, the scale instance.
beforeFit Function undefined Callback that runs before the scale fits to the canvas. Passed a single argument, the scale instance.
afterFit Function undefined Callback that runs after the scale fits to the canvas. Passed a single argument, the scale instance.
afterUpdate Function undefined Callback that runs at the end of the update process. Passed a single argument, the scale instance.
gridLines Object - Options for the grid lines that run perpendicular to the axis.
gridLines.display Boolean true
gridLines.color Color "rgba(0, 0, 0, 0.1)" Color of the grid lines.
gridLines.lineWidth Number 1 Stroke width of grid lines
gridLines.drawOnChartArea Boolean true If true, draw lines on the chart area inside the axis lines. This is useful when there are multiple axes and you need to control which grid lines are drawn
gridLines.drawTicks Boolean true If true, draw lines beside the ticks in the axis area beside the chart.
gridLines.tickMarkLength Number 10 Length in pixels that the grid lines will draw into the axis area.
gridLines.zeroLineWidth Number 1 Stroke width of the grid line for the first index (index 0).
gridLines.zeroLineColor Color "rgba(0, 0, 0, 0.25)" Stroke color of the grid line for the first index (index 0).
gridLines.offsetGridLines Boolean false If true, offset labels from grid lines.
scaleLabel Object Title for the entire axis.
scaleLabel.display Boolean false
scaleLabel.labelString String "" The text for the title. (i.e. "# of People", "Response Choices")
scaleLabel.fontColor Color "#666" Font color for the scale title.
scaleLabel.fontFamily String "Helvetica Neue" Font family for the scale title, follows CSS font-family options.
scaleLabel.fontSize Number 12 Font size for the scale title.
scaleLabel.fontStyle String "normal" Font style for the scale title, follows CSS font-style options (i.e. normal, italic, oblique, initial, inherit).
ticks Object Settings for the labels that run along the axis.
ticks.beginAtZero Boolean false If true the scale will be begin at 0, if false the ticks will begin at your smallest data value.
ticks.fontColor Color "#666" Font color for the tick labels.
ticks.fontFamily String "Helvetica Neue" Font family for the tick labels, follows CSS font-family options.
ticks.fontSize Number 12 Font size for the tick labels.
ticks.fontStyle String "normal" Font style for the tick labels, follows CSS font-style options (i.e. normal, italic, oblique, initial, inherit).
ticks.maxRotation Number 90 Maximum rotation for tick labels when rotating to condense labels. Note: Rotation doesn't occur until necessary. Note: Only applicable to horizontal scales.
ticks.minRotation Number 20 currently not-implemented Minimum rotation for tick labels when condensing is necessary. Note: Only applicable to horizontal scales.
ticks.maxTicksLimit Number 11 Maximum number of ticks and gridlines to show. If not defined, it will limit to 11 ticks but will show all gridlines.
ticks.padding Number 10 Padding between the tick label and the axis. Note: Only applicable to horizontal scales.
ticks.mirror Boolean false Flips tick labels around axis, displaying the labels inside the chart instead of outside. Note: Only applicable to vertical scales.
ticks.reverse Boolean false Reverses order of tick labels.
ticks.display Boolean true If true, show the ticks.
ticks.suggestedMin Number - User defined minimum number for the scale, overrides minimum value except for if it is higher than the minimum value.
ticks.suggestedMax Number - User defined maximum number for the scale, overrides maximum value except for if it is lower than the maximum value.
ticks.min Number - User defined minimum number for the scale, overrides minimum value.
ticks.max Number - User defined minimum number for the scale, overrides maximum value
ticks.autoSkip Boolean true If true, automatically calculates how many labels that can be shown and hides labels accordingly. Turn it off to show all labels no matter what
ticks.callback Function function(value) { return '' + value; } Returns the string representation of the tick value as it should be displayed on the chart.

The callback method may be used for advanced tick customization. The following callback would display every label in scientific notation

{
    scales: {
        xAxes: [{
            ticks: {
                // Return an empty string to draw the tick line but hide the tick label
                // Return `null` or `undefined` to hide the tick line entirely
                   userCallback: function(value, index, values) {
                    return value.toExponential();
                }
            }
        }]
    }
}

Category Scale

The category scale will be familiar to those who have used v1.0. Labels are drawn in from the labels array included in the chart data.

The category scale extends the core scale class with the following tick template:

{
    position: "bottom",
}

The ticks.min and ticks.max attributes may be used with the category scale. Unlike other scales, the value of these attributes must simply be something that can be found in the labels array of the data object.

Linear Scale

The linear scale can be used to display numerical data. It can be placed on either the x or y axis. The scatter chart type automatically configures a line chart to use one of these scales for the x axis.

The linear scale extends the core scale class with the following tick template:

{
    position: "left",
    ticks: {
        callback: function(tickValue, index, ticks) {
            var delta = ticks[1] - ticks[0];

            // If we have a number like 2.5 as the delta, figure out how many decimal places we need
            if (Math.abs(delta) > 1) {
                if (tickValue !== Math.floor(tickValue)) {
                    // not an integer
                    delta = tickValue - Math.floor(tickValue);
                }
            }

            var logDelta = helpers.log10(Math.abs(delta));
            var tickString = '';

            if (tickValue !== 0) {
                var numDecimal = -1 * Math.floor(logDelta);
                numDecimal = Math.max(Math.min(numDecimal, 20), 0); // toFixed has a max of 20 decimal places
                tickString = tickValue.toFixed(numDecimal);
            } else {
                tickString = '0'; // never show decimal places for 0
            }

              return tickString;
          }
    }
}

It also provides additional configuration options:

Name Type Default Description
ticks.stepSize Number - User defined fixed step size for the scale. If set, the scale ticks will be enumerated by multiple of stepSize, having one tick per increment. If not set, the ticks are labeled automatically using the nice numbers algorithm.

Logarithmic Scale

The logarithmic scale is used to display logarithmic data of course. It can be placed on either the x or y axis.

The log scale extends the core scale class with the following tick template:

{
    position: "left",
    ticks: {
        callback: function(value) {
            var remain = value / (Math.pow(10, Math.floor(Chart.helpers.log10(value))));

            if (remain === 1 || remain === 2 || remain === 5) {
                return value.toExponential();
            } else {
                return '';
            }
        }
    }
}

Time Scale

The time scale is used to display times and dates. It can be placed on the x axis. When building its ticks, it will automatically calculate the most comfortable unit base on the size of the scale.

The time scale extends the core scale class with the following tick template:

{
    position: "bottom",
    time: {
        // string/callback - By default, date objects are expected. You may use a pattern string from http://momentjs.com/docs/#/parsing/string-format/ to parse a time string format, or use a callback function that is passed the label, and must return a moment() instance.
        parser: false,
        // string - By default, unit will automatically be detected.  Override with 'week', 'month', 'year', etc. (see supported time measurements)
        unit: false,

        // Number - The number of steps of the above unit between ticks
        unitStepSize: 1

        // string - By default, no rounding is applied.  To round, set to a supported time unit eg. 'week', 'month', 'year', etc.
        round: false,

        // Moment js for each of the units. Replaces `displayFormat`
        // To override, use a pattern string from http://momentjs.com/docs/#/displaying/format/
        displayFormats: {
            'millisecond': 'SSS [ms]',
            'second': 'h:mm:ss a', // 11:20:01 AM
            'minute': 'h:mm:ss a', // 11:20:01 AM
            'hour': 'MMM D, hA', // Sept 4, 5PM
            'day': 'll', // Sep 4 2015
            'week': 'll', // Week 46, or maybe "[W]WW - YYYY" ?
            'month': 'MMM YYYY', // Sept 2015
            'quarter': '[Q]Q - YYYY', // Q3
            'year': 'YYYY', // 2015
        },
        // Sets the display format used in tooltip generation
        tooltipFormat: ''
    },
}

The following time measurements are supported:

{
    'millisecond': {
        display: 'SSS [ms]', // 002 ms
        maxStep: 1000,
    },
    'second': {
        display: 'h:mm:ss a', // 11:20:01 AM
        maxStep: 60,
    },
    'minute': {
        display: 'h:mm:ss a', // 11:20:01 AM
        maxStep: 60,
    },
    'hour': {
        display: 'MMM D, hA', // Sept 4, 5PM
        maxStep: 24,
    },
    'day': {
        display: 'll', // Sep 4 2015
        maxStep: 7,
    },
    'week': {
        display: 'll', // Week 46, or maybe "[W]WW - YYYY" ?
        maxStep: 4.3333,
    },
    'month': {
        display: 'MMM YYYY', // Sept 2015
        maxStep: 12,
    },
    'quarter': {
        display: '[Q]Q - YYYY', // Q3
        maxStep: 4,
    },
    'year': {
        display: 'YYYY', // 2015
        maxStep: false,
    },
}

Radial Linear Scale

The radial linear scale is used specifically for the radar chart type.

The radial linear scale extends the core scale class with the following tick template:

{
    animate: true,
    lineArc: false,
    position: "chartArea",

    angleLines: {
        display: true,
        color: "rgba(0, 0, 0, 0.1)",
        lineWidth: 1
    },

    // label settings
    ticks: {
        //Boolean - Show a backdrop to the scale label
        showLabelBackdrop: true,

        //String - The colour of the label backdrop
        backdropColor: "rgba(255,255,255,0.75)",

        //Number - The backdrop padding above & below the label in pixels
        backdropPaddingY: 2,

        //Number - The backdrop padding to the side of the label in pixels
        backdropPaddingX: 2,

        //Number - Limit the maximum number of ticks and gridlines
        maxTicksLimit: 11,
    },

    pointLabels: {
        //String - Point label font declaration
        fontFamily: "'Arial'",

        //String - Point label font weight
        fontStyle: "normal",

        //Number - Point label font size in pixels
        fontSize: 10,

        //String - Point label font colour
        fontColor: "#666",

        //Function - Used to determine point labels to show in scale
        callback: function(pointLabel) {
            return pointLabel;
        }
    },
}

Advanced usage

Prototype methods

For each chart, there are a set of global prototype methods on the shared ChartType which you may find useful. These are available on all charts created with Chart.js, but for the examples, let's use a line chart we've made.

// For example:
var myLineChart = new Chart(ctx, config);

.destroy()

Use this to destroy any chart instances that are created. This will clean up any references stored to the chart object within Chart.js, along with any associated event listeners attached by Chart.js. This must be called before the canvas is reused for a new chart.

// Destroys a specific chart instance
myLineChart.destroy();

.update(duration, lazy)

Triggers an update of the chart. This can be safely called after replacing the entire data object. This will update all scales, legends, and then re-render the chart.

// duration is the time for the animation of the redraw in miliseconds
// lazy is a boolean. if true, the animation can be interupted by other animations
myLineChart.data.datasets[0].data[2] = 50; // Would update the first dataset's value of 'March' to be 50
myLineChart.update(); // Calling update now animates the position of March from 90 to 50.

.render(duration, lazy)

Triggers a redraw of all chart elements. Note, this does not update elements for new data. Use .update() in that case.

// duration is the time for the animation of the redraw in miliseconds
// lazy is a boolean. if true, the animation can be interupted by other animations
myLineChart.render(duration, lazy);

.stop()

Use this to stop any current animation loop. This will pause the chart during any current animation frame. Call .render() to re-animate.

// Stops the charts animation loop at its current frame
myLineChart.stop();
// => returns 'this' for chainability

.resize()

Use this to manually resize the canvas element. This is run each time the canvas container is resized, but you can call this method manually if you change the size of the canvas nodes container element.

// Resizes & redraws to fill its container element
myLineChart.resize();
// => returns 'this' for chainability

.clear()

Will clear the chart canvas. Used extensively internally between animation frames, but you might find it useful.

// Will clear the canvas that myLineChart is drawn on
myLineChart.clear();
// => returns 'this' for chainability

.toBase64Image()

This returns a base 64 encoded string of the chart in it's current state.

myLineChart.toBase64Image();
// => returns png data url of the image on the canvas

.generateLegend()

Returns an HTML string of a legend for that chart. The legend is generated from the legendCallback in the options.

myLineChart.generateLegend();
// => returns HTML string of a legend for this chart

.getElementAtEvent(e)

Calling getElementAtEvent(event) on your Chart instance passing an argument of an event, or jQuery event, will return the single element at the event position. If there are multiple items within range, only the first is returned

myLineChart.getElementAtEvent(e);
// => returns the first element at the event point.

.getElementsAtEvent(e)

Looks for the element under the event point, then returns all elements at the same data index. This is used internally for 'label' mode highlighting.

Calling getElementsAtEvent(event) on your Chart instance passing an argument of an event, or jQuery event, will return the point elements that are at that the same position of that event.

canvas.onclick = function(evt){
    var activePoints = myLineChart.getElementsAtEvent(evt);
    // => activePoints is an array of points on the canvas that are at the same position as the click event.
};

This functionality may be useful for implementing DOM based tooltips, or triggering custom behaviour in your application.

.getDatasetAtEvent(e)

Looks for the element under the event point, then returns all elements from that dataset. This is used internally for 'dataset' mode highlighting

myLineChart.getDatasetAtEvent(e);
// => returns an array of elements

External Tooltips

You can enable custom tooltips in the global or chart configuration like so:

var myPieChart = new Chart(ctx, {
    type: 'pie',
    data: data,
    options: {
        tooltips: {
            custom: function(tooltip) {
                // tooltip will be false if tooltip is not visible or should be hidden
                if (!tooltip) {
                    return;
                }

                // Otherwise, tooltip will be an object with all tooltip properties like:

                // tooltip.caretSize
                // tooltip.caretPadding
                // tooltip.chart
                // tooltip.cornerRadius
                // tooltip.fillColor
                // tooltip.font...
                // tooltip.text
                // tooltip.x
                // tooltip.y
                // etc...
            }
        }
    }
});

See sample/line-customTooltips.html for examples on how to get started.

Writing new scale types

Starting with Chart.js 2.0 scales can be individually extended. Scales should always derive from Chart.Scale.

var MyScale = Chart.Scale.extend({
    /* extensions ... */
});

// MyScale is now derived from Chart.Scale

Once you have created your scale class, you need to register it with the global chart object so that it can be used. A default config for the scale may be provided when registering the constructor. The first parameter to the register function is a string key that is used later to identify which scale type to use for a chart.

Chart.scaleService.registerScaleType('myScale', MyScale, defaultConfigObject);

To use the new scale, simply pass in the string key to the config when creating a chart.

var lineChart = new Chart(ctx, {
    data: data,
    type: 'line',
    options: {
        scales: {
            yAxes: [{
                type: 'myScale' // this is the same key that was passed to the registerScaleType function
            }]
        }
    }
})

Scale Properties

Scale instances are given the following properties during the fitting process.

{
    left: Number, // left edge of the scale bounding box
    right: Number, // right edge of the bounding box'
    top: Number, 
    bottom: Number,
    width: Number, // the same as right - left
    height: Number, // the same as bottom - top

    // Margin on each side. Like css, this is outside the bounding box. 
    margins: {
        left: Number,
        right: Number,
        top: Number,
        bottom: Number,
    },

    // Amount of padding on the inside of the bounding box (like CSS)
    paddingLeft: Number,
    paddingRight: Number,
    paddingTop: Number,
    paddingBottom: Number,
}

Scale Interface

To work with Chart.js, custom scale types must implement the following interface.

{
    // Determines the data limits. Should set this.min and this.max to be the data max/min
    determineDataLimits: function() {},

    // Generate tick marks. this.chart is the chart instance. The data object can be accessed as this.chart.data
    // buildTicks() should create a ticks array on the axis instance, if you intend to use any of the implementations from the base class
    buildTicks: function() {},

    // Get the value to show for the data at the given index of the the given dataset, ie this.chart.data.datasets[datasetIndex].data[index]
    getLabelForIndex: function(index, datasetIndex) {},

    // Get the pixel (x coordinate for horizontal axis, y coordinate for vertical axis) for a given value
    // @param index: index into the ticks array
    // @param includeOffset: if true, get the pixel halway between the given tick and the next
    getPixelForTick: function(index, includeOffset) {},

    // Get the pixel (x coordinate for horizontal axis, y coordinate for vertical axis) for a given value
    // @param value : the value to get the pixel for
    // @param index : index into the data array of the value
    // @param datasetIndex : index of the dataset the value comes from
    // @param includeOffset : if true, get the pixel halway between the given tick and the next
    getPixelForValue: function(value, index, datasetIndex, includeOffset) {}

    // Get the value for a given pixel (x coordinate for horizontal axis, y coordinate for vertical axis)
    // @param pixel : pixel value
    getValueForPixel: function(pixel) {}
}

Optionally, the following methods may also be overwritten, but an implementation is already provided by the Chart.Scale base class.

    // Transform the ticks array of the scale instance into strings. The default implementation simply calls this.options.ticks.callback(numericalTick, index, ticks); 
    convertTicksToLabels: function() {},

    // Determine how much the labels will rotate by. The default implementation will only rotate labels if the scale is horizontal. 
    calculateTickRotation: function() {},

    // Fits the scale into the canvas.
    // this.maxWidth and this.maxHeight will tell you the maximum dimensions the scale instance can be. Scales should endeavour to be as efficient as possible with canvas space.
    // this.margins is the amount of space you have on either side of your scale that you may expand in to. This is used already for calculating the best label rotation
    // You must set this.minSize to be the size of your scale. It must be an object containing 2 properties: width and height.
    // You must set this.width to be the width and this.height to be the height of the scale
    fit: function() {},

    // Draws the scale onto the canvas. this.(left|right|top|bottom) will have been populated to tell you the area on the canvas to draw in
    // @param chartArea : an object containing four properties: left, right, top, bottom. This is the rectangle that lines, bars, etc will be drawn in. It may be used, for example, to draw grid lines.
    draw: function(chartArea) {},

The Core.Scale base class also has some utility functions that you may find useful.

{    
    // Returns true if the scale instance is horizontal
    isHorizontal: function() {},

    // Get the correct value from the value from this.chart.data.datasets[x].data[]
    // If dataValue is an object, returns .x or .y depending on the return of isHorizontal()
    // If the value is undefined, returns NaN
    // Otherwise returns the value.
    // Note that in all cases, the returned value is not guaranteed to be a Number
    getRightValue: function(dataValue) {},
}

Writing new chart types

Chart.js 2.0 introduces the concept of controllers for each dataset. Like scales, new controllers can be written as needed.

Chart.controllers.MyType = Chart.DatasetController.extend({

});


// Now we can create a new instance of our chart, using the Chart.js API
new Chart(ctx, {
    // this is the string the constructor was registered at, ie Chart.controllers.MyType
    type: 'MyType',
    data: data,
    options: options
});

Dataset Controller Interface

Dataset controllers must implement the following interface.

{
    // Create elements for each piece of data in the dataset. Store elements in an array on the dataset as dataset.metaData
    addElements: function() {},

    // Create a single element for the data at the given index and reset its state
    addElementAndReset: function(index) {},

    // Draw the representation of the dataset
    // @param ease : if specified, this number represents how far to transition elements. See the implementation of draw() in any of the provided controllers to see how this should be used
    draw: function(ease) {},

    // Remove hover styling from the given element
    removeHoverStyle: function(element) {},

    // Add hover styling to the given element
    setHoverStyle: function(element) {},

    // Update the elements in response to new data
    // @param reset : if true, put the elements into a reset state so they can animate to their final values
    update: function(reset) {},
}

The following methods may optionally be overridden by derived dataset controllers

{
    // Initializes the controller
    initialize: function(chart, datasetIndex) {},

    // Ensures that the dataset represented by this controller is linked to a scale. Overridden to helpers.noop in the polar area and doughnut controllers as these
    // chart types using a single scale
    linkScales: function() {},

    // Called by the main chart controller when an update is triggered. The default implementation handles the number of data points changing and creating elements appropriately. 
    buildOrUpdateElements: function() {}
}

Extending existing chart types

Extending or replacing an existing controller type is easy. Simply replace the constructor for one of the built in types with your own.

The built in controller types are:

  • Chart.controllers.line
  • Chart.controllers.bar
  • Chart.controllers.radar
  • Chart.controllers.doughnut
  • Chart.controllers.polarArea
  • Chart.controllers.bubble

Bar Controller

The bar controller has a special property that you should be aware of. To correctly calculate the width of a bar, the controller must determine the number of datasets that map to bars. To do this, the bar controller attaches a property bar to the dataset during initialization. If you are creating a replacement or updated bar controller, you should do the same. This will ensure that charts with regular bars and your new derived bars will work seamlessly.

Creating Plugins

Starting with v2.1.0, you can create plugins for chart.js. To register your plugin, simply call Chart.pluginService.register and pass your plugin in. Plugins will be called at the following times

  • Start of initialization
  • End of initialization
  • Start of update
  • End of update
  • Start of draw
  • End of draw

Plugins should derive from Chart.PluginBase and implement the following interface

{
    beforeInit: function(chartInstance) { },
    afterInit: function(chartInstance) { },

    beforeUpdate: function(chartInstance) { },
    afterUpdate: function(chartInstance) { },

    // This is called at the start of a render. It is only called once, even if the animation will run for a number of frames. Use beforeDraw or afterDraw 
    // to do something on each animation frame
    beforeRender: function(chartInstance) { },

    // Easing is for animation
    beforeDraw: function(chartInstance, easing) { },
    afterDraw: function(chartInstance, easing) { }

    destroy: function(chartInstance) { }
}

Building Chart.js

Chart.js uses gulp to build the library into a single JavaScript file.

Firstly, we need to ensure development dependencies are installed. With node and npm installed, after cloning the Chart.js repo to a local directory, and navigating to that directory in the command line, we can run the following:

npm install
npm install -g gulp

This will install the local development dependencies for Chart.js, along with a CLI for the JavaScript task runner gulp.

Now, we can run the gulp build task.

gulp build

Notes

Previous versions

Please note - documentation for previous versions are available on the GitHub repo.

Browser support

Chart.js offers support for all browsers where canvas is supported.

Browser support for the canvas element is available in all modern & major mobile browsers (http://caniuse.com/#feat=canvas).

Bugs & issues

Please report these on the GitHub page - at github.com/nnnick/Chart.js. If you could include a link to a simple jsbin or similar to demonstrate the issue, that'd be really helpful.

Contributing

New contributions to the library are welcome, just a couple of guidelines:

  • Tabs for indentation, not spaces please.
  • Please ensure you're changing the individual files in /src, not the concatenated output in the Chart.js file in the root of the repo.
  • Please check that your code will pass jshint code standards, gulp jshint will run this for you.
  • Please keep pull requests concise, and document new functionality in the relevant .md file.
  • Consider whether your changes are useful for all users, or if creating a Chart.js extension would be more appropriate.

License

Chart.js is open source and available under the MIT license.