AdminLTE/plugins/chart.js/docs/search_plus_index.json
2018-04-22 20:08:03 -04:00

1 line
130 KiB
JSON

{"./":{"url":"./","title":"Chart.js","keywords":"","body":"Chart.js Installation You can download the latest version of Chart.js from the GitHub releases or use a Chart.js CDN. Detailed installation instructions can be found on the installation page. Creating a Chart It's easy to get started with Chart.js. All that's required is the script included in your page along with a single node to render the chart. In this example, we create a bar chart for a single dataset and render that in our page. You can see all the ways to use Chart.js in the usage documentation var ctx = document.getElementById(\"myChart\").getContext('2d'); 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], backgroundColor: [ 'rgba(255, 99, 132, 0.2)', 'rgba(54, 162, 235, 0.2)', 'rgba(255, 206, 86, 0.2)', 'rgba(75, 192, 192, 0.2)', 'rgba(153, 102, 255, 0.2)', 'rgba(255, 159, 64, 0.2)' ], borderColor: [ 'rgba(255,99,132,1)', 'rgba(54, 162, 235, 1)', 'rgba(255, 206, 86, 1)', 'rgba(75, 192, 192, 1)', 'rgba(153, 102, 255, 1)', 'rgba(255, 159, 64, 1)' ], borderWidth: 1 }] }, options: { scales: { yAxes: [{ ticks: { beginAtZero:true } }] } } }); Contributing Before submitting an issue or a pull request to the project, please take a moment to look over the contributing guidelines first. For support using Chart.js, please post questions with the chartjs tag on Stack Overflow. License Chart.js is available under the MIT license. "},"getting-started/":{"url":"getting-started/","title":"Getting Started","keywords":"","body":"Getting Started Let's get started using Chart.js! First, we need to have a canvas in our page. Now that we have a canvas we can use, we need to include Chart.js in our page. Now, we can create a chart. We add a script to our page: var ctx = document.getElementById('myChart').getContext('2d'); var chart = new Chart(ctx, { // The type of chart we want to create type: 'line', // The data for our dataset data: { labels: [\"January\", \"February\", \"March\", \"April\", \"May\", \"June\", \"July\"], datasets: [{ label: \"My First dataset\", backgroundColor: 'rgb(255, 99, 132)', borderColor: 'rgb(255, 99, 132)', data: [0, 10, 5, 2, 20, 30, 45], }] }, // Configuration options go here options: {} }); 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. There are many examples of Chart.js that are available in the /samples folder of Chart.js.zip that is attached to every release. "},"getting-started/installation.html":{"url":"getting-started/installation.html","title":"Installation","keywords":"","body":"Installation Chart.js can be installed via npm or bower. It is recommended to get Chart.js this way. npm npm install chart.js --save Bower bower install chart.js --save CDN CDNJS Chart.js built files are available on CDNJS: https://cdnjs.com/libraries/Chart.js jsDelivr Chart.js built files are also available through jsDelivr: https://www.jsdelivr.com/package/npm/chart.js?path=dist Github You can download the latest version of Chart.js on GitHub. If you download or clone the repository, you must build Chart.js to generate the dist files. Chart.js no longer comes with prebuilt release versions, so an alternative option to downloading the repo is strongly advised. Selecting the Correct Build Chart.js provides two different builds for you to choose: Stand-Alone Build, Bundled Build. Stand-Alone Build Files: dist/Chart.js dist/Chart.min.js The stand-alone build includes Chart.js as well as the color parsing library. If this version is used, you are required to include Moment.js before Chart.js for the functionality of the time axis. Bundled Build Files: dist/Chart.bundle.js dist/Chart.bundle.min.js The bundled build includes Moment.js in a single file. You should use this version if you require time axes and want to include a single file. You should not use this build if your application already included Moment.js. Otherwise, Moment.js will be included twice which results in increasing page load time and possible version compatability issues. "},"getting-started/integration.html":{"url":"getting-started/integration.html","title":"Integration","keywords":"","body":"Integration Chart.js can be integrated with plain JavaScript or with different module loaders. The examples below show how to load Chart.js in different systems. ES6 Modules import Chart from 'chart.js'; var myChart = new Chart(ctx, {...}); Script Tag var myChart = new Chart(ctx, {...}); Common JS var Chart = require('chart.js'); var myChart = new Chart(ctx, {...}); Require JS require(['path/to/chartjs/dist/Chart.js'], function(Chart){ var myChart = new Chart(ctx, {...}); }); Important: RequireJS can not load CommonJS module as is, so be sure to require one of the built UMD files instead (i.e. dist/Chart.js, dist/Chart.min.js, etc.). "},"getting-started/usage.html":{"url":"getting-started/usage.html","title":"Usage","keywords":"","body":"Usage Chart.js can be used with ES6 modules, plain JavaScript and module loaders. 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. // Any of the following formats may be used var ctx = document.getElementById(\"myChart\"); var ctx = document.getElementById(\"myChart\").getContext(\"2d\"); var ctx = $(\"#myChart\"); 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. 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], backgroundColor: [ 'rgba(255, 99, 132, 0.2)', 'rgba(54, 162, 235, 0.2)', 'rgba(255, 206, 86, 0.2)', 'rgba(75, 192, 192, 0.2)', 'rgba(153, 102, 255, 0.2)', 'rgba(255, 159, 64, 0.2)' ], borderColor: [ 'rgba(255,99,132,1)', 'rgba(54, 162, 235, 1)', 'rgba(255, 206, 86, 1)', 'rgba(75, 192, 192, 1)', 'rgba(153, 102, 255, 1)', 'rgba(255, 159, 64, 1)' ], borderWidth: 1 }] }, options: { scales: { yAxes: [{ ticks: { beginAtZero:true } }] } } }); "},"general/":{"url":"general/","title":"General","keywords":"","body":"General Configuration These sections describe general configuration options that can apply elsewhere in the documentation. Responsive defines responsive chart options that apply to all charts. Device Pixel Ratio defines the ratio between display pixels and rendered pixels. Interactions defines options that reflect how hovering chart elements works. Options scriptable and indexable options syntax. Colors defines acceptable color values. Font defines various font options. "},"general/responsive.html":{"url":"general/responsive.html","title":"Responsive","keywords":"","body":"Responsive Charts When it comes to change the chart size based on the window size, a major limitation is that the canvas render size (canvas.width and .height) can not be expressed with relative values, contrary to the display size (canvas.style.width and .height). Furthermore, these sizes are independent from each other and thus the canvas render size does not adjust automatically based on the display size, making the rendering inaccurate. The following examples do not work: : invalid values, the canvas doesn't resize (example) : invalid behavior, the canvas is resized but becomes blurry (example) Chart.js provides a few options to enable responsiveness and control the resize behavior of charts by detecting when the canvas display size changes and update the render size accordingly. Configuration Options Name Type Default Description responsive Boolean true Resizes the chart canvas when its container does (important note...). 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. onResize Function null Called when a resize occurs. Gets passed two arguments: the chart instance and the new size. Important Note Detecting when the canvas size changes can not be done directly from the CANVAS element. Chart.js uses its parent container to update the canvas render and display sizes. However, this method requires the container to be relatively positioned and dedicated to the chart canvas only. Responsiveness can then be achieved by setting relative values for the container size (example): The chart can also be programmatically resized by modifying the container size: chart.canvas.parentNode.style.height = '128px'; Printing Resizeable Charts CSS media queries allow changing styles when printing a page. The CSS applied from these media queries may cause charts to need to resize. However, the resize won't happen automatically. To support resizing charts when printing, one needs to hook the onbeforeprint event and manually trigger resizing of each chart. function beforePrintHandler () { for (var id in Chart.instances) { Chart.instances[id].resize() } } "},"general/device-pixel-ratio.html":{"url":"general/device-pixel-ratio.html","title":"Pixel Ratio","keywords":"","body":"Device Pixel Ratio By default the chart's canvas will use a 1:1 pixel ratio, unless the physical display has a higher pixel ratio (e.g. Retina displays). For applications where a chart will be converted to a bitmap, or printed to a higher DPI medium it can be desirable to render the chart at a higher resolution than the default. Setting devicePixelRatio to a value other than 1 will force the canvas size to be scaled by that amount, relative to the container size. There should be no visible difference on screen; the difference will only be visible when the image is zoomed or printed. Configuration Options Name Type Default Description devicePixelRatio Number window.devicePixelRatio Override the window's default devicePixelRatio. "},"general/interactions/":{"url":"general/interactions/","title":"Interactions","keywords":"","body":"Interactions The hover configuration is passed into the options.hover namespace. The global hover configuration is at Chart.defaults.global.hover. To configure which events trigger chart interactions, see events. Name Type Default Description mode String 'nearest' Sets which elements appear in the tooltip. See Interaction Modes for details. intersect Boolean true if true, the hover mode only applies when the mouse position intersects an item on the chart. axis String 'x' Can be set to 'x', 'y', or 'xy' to define which directions are used in calculating distances. Defaults to 'x' for index mode and 'xy' in dataset and nearest modes. animationDuration Number 400 Duration in milliseconds it takes to animate hover style changes. "},"general/interactions/events.html":{"url":"general/interactions/events.html","title":"Events","keywords":"","body":"Events The following properties define how the chart interacts with events. Name Type Default Description events String[] [\"mousemove\", \"mouseout\", \"click\", \"touchstart\", \"touchmove\", \"touchend\"] The events option defines the browser events that the chart should listen to for tooltips and hovering. more... onHover Function null Called when any of the events fire. Called in the context of the chart and passed the event and an array of active elements (bars, points, etc). onClick Function null Called if the event is of type 'mouseup' or 'click'. Called in the context of the chart and passed the event and an array of active elements Event Option For example, to have the chart only respond to click events, you could do var chart = new Chart(ctx, { type: 'line', data: data, options: { // This chart will not respond to mousemove, etc events: ['click'] } }); "},"general/interactions/modes.html":{"url":"general/interactions/modes.html","title":"Modes","keywords":"","body":"Interaction Modes When configuring interaction with the graph via hover or tooltips, a number of different modes are available. The modes are detailed below and how they behave in conjunction with the intersect setting. point Finds all of the items that intersect the point. var chart = new Chart(ctx, { type: 'line', data: data, options: { tooltips: { mode: 'point' } } }) nearest Gets the item that is nearest to the point. The nearest item is determined based on the distance to the center of the chart item (point, bar). If 2 or more items are at the same distance, the one with the smallest area is used. If intersect is true, this is only triggered when the mouse position intersects an item in the graph. This is very useful for combo charts where points are hidden behind bars. var chart = new Chart(ctx, { type: 'line', data: data, options: { tooltips: { mode: 'nearest' } } }) single (deprecated) Finds the first item that intersects the point and returns it. Behaves like 'nearest' mode with intersect = true. label (deprecated) See 'index' mode index Finds item at the same index. If the intersect setting is true, the first intersecting item is used to determine the index in the data. If intersect false the nearest item, in the x direction, is used to determine the index. var chart = new Chart(ctx, { type: 'line', data: data, options: { tooltips: { mode: 'index' } } }) To use index mode in a chart like the horizontal bar chart, where we search along the y direction, you can use the axis setting introduced in v2.7.0. By setting this value to 'y' on the y direction is used. var chart = new Chart(ctx, { type: 'horizontalBar', data: data, options: { tooltips: { mode: 'index', axis: 'y' } } }) x-axis (deprecated) Behaves like 'index' mode with intersect = false. dataset Finds items in the same dataset. If the intersect setting is true, the first intersecting item is used to determine the index in the data. If intersect false the nearest item is used to determine the index. var chart = new Chart(ctx, { type: 'line', data: data, options: { tooltips: { mode: 'dataset' } } }) x Returns all items that would intersect based on the X coordinate of the position only. Would be useful for a vertical cursor implementation. Note that this only applies to cartesian charts var chart = new Chart(ctx, { type: 'line', data: data, options: { tooltips: { mode: 'x' } } }) y Returns all items that would intersect based on the Y coordinate of the position. This would be useful for a horizontal cursor implementation. Note that this only applies to cartesian charts. var chart = new Chart(ctx, { type: 'line', data: data, options: { tooltips: { mode: 'y' } } }) "},"general/options.html":{"url":"general/options.html","title":"Options","keywords":"","body":"Options Scriptable Options Scriptable options also accept a function which is called for each data and that takes the unique argument context representing contextual information (see option context). Example: color: function(context) { var index = context.dataIndex; var value = context.dataset.data[index]; return value Note: scriptable options are only supported by a few bubble chart options. Indexable Options Indexable options also accept an array in which each item corresponds to the element at the same index. Note that this method requires to provide as many items as data, so, in most cases, using a function is more appropriated if supported. Example: color: [ 'red', // color for data at index 0 'blue', // color for data at index 1 'green', // color for data at index 2 'black', // color for data at index 3 //... ] Option Context The option context is used to give contextual information when resolving options and currently only applies to scriptable options. The context object contains the following properties: chart: the associated chart dataIndex: index of the current data dataset: dataset at index datasetIndex datasetIndex: index of the current dataset Important: since the context can represent different types of entities (dataset, data, etc.), some properties may be undefined so be sure to test any context property before using it. "},"general/colors.html":{"url":"general/colors.html","title":"Colors","keywords":"","body":"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. If a color is needed, but not specified, Chart.js will use the global default color. This color is stored at Chart.defaults.global.defaultColor. It is initially set to 'rgba(0, 0, 0, 0.1)' 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. Patterns and Gradients An alternative option is to pass a CanvasPattern or CanvasGradient object instead of a string colour. 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 }] } }) } Using pattern fills for data graphics can help viewers with vision deficiencies (e.g. color-blindness or partial sight) to more easily understand your data. Using the Patternomaly library you can generate patterns to fill datasets. var chartData = { datasets: [{ data: [45, 25, 20, 10], backgroundColor: [ pattern.draw('square', '#ff6384'), pattern.draw('circle', '#36a2eb'), pattern.draw('diamond', '#cc65fe'), pattern.draw('triangle', '#ffce56'), ] }], labels: ['Red', 'Blue', 'Purple', 'Yellow'] }; "},"general/fonts.html":{"url":"general/fonts.html","title":"Fonts","keywords":"","body":"Fonts There are 4 special global settings that can change all of the fonts on the chart. These options are in Chart.defaults.global. The global font settings only apply when more specific options are not included in the config. For example, in this chart the text will all be red except for the labels in the legend. Chart.defaults.global.defaultFontColor = 'red'; let chart = new Chart(ctx, { type: 'line', data: data, options: { legend: { labels: { // This more specific font property overrides the global property fontColor: 'black' } } } }); Name Type Default Description 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. Non-Existant Fonts If a font is specified for a chart that does exist on the system, the browser will not apply the font when it is set. If you notice odd fonts appearing in your charts, check that the font you are applying exists on your system. See issue 3318 for more details. "},"configuration/":{"url":"configuration/","title":"Configuration","keywords":"","body":"Configuration The configuration is used to change how the chart behaves. There are properties to control styling, fonts, the legend, etc. Global 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 the options object passed to the chart with the global configuration using chart type defaults and scales defaults appropriately. This way you can be as specific as you would like in your individual chart configuration, while still changing the defaults for all chart types where applicable. The global general options are defined in Chart.defaults.global. The defaults for each chart type are discussed in the documentation for that chart type. The following example would set the hover mode to 'nearest' for all charts where this was not overridden by the chart type defaults or the options passed to the constructor on creation. Chart.defaults.global.hover.mode = 'nearest'; // Hover mode is set to nearest because it was not overridden here var chartHoverModeNearest = new Chart(ctx, { type: 'line', data: data, }); // This chart would have the hover mode that was passed in var chartDifferentHoverMode = new Chart(ctx, { type: 'line', data: data, options: { hover: { // Overrides the global setting mode: 'index' } } }) "},"configuration/animations.html":{"url":"configuration/animations.html","title":"Animations","keywords":"","body":"Animations Chart.js animates charts out of the box. A number of options are provided to configure how the animation looks and how long it takes Animation Configuration The following animation options are available. The global options for 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. more... onProgress Function null Callback called on each step of an animation. more... onComplete Function null Callback called at the end of an animation. more... Easing Available options are: 'linear' 'easeInQuad' 'easeOutQuad' 'easeInOutQuad' 'easeInCubic' 'easeOutCubic' 'easeInOutCubic' 'easeInQuart' 'easeOutQuart' 'easeInOutQuart' 'easeInQuint' 'easeOutQuint' 'easeInOutQuint' 'easeInSine' 'easeOutSine' 'easeInOutSine' 'easeInExpo' 'easeOutExpo' 'easeInOutExpo' 'easeInCirc' 'easeOutCirc' 'easeInOutCirc' 'easeInElastic' 'easeOutElastic' 'easeInOutElastic' 'easeInBack' 'easeOutBack' 'easeInOutBack' 'easeInBounce' 'easeOutBounce' 'easeInOutBounce' See Robert Penner's easing equations. Animation Callbacks The onProgress and onComplete callbacks are useful for synchronizing an external draw to the chart animation. The callback is passed a Chart.Animation instance: { // Chart object chart: Chart, // Current Animation frame number currentStep: Number, // Number of animation frames numSteps: Number, // Animation easing to use easing: String, // Function that renders the chart render: Function, // User callback onAnimationProgress: Function, // User callback onAnimationComplete: Function } The following example fills a progress bar during the chart animation. var chart = new Chart(ctx, { type: 'line', data: data, options: { animation: { onProgress: function(animation) { progress.value = animation.animationObject.currentStep / animation.animationObject.numSteps; } } } }); Another example usage of these callbacks can be found on Github: this sample displays a progress bar showing how far along the animation is. "},"configuration/layout.html":{"url":"configuration/layout.html","title":"Layout","keywords":"","body":"Layout Configuration The layout configuration is passed into the options.layout namespace. The global options for the chart layout is defined in Chart.defaults.global.layout. Name Type Default Description padding Number or Object 0 The padding to add inside the chart. more... Padding If this value is a number, it is applied to all sides of the chart (left, top, right, bottom). If this value is an object, the left property defines the left padding. Similarly the right, top, and bottom properties can also be specified. Lets say you wanted to add 50px of padding to the left side of the chart canvas, you would do: let chart = new Chart(ctx, { type: 'line', data: data, options: { layout: { padding: { left: 50, right: 0, top: 0, bottom: 0 } } } }); "},"configuration/legend.html":{"url":"configuration/legend.html","title":"Legend","keywords":"","body":"Legend Configuration The chart legend displays data about the datasets that area appearing on the chart. Configuration options The legend configuration is passed into the options.legend namespace. The global options for the chart legend is defined in Chart.defaults.global.legend. Name Type Default Description display Boolean true is the legend shown position String 'top' Position of the legend. more... fullWidth Boolean true Marks that this box should take the full width of the canvas (pushing down other boxes). This is unlikely to need to be changed in day-to-day use. onClick Function A callback that is called when a click event is registered on a label item onHover Function A callback that is called when a 'mousemove' event is registered on top of a label item reverse Boolean false Legend will show datasets in reverse order. labels Object See the Legend Label Configuration section below. Position Position of the legend. Options are: 'top' 'left' 'bottom' 'right' Legend Label Configuration The legend label configuration is nested below the legend configuration using the labels key. Name Type Default Description boxWidth Number 40 width of coloured box fontSize Number 12 font size of text fontStyle String 'normal' font style of text fontColor Color '#666' Color of text fontFamily String \"'Helvetica Neue', 'Helvetica', 'Arial', sans-serif\" Font family of legend text. padding Number 10 Padding between rows of colored boxes. generateLabels Function Generates legend items for each thing in the legend. Default implementation returns the text + styling for the color box. See Legend Item for details. filter Function null Filters legend items out of the legend. Receives 2 parameters, a Legend Item and the chart data. usePointStyle Boolean false Label style will match corresponding point style (size is based on fontSize, boxWidth is not used in this case). Legend Item Interface Items passed to the legend onClick function are the ones returned from labels.generateLabels. These items must implement the following interface. { // Label that will be displayed text: String, // Fill style of the legend box fillStyle: Color, // If true, this item represents a hidden dataset. Label will be rendered with a strike-through effect hidden: Boolean, // For box border. See https://developer.mozilla.org/en/docs/Web/API/CanvasRenderingContext2D/lineCap lineCap: String, // For box border. See https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/setLineDash lineDash: Array[Number], // For box border. See https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/lineDashOffset lineDashOffset: Number, // For box border. See https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/lineJoin lineJoin: String, // Width of box border lineWidth: Number, // Stroke style of the legend box strokeStyle: Color // Point style of the legend box (only used if usePointStyle is true) pointStyle: String } Example The following example will create a chart with the legend enabled and turn all of the text red in color. var chart = new Chart(ctx, { type: 'bar', data: data, options: { legend: { display: true, labels: { fontColor: 'rgb(255, 99, 132)' } } } }); Custom On Click Actions It can be common to want to trigger different behaviour when clicking an item in the legend. This can be easily achieved using a callback in the config object. The default legend click handler is: function(e, legendItem) { var index = legendItem.datasetIndex; var ci = this.chart; var meta = ci.getDatasetMeta(index); // See controller.isDatasetVisible comment meta.hidden = meta.hidden === null? !ci.data.datasets[index].hidden : null; // We hid a dataset ... rerender the chart ci.update(); } Lets say we wanted instead to link the display of the first two datasets. We could change the click handler accordingly. var defaultLegendClickHandler = Chart.defaults.global.legend.onClick; var newLegendClickHandler = function (e, legendItem) { var index = legendItem.datasetIndex; if (index > 1) { // Do the original logic defaultLegendClickHandler(e, legendItem); } else { let ci = this.chart; [ci.getDatasetMeta(0), ci.getDatasetMeta(1)].forEach(function(meta) { meta.hidden = meta.hidden === null? !ci.data.datasets[index].hidden : null; }); ci.update(); } }; var chart = new Chart(ctx, { type: 'line', data: data, options: { legend: { } } }); Now when you click the legend in this chart, the visibility of the first two datasets will be linked together. HTML Legends Sometimes you need a very complex legend. In these cases, it makes sense to generate an HTML legend. Charts provide a generateLegend() method on their prototype that returns an HTML string for the legend. To configure how this legend is generated, you can change the legendCallback config property. var chart = new Chart(ctx, { type: 'line', data: data, options: { legendCallback: function(chart) { // Return the HTML string here. } } }); Note that legendCallback is not called automatically and you must call generateLegend() yourself in code when creating a legend using this method. "},"configuration/title.html":{"url":"configuration/title.html","title":"Title","keywords":"","body":"Title The chart title defines text to draw at the top of the chart. Title Configuration The title configuration is passed into the options.title namespace. The global options for the chart title is defined in Chart.defaults.global.title. Name Type Default Description display Boolean false is the title shown position String 'top' Position of title. more... fontSize Number 12 Font size fontFamily String \"'Helvetica Neue', 'Helvetica', 'Arial', sans-serif\" Font family for the title text. fontColor Color '#666' Font color fontStyle String 'bold' Font style padding Number 10 Number of pixels to add above and below the title text. lineHeight Number/String 1.2 Height of an individual line of text (see MDN) text String/String[] '' Title text to display. If specified as an array, text is rendered on multiple lines. Position Possible title position values are: 'top' 'left' 'bottom' 'right' Example Usage The example below would enable a title of 'Custom Chart Title' on the chart that is created. var chart = new Chart(ctx, { type: 'line', data: data, options: { title: { display: true, text: 'Custom Chart Title' } } }) "},"configuration/tooltip.html":{"url":"configuration/tooltip.html","title":"Tooltip","keywords":"","body":"Tooltips Tooltip Configuration The tooltip configuration is passed into the options.tooltips namespace. The global options for the chart tooltips is defined in Chart.defaults.global.tooltips. Name Type Default Description enabled Boolean true Are on-canvas tooltips enabled custom Function null See custom tooltip section. mode String 'nearest' Sets which elements appear in the tooltip. more.... intersect Boolean true if true, the tooltip mode applies only when the mouse position intersects with an element. If false, the mode will be applied at all times. position String 'average' The mode for positioning the tooltip. more... callbacks Object See the callbacks section itemSort Function Sort tooltip items. more... filter Function Filter tooltip items. more... backgroundColor Color 'rgba(0,0,0,0.8)' Background color of the tooltip. titleFontFamily String \"'Helvetica Neue', 'Helvetica', 'Arial', sans-serif\" title font titleFontSize Number 12 Title font size titleFontStyle String 'bold' Title font style titleFontColor Color '#fff' Title font color titleSpacing Number 2 Spacing to add to top and bottom of each title line. titleMarginBottom Number 6 Margin to add on bottom of title section. bodyFontFamily String \"'Helvetica Neue', 'Helvetica', 'Arial', sans-serif\" body line font bodyFontSize Number 12 Body font size bodyFontStyle String 'normal' Body font style bodyFontColor Color '#fff' Body font color bodySpacing Number 2 Spacing to add to top and bottom of each tooltip item. footerFontFamily String \"'Helvetica Neue', 'Helvetica', 'Arial', sans-serif\" footer font footerFontSize Number 12 Footer font size footerFontStyle String 'bold' Footer font style footerFontColor Color '#fff' Footer font color footerSpacing Number 2 Spacing to add to top and bottom of each footer line. 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. caretPadding Number 2 Extra distance to move the end of the tooltip arrow away from the tooltip point. 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 displayColors Boolean true if true, color boxes are shown in the tooltip borderColor Color 'rgba(0,0,0,0)' Color of the border borderWidth Number 0 Size of the border Position Modes Possible modes are: 'average' 'nearest' 'average' mode will place the tooltip at the average position of the items displayed in the tooltip. 'nearest' will place the tooltip at the position of the element closest to the event position. New modes can be defined by adding functions to the Chart.Tooltip.positioners map. Example: /** * Custom positioner * @function Chart.Tooltip.positioners.custom * @param elements {Chart.Element[]} the tooltip elements * @param eventPosition {Point} the position of the event in canvas coordinates * @returns {Point} the tooltip position */ Chart.Tooltip.positioners.custom = function(elements, eventPosition) { /** @type {Chart.Tooltip} */ var tooltip = this; /* ... */ return { x: 0, y: 0 }; } Sort Callback Allows sorting of tooltip items. Must implement at minimum a function that can be passed to Array.prototype.sort. This function can also accept a third parameter that is the data object passed to the chart. Filter Callback Allows filtering of tooltip items. Must implement at minimum a function that can be passed to Array.prototype.filter. This function can also accept a second parameter that is the data object passed to the chart. Tooltip Callbacks The tooltip label configuration is nested below the tooltip configuration using the callbacks key. The tooltip has the following callbacks for providing text. For all functions, 'this' will be the tooltip object created from the Chart.Tooltip constructor. All functions are called with the same arguments: a tooltip item and the data object passed to the chart. All functions must return either a string or an array of strings. Arrays of strings are treated as multiple lines of text. Name Arguments Description beforeTitle Array[tooltipItem], data Returns the text to render before the title. title Array[tooltipItem], data Returns text to render as the title of the tooltip. afterTitle Array[tooltipItem], data Returns text to render after the title. beforeBody Array[tooltipItem], data Returns text to render before the body section. beforeLabel tooltipItem, data Returns text to render before an individual label. This will be called for each item in the tooltip. label tooltipItem, data Returns text to render for an individual item in the tooltip. labelColor tooltipItem, chart Returns the colors to render for the tooltip item. more... labelTextColor tooltipItem, chart Returns the colors for the text of the label for the tooltip item. afterLabel tooltipItem, data Returns text to render after an individual label. afterBody Array[tooltipItem], data Returns text to render after the body section beforeFooter Array[tooltipItem], data Returns text to render before the footer section. footer Array[tooltipItem], data Returns text to render as the footer of the tooltip. afterFooter Array[tooltipItem], data Text to render after the footer section Label Callback The label callback can change the text that displays for a given data point. A common example to round data values; the following example rounds the data to two decimal places. var chart = new Chart(ctx, { type: 'line', data: data, options: { tooltips: { callbacks: { label: function(tooltipItem, data) { var label = data.datasets[tooltipItem.datasetIndex].label || ''; if (label) { label += ': '; } label += Math.round(tooltipItem.yLabel * 100) / 100; return label; } } } } }); Label Color Callback For example, to return a red box for each item in the tooltip you could do: var chart = new Chart(ctx, { type: 'line', data: data, options: { tooltips: { callbacks: { labelColor: function(tooltipItem, chart) { return { borderColor: 'rgb(255, 0, 0)', backgroundColor: 'rgb(255, 0, 0)' } }, labelTextColor:function(tooltipItem, chart){ return '#543453'; } } } } }); Tooltip Item Interface The tooltip items passed to the tooltip callbacks implement the following interface. { // X Value of the tooltip as a string xLabel: String, // Y value of the tooltip as a string yLabel: String, // Index of the dataset the item comes from datasetIndex: Number, // Index of this data item in the dataset index: Number, // X position of matching point x: Number, // Y position of matching point y: Number, } External (Custom) Tooltips Custom tooltips allow you to hook into the tooltip rendering process so that you can render the tooltip in your own custom way. Generally this is used to create an HTML tooltip instead of an oncanvas one. You can enable custom tooltips in the global or chart configuration like so: var myPieChart = new Chart(ctx, { type: 'pie', data: data, options: { tooltips: { // Disable the on-canvas tooltip enabled: false, custom: function(tooltipModel) { // Tooltip Element var tooltipEl = document.getElementById('chartjs-tooltip'); // Create element on first render if (!tooltipEl) { tooltipEl = document.createElement('div'); tooltipEl.id = 'chartjs-tooltip'; tooltipEl.innerHTML = \"\"; document.body.appendChild(tooltipEl); } // Hide if no tooltip if (tooltipModel.opacity === 0) { tooltipEl.style.opacity = 0; return; } // Set caret Position tooltipEl.classList.remove('above', 'below', 'no-transform'); if (tooltipModel.yAlign) { tooltipEl.classList.add(tooltipModel.yAlign); } else { tooltipEl.classList.add('no-transform'); } function getBody(bodyItem) { return bodyItem.lines; } // Set Text if (tooltipModel.body) { var titleLines = tooltipModel.title || []; var bodyLines = tooltipModel.body.map(getBody); var innerHtml = ''; titleLines.forEach(function(title) { innerHtml += '' + title + ''; }); innerHtml += ''; bodyLines.forEach(function(body, i) { var colors = tooltipModel.labelColors[i]; var style = 'background:' + colors.backgroundColor; style += '; border-color:' + colors.borderColor; style += '; border-width: 2px'; var span = ''; innerHtml += '' + span + body + ''; }); innerHtml += ''; var tableRoot = tooltipEl.querySelector('table'); tableRoot.innerHTML = innerHtml; } // `this` will be the overall tooltip var position = this._chart.canvas.getBoundingClientRect(); // Display, position, and set styles for font tooltipEl.style.opacity = 1; tooltipEl.style.position = 'absolute'; tooltipEl.style.left = position.left + tooltipModel.caretX + 'px'; tooltipEl.style.top = position.top + tooltipModel.caretY + 'px'; tooltipEl.style.fontFamily = tooltipModel._bodyFontFamily; tooltipEl.style.fontSize = tooltipModel.bodyFontSize + 'px'; tooltipEl.style.fontStyle = tooltipModel._bodyFontStyle; tooltipEl.style.padding = tooltipModel.yPadding + 'px ' + tooltipModel.xPadding + 'px'; } } } }); See samples for examples on how to get started with custom tooltips. Tooltip Model The tooltip model contains parameters that can be used to render the tooltip. { // The items that we are rendering in the tooltip. See Tooltip Item Interface section dataPoints: TooltipItem[], // Positioning xPadding: Number, yPadding: Number, xAlign: String, yAlign: String, // X and Y properties are the top left of the tooltip x: Number, y: Number, width: Number, height: Number, // Where the tooltip points to caretX: Number, caretY: Number, // Body // The body lines that need to be rendered // Each object contains 3 parameters // before: String[] // lines of text before the line with the color square // lines: String[], // lines of text to render as the main item with color square // after: String[], // lines of text to render after the main lines body: Object[], // lines of text that appear after the title but before the body beforeBody: String[], // line of text that appear after the body and before the footer afterBody: String[], bodyFontColor: Color, _bodyFontFamily: String, _bodyFontStyle: String, _bodyAlign: String, bodyFontSize: Number, bodySpacing: Number, // Title // lines of text that form the title title: String[], titleFontColor: Color, _titleFontFamily: String, _titleFontStyle: String, titleFontSize: Number, _titleAlign: String, titleSpacing: Number, titleMarginBottom: Number, // Footer // lines of text that form the footer footer: String[], footerFontColor: Color, _footerFontFamily: String, _footerFontStyle: String, footerFontSize: Number, _footerAlign: String, footerSpacing: Number, footerMarginTop: Number, // Appearance caretSize: Number, cornerRadius: Number, backgroundColor: Color, // colors to render for each item in body[]. This is the color of the squares in the tooltip labelColors: Color[], // 0 opacity is a hidden tooltip opacity: Number, legendColorBackground: Color, displayColors: Boolean, } "},"configuration/elements.html":{"url":"configuration/elements.html","title":"Elements","keywords":"","body":"Elements While chart types provide settings to configure the styling of each dataset, you sometimes want to style all datasets the same way. A common example would be to stroke all of the bars in a bar chart with the same colour but change the fill per dataset. Options can be configured for four different types of elements: arc, lines, points, and rectangles. When set, these options apply to all objects of that type unless specifically overridden by the configuration attached to a dataset. Global Configuration The element options can be specified per chart or globally. The global options for elements are defined in Chart.defaults.global.elements. For example, to set the border width of all bar charts globally you would do: Chart.defaults.global.elements.rectangle.borderWidth = 2; Point Configuration Point elements are used to represent the points in a line chart or a bubble chart. Global point options: Chart.defaults.global.elements.point Name Type Default Description radius Number 3 Point radius. pointStyle String circle Point style. backgroundColor Color 'rgba(0,0,0,0.1)' Point fill color. borderWidth Number 1 Point stroke width. borderColor Color 'rgba(0,0,0,0.1)' Point stroke color. hitRadius Number 1 Extra radius added to point radius for hit detection. hoverRadius Number 4 Point radius when hovered. hoverBorderWidth Number 1 Stroke width when hovered. Point Styles The following values are supported: 'circle' 'cross' 'crossRot' 'dash' 'line' 'rect' 'rectRounded' 'rectRot' 'star' 'triangle' If the value is an image, that image is drawn on the canvas using drawImage. Line Configuration Line elements are used to represent the line in a line chart. Global line options: Chart.defaults.global.elements.line Name Type Default Description tension Number 0.4 Bézier curve tension (0 for no Bézier curves). backgroundColor Color 'rgba(0,0,0,0.1)' Line fill color. borderWidth Number 3 Line stroke width. borderColor Color 'rgba(0,0,0,0.1)' Line stroke color. borderCapStyle String 'butt' Line cap style (see MDN). borderDash Array [] Line dash (see MDN). borderDashOffset Number 0 Line dash offset (see MDN). borderJoinStyle String 'miter Line join style (see MDN). capBezierPoints Boolean true true to keep Bézier control inside the chart, false for no restriction. fill Boolean/String true Fill location: 'zero', 'top', 'bottom', true (eq. 'zero') or false (no fill). stepped Boolean false true to show the line as a stepped line (tension will be ignored). Rectangle Configuration Rectangle elements are used to represent the bars in a bar chart. Global rectangle options: Chart.defaults.global.elements.rectangle Name Type Default Description backgroundColor Color 'rgba(0,0,0,0.1)' Bar fill color. borderWidth Number 0 Bar stroke width. borderColor Color 'rgba(0,0,0,0.1)' Bar stroke color. borderSkipped String 'bottom' Skipped (excluded) border: 'bottom', 'left', 'top' or 'right'. Arc Configuration Arcs are used in the polar area, doughnut and pie charts. Global arc options: Chart.defaults.global.elements.arc. Name Type Default Description backgroundColor Color 'rgba(0,0,0,0.1)' Arc fill color. borderColor Color '#fff' Arc stroke color. borderWidth Number 2 Arc stroke width. "},"charts/":{"url":"charts/","title":"Charts","keywords":"","body":"Charts Chart.js comes with built-in chart types: line bar radar polar area doughnut and pie bubble Area charts can be built from a line or radar chart using the dataset fill option. To create a new chart type, see the developer notes "},"charts/line.html":{"url":"charts/line.html","title":"Line","keywords":"","body":"Line A line chart is a way of plotting data points on a line. Often, it is used to show trend data, or the comparison of two data sets. new Chart(document.getElementById(\"chartjs-0\"),{\"type\":\"line\",\"data\":{\"labels\":[\"January\",\"February\",\"March\",\"April\",\"May\",\"June\",\"July\"],\"datasets\":[{\"label\":\"My First Dataset\",\"data\":[65,59,80,81,56,55,40],\"fill\":false,\"borderColor\":\"rgb(75, 192, 192)\",\"lineTension\":0.1}]},\"options\":{}}); Example Usage var myLineChart = new Chart(ctx, { type: 'line', data: data, options: options }); Dataset Properties The line chart allows a number of properties to be specified for each dataset. These are used to set display properties for a specific dataset. For example, the colour of a line is generally set this way. 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. Name Type Description 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. If not specified, this defaults to the ID of the first found x axis yAxisID String The ID of the y axis to plot this dataset on. If not specified, this defaults to the ID of the first found y axis. backgroundColor Color The fill color under the line. See Colors borderColor Color The color of the line. See Colors borderWidth Number The width of the line in pixels. borderDash Number[] Length and spacing of dashes. See MDN borderDashOffset Number Offset for line dashes. See MDN borderCapStyle String Cap style of the line. See MDN borderJoinStyle String Line joint style. See MDN cubicInterpolationMode String Algorithm used to interpolate a smooth curve from the discrete data points. more... fill Boolean/String How to fill the area under the line. See area charts lineTension Number Bezier curve tension of the line. Set to 0 to draw straightlines. This option is ignored if monotone cubic interpolation is used. pointBackgroundColor Color/Color[] The fill color for points. pointBorderColor Color/Color[] The border color for points. pointBorderWidth Number/Number[] The width of the point border in pixels. pointRadius Number/Number[] The radius of the point shape. If set to 0, the point is not rendered. pointStyle String/String[]/Image/Image[] Style of the point. more... pointHitRadius Number/Number[] The pixel size of the non-displayed point that reacts to mouse events. pointHoverBackgroundColor Color/Color[] Point background color when hovered. pointHoverBorderColor Color/Color[] Point border color when hovered. pointHoverBorderWidth Number/Number[] Border width of point when hovered. pointHoverRadius Number/Number[] The radius of the point when hovered. showLine Boolean If false, the line is not drawn for this dataset. spanGaps Boolean If true, lines will be drawn between points with no or null data. If false, points with NaN data will create a break in the line steppedLine Boolean/String If the line is shown as a stepped line. more... cubicInterpolationMode The following interpolation modes are supported: 'default' 'monotone'. The 'default' algorithm uses a custom weighted cubic interpolation, which produces pleasant curves for all types of datasets. The 'monotone' algorithm is more suited to y = f(x) datasets : it preserves monotonicity (or piecewise monotonicity) of the dataset being interpolated, and ensures local extremums (if any) stay at input data points. If left untouched (undefined), the global options.elements.line.cubicInterpolationMode property is used. Stepped Line The following values are supported for steppedLine: false: No Step Interpolation (default) true: Step-before Interpolation (eq. 'before') 'before': Step-before Interpolation 'after': Step-after Interpolation If the steppedLine value is set to anything other than false, lineTension will be ignored. Configuration Options The line chart defines the following configuration options. These options are merged with the global chart configuration options, Chart.defaults.global, to form the options passed to the chart. Name Type Default Description showLines Boolean true If false, the lines between points are not drawn. spanGaps Boolean false If false, NaN data causes a break in the line. Default Options It is common to want to apply a configuration setting to all created line charts. The global line chart settings are stored in Chart.defaults.line. Changing the global options only affects charts created after the change. Existing charts are not changed. For example, to configure all line charts with spanGaps = true you would do: Chart.defaults.line.spanGaps = true; Data Structure The data property of a dataset for a line chart can be passed in two formats. Number[] data: [20, 10] When the data array is an array of numbers, the x axis is generally a category. The points are placed onto the axis using their position in the array. When a line chart is created with a category axis, the labels property of the data object must be specified. Point[] data: [{ x: 10, y: 20 }, { x: 15, y: 10 }] This alternate is used for sparse datasets, such as those in scatter charts. Each data point is specified using an object containing x and y properties. Stacked Area Chart Line charts can be configured into stacked area charts by changing the settings on the y axis to enable stacking. Stacked area charts can be used to show how one data trend is made up of a number of smaller pieces. var stackedLine = new Chart(ctx, { type: 'line', data: data, options: { scales: { yAxes: [{ stacked: true }] } } }); High Performance Line Charts When charting a lot of data, the chart render time may start to get quite large. In that case, the following strategies can be used to improve performance. Data Decimation Decimating your data will achieve the best results. When there is a lot of data to display on the graph, it doesn't make sense to show tens of thousands of data points on a graph that is only a few hundred pixels wide. There are many approaches to data decimation and selection of an algorithm will depend on your data and the results you want to achieve. For instance, min/max decimation will preserve peaks in your data but could require up to 4 points for each pixel. This type of decimation would work well for a very noisy signal where you need to see data peaks. Disable Bezier Curves If you are drawing lines on your chart, disabling bezier curves will improve render times since drawing a straight line is more performant than a bezier curve. To disable bezier curves for an entire chart: new Chart(ctx, { type: 'line', data: data, options: { elements: { line: { tension: 0, // disables bezier curves } } } }); Disable Line Drawing If you have a lot of data points, it can be more performant to disable rendering of the line for a dataset and only draw points. Doing this means that there is less to draw on the canvas which will improve render performance. To disable lines: new Chart(ctx, { type: 'line', data: { datasets: [{ showLine: false, // disable for a single dataset }] }, options: { showLines: false, // disable for all datasets } }); Disable Animations If your charts have long render times, it is a good idea to disable animations. Doing so will mean that the chart needs to only be rendered once during an update instead of multiple times. This will have the effect of reducing CPU usage and improving general page performance. To disable animations new Chart(ctx, { type: 'line', data: data, options: { animation: { duration: 0, // general animation time }, hover: { animationDuration: 0, // duration of animations when hovering an item }, responsiveAnimationDuration: 0, // animation duration after a resize } }); "},"charts/bar.html":{"url":"charts/bar.html","title":"Bar","keywords":"","body":"Bar A bar chart provides a way of showing data values represented as vertical bars. It is sometimes used to show trend data, and the comparison of multiple data sets side by side. new Chart(document.getElementById(\"chartjs-1\"),{\"type\":\"bar\",\"data\":{\"labels\":[\"January\",\"February\",\"March\",\"April\",\"May\",\"June\",\"July\"],\"datasets\":[{\"label\":\"My First Dataset\",\"data\":[65,59,80,81,56,55,40],\"fill\":false,\"backgroundColor\":[\"rgba(255, 99, 132, 0.2)\",\"rgba(255, 159, 64, 0.2)\",\"rgba(255, 205, 86, 0.2)\",\"rgba(75, 192, 192, 0.2)\",\"rgba(54, 162, 235, 0.2)\",\"rgba(153, 102, 255, 0.2)\",\"rgba(201, 203, 207, 0.2)\"],\"borderColor\":[\"rgb(255, 99, 132)\",\"rgb(255, 159, 64)\",\"rgb(255, 205, 86)\",\"rgb(75, 192, 192)\",\"rgb(54, 162, 235)\",\"rgb(153, 102, 255)\",\"rgb(201, 203, 207)\"],\"borderWidth\":1}]},\"options\":{\"scales\":{\"yAxes\":[{\"ticks\":{\"beginAtZero\":true}}]}}}); Example Usage var myBarChart = new Chart(ctx, { type: 'bar', data: data, options: options }); Dataset Properties The bar chart allows a number of properties to be specified for each dataset. These are used to set display properties for a specific dataset. For example, the colour of the bars is generally set this way. 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. Name Type Description 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. If not specified, this defaults to the ID of the first found x axis yAxisID String The ID of the y axis to plot this dataset on. If not specified, this defaults to the ID of the first found y axis. backgroundColor Color/Color[] The fill color of the bar. See Colors borderColor Color/Color[] The color of the bar border. See Colors borderWidth Number/Number[] The stroke width of the bar in pixels. borderSkipped String Which edge to skip drawing the border for. more... hoverBackgroundColor Color/Color[] The fill colour of the bars when hovered. hoverBorderColor Color/Color[] The stroke colour of the bars when hovered. hoverBorderWidth Number/Number[] The stroke width of the bars when hovered. borderSkipped This setting is used to avoid drawing the bar stroke at the base of the fill. In general, this does not need to be changed except when creating chart types that derive from a bar chart. Options are: 'bottom' 'left' 'top' 'right' Configuration Options The bar chart defines the following configuration options. These options are merged with the global chart configuration options, Chart.defaults.global, to form the options passed to the chart. Name Type Default Description barPercentage Number 0.9 Percent (0-1) of the available width each bar should be within the category width. 1.0 will take the whole category width and put the bars right next to each other. more... categoryPercentage Number 0.8 Percent (0-1) of the available width each category should be within the sample width. more... barThickness Number Manually set width of each bar in pixels. If not set, the base sample widths are calculated automatically so that they take the full available widths without overlap. Then, the bars are sized using barPercentage and categoryPercentage. maxBarThickness Number Set this to ensure that bars are not sized thicker than this. gridLines.offsetGridLines Boolean true If true, the bars for a particular data point fall between the grid lines. The grid line will move to the left by one half of the tick interval. If false, the grid line will go right down the middle of the bars. more... offsetGridLines If true, the bars for a particular data point fall between the grid lines. The grid line will move to the left by one half of the tick interval, which is the space between the grid lines. If false, the grid line will go right down the middle of the bars. This is set to true for a bar chart while false for other charts by default. This setting applies to the axis configuration. If axes are added to the chart, this setting will need to be set for each new axis. options = { scales: { xAxes: [{ gridLines: { offsetGridLines: true } }] } } Default Options It is common to want to apply a configuration setting to all created bar charts. The global bar chart settings are stored in Chart.defaults.bar. Changing the global options only affects charts created after the change. Existing charts are not changed. 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: |==============| Data Structure The data property of a dataset for a bar chart is specified as a an array of numbers. Each point in the data array corresponds to the label at the same index on the x axis. data: [20, 10] You can also specify the dataset as x/y coordinates when using the time scale. data: [{x:'2016-12-25', y:20}, {x:'2016-12-26', y:10}] Stacked Bar Chart Bar charts can be configured into stacked bar charts by changing the settings on the X and Y axes to enable stacking. Stacked bar charts can be used to show how one data series is made up of a number of smaller pieces. var stackedBar = new Chart(ctx, { type: 'bar', data: data, options: { scales: { xAxes: [{ stacked: true }], yAxes: [{ stacked: true }] } } }); Dataset Properties The following dataset properties are specific to stacked bar charts. Name Type Description stack String The ID of the group to which this dataset belongs to (when stacked, each group will be a separate stack) Horizontal Bar Chart A horizontal bar chart is a variation on a vertical bar chart. It is sometimes used to show trend data, and the comparison of multiple data sets side by side. new Chart(document.getElementById(\"chartjs-2\"),{\"type\":\"horizontalBar\",\"data\":{\"labels\":[\"January\",\"February\",\"March\",\"April\",\"May\",\"June\",\"July\"],\"datasets\":[{\"label\":\"My First Dataset\",\"data\":[65,59,80,81,56,55,40],\"fill\":false,\"backgroundColor\":[\"rgba(255, 99, 132, 0.2)\",\"rgba(255, 159, 64, 0.2)\",\"rgba(255, 205, 86, 0.2)\",\"rgba(75, 192, 192, 0.2)\",\"rgba(54, 162, 235, 0.2)\",\"rgba(153, 102, 255, 0.2)\",\"rgba(201, 203, 207, 0.2)\"],\"borderColor\":[\"rgb(255, 99, 132)\",\"rgb(255, 159, 64)\",\"rgb(255, 205, 86)\",\"rgb(75, 192, 192)\",\"rgb(54, 162, 235)\",\"rgb(153, 102, 255)\",\"rgb(201, 203, 207)\"],\"borderWidth\":1}]},\"options\":{\"scales\":{\"xAxes\":[{\"ticks\":{\"beginAtZero\":true}}]}}}); Example var myBarChart = new Chart(ctx, { type: 'horizontalBar', data: data, options: options }); Config Options The configuration options for the horizontal bar chart are the same as for the bar chart. However, any options specified on the x axis in a bar chart, are applied to the y axis in a horizontal bar chart. The default horizontal bar configuration is specified in Chart.defaults.horizontalBar. "},"charts/radar.html":{"url":"charts/radar.html","title":"Radar","keywords":"","body":"Radar 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. new Chart(document.getElementById(\"chartjs-3\"),{\"type\":\"radar\",\"data\":{\"labels\":[\"Eating\",\"Drinking\",\"Sleeping\",\"Designing\",\"Coding\",\"Cycling\",\"Running\"],\"datasets\":[{\"label\":\"My First Dataset\",\"data\":[65,59,90,81,56,55,40],\"fill\":true,\"backgroundColor\":\"rgba(255, 99, 132, 0.2)\",\"borderColor\":\"rgb(255, 99, 132)\",\"pointBackgroundColor\":\"rgb(255, 99, 132)\",\"pointBorderColor\":\"#fff\",\"pointHoverBackgroundColor\":\"#fff\",\"pointHoverBorderColor\":\"rgb(255, 99, 132)\"},{\"label\":\"My Second Dataset\",\"data\":[28,48,40,19,96,27,100],\"fill\":true,\"backgroundColor\":\"rgba(54, 162, 235, 0.2)\",\"borderColor\":\"rgb(54, 162, 235)\",\"pointBackgroundColor\":\"rgb(54, 162, 235)\",\"pointBorderColor\":\"#fff\",\"pointHoverBackgroundColor\":\"#fff\",\"pointHoverBorderColor\":\"rgb(54, 162, 235)\"}]},\"options\":{\"elements\":{\"line\":{\"tension\":0,\"borderWidth\":3}}}}); Example Usage var myRadarChart = new Chart(ctx, { type: 'radar', data: data, options: options }); Dataset Properties The radar chart allows a number of properties to be specified for each dataset. These are used to set display properties for a specific dataset. For example, the colour of a line is generally set this way. 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. Name Type Description label String The label for the dataset which appears in the legend and tooltips. backgroundColor Color The fill color under the line. See Colors borderColor Color The color of the line. See Colors borderWidth Number The width of the line in pixels. borderDash Number[] Length and spacing of dashes. See MDN borderDashOffset Number Offset for line dashes. See MDN borderCapStyle String Cap style of the line. See MDN borderJoinStyle String Line joint style. See MDN fill Boolean/String How to fill the area under the line. See area charts lineTension Number Bezier curve tension of the line. Set to 0 to draw straightlines. pointBackgroundColor Color/Color[] The fill color for points. pointBorderColor Color/Color[] The border color for points. pointBorderWidth Number/Number[] The width of the point border in pixels. pointRadius Number/Number[] The radius of the point shape. If set to 0, the point is not rendered. pointStyle String/String[]/Image/Image[] Style of the point. more... pointHitRadius Number/Number[] The pixel size of the non-displayed point that reacts to mouse events. pointHoverBackgroundColor Color/Color[] Point background color when hovered. pointHoverBorderColor Color/Color[] Point border color when hovered. pointHoverBorderWidth Number/Number[] Border width of point when hovered. pointHoverRadius Number/Number[] The radius of the point when hovered. pointStyle The style of point. Options are: 'circle' 'cross' 'crossRot' 'dash'. 'line' 'rect' 'rectRounded' 'rectRot' 'star' 'triangle' If the option is an image, that image is drawn on the canvas using drawImage. Configuration Options Unlike other charts, the radar chart has no chart specific options. Scale Options The radar chart supports only a single scale. The options for this scale are defined in the scale property. options = { scale: { // Hides the scale display: false } }; Default Options It is common to want to apply a configuration setting to all created radar charts. The global radar chart settings are stored in Chart.defaults.radar. Changing the global options only affects charts created after the change. Existing charts are not changed. Data Structure The data property of a dataset for a radar chart is specified as a an array of numbers. Each point in the data array corresponds to the label at the same index on the x axis. data: [20, 10] 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. data: { labels: ['Running', 'Swimming', 'Eating', 'Cycling'], datasets: [{ data: [20, 10, 4, 2] }] } "},"charts/doughnut.html":{"url":"charts/doughnut.html","title":"Doughnut & Pie","keywords":"","body":"Doughnut and Pie Pie and doughnut charts are probably the most commonly used charts. 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. new Chart(document.getElementById(\"chartjs-4\"),{\"type\":\"doughnut\",\"data\":{\"labels\":[\"Red\",\"Blue\",\"Yellow\"],\"datasets\":[{\"label\":\"My First Dataset\",\"data\":[300,50,100],\"backgroundColor\":[\"rgb(255, 99, 132)\",\"rgb(54, 162, 235)\",\"rgb(255, 205, 86)\"]}]}}); 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 }); Dataset Properties The doughnut/pie chart allows a number of properties to be specified for each dataset. These are used to set display properties for a specific dataset. For example, the colour of a the dataset's arc are generally set this way. Name Type Description backgroundColor Color[] The fill color of the arcs in the dataset. See Colors borderColor Color[] The border color of the arcs in the dataset. See Colors borderWidth Number[] The border width of the arcs in the dataset. hoverBackgroundColor Color[] The fill colour of the arcs when hovered. hoverBorderColor Color[] The stroke colour of the arcs when hovered. hoverBorderWidth Number[] The stroke width of the arcs when hovered. Config 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, the chart will animate in with a rotation animation. This property is in the options.animation object. animation.animateScale Boolean false If true, will animate scaling the chart from the center outwards. Default Options 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. Data Structure 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 also need to specify an array of labels so that tooltips appear correctly data = { datasets: [{ data: [10, 20, 30] }], // These labels appear in the legend and in the tooltips when hovering different arcs labels: [ 'Red', 'Yellow', 'Blue' ] }; "},"charts/polar.html":{"url":"charts/polar.html","title":"Polar Area","keywords":"","body":"Polar Area 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. new Chart(document.getElementById(\"chartjs-5\"),{\"type\":\"polarArea\",\"data\":{\"labels\":[\"Red\",\"Green\",\"Yellow\",\"Grey\",\"Blue\"],\"datasets\":[{\"label\":\"My First Dataset\",\"data\":[11,16,7,3,14],\"backgroundColor\":[\"rgb(255, 99, 132)\",\"rgb(75, 192, 192)\",\"rgb(255, 205, 86)\",\"rgb(201, 203, 207)\",\"rgb(54, 162, 235)\"]}]}}); Example Usage new Chart(ctx, { data: data, type: 'polarArea', options: options }); Dataset Properties The following options can be included in a polar area chart dataset to configure options for that specific dataset. Name Type Description backgroundColor Color[] The fill color of the arcs in the dataset. See Colors borderColor Color[] The border color of the arcs in the dataset. See Colors borderWidth Number[] The border width of the arcs in the dataset. hoverBackgroundColor Color[] The fill colour of the arcs when hovered. hoverBorderColor Color[] The stroke colour of the arcs when hovered. hoverBorderWidth Number[] The stroke width of the arcs when hovered. Config Options These are the customisation options specific to Polar Area charts. These options are merged with the global chart default options, and form the options of the chart. Name Type Default Description startAngle Number -0.5 * Math.PI Starting angle to draw arcs for the first item in a dataset. animation.animateRotate Boolean true If true, the chart will animate in with a rotation animation. This property is in the options.animation object. animation.animateScale Boolean true If true, will animate scaling the chart from the center outwards. Default Options We can also change these defaults values for each PolarArea type that is created, this object is available at Chart.defaults.polarArea. Changing the global options only affects charts created after the change. Existing charts are not changed. For example, to configure all new polar area charts with animateScale = false you would do: Chart.defaults.polarArea.animation.animateScale = false; Data Structure For a polar area 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 also need to specify an array of labels so that tooltips appear correctly for each slice. data = { datasets: [{ data: [10, 20, 30] }], // These labels appear in the legend and in the tooltips when hovering different arcs labels: [ 'Red', 'Yellow', 'Blue' ] }; "},"charts/bubble.html":{"url":"charts/bubble.html","title":"Bubble","keywords":"","body":"Bubble Chart A bubble chart is used to display three dimensions of data at the same time. The location of the bubble is determined by the first two dimensions and the corresponding horizontal and vertical axes. The third dimension is represented by the size of the individual bubbles. new Chart(document.getElementById(\"chartjs-6\"),{\"type\":\"bubble\",\"data\":{\"datasets\":[{\"label\":\"First Dataset\",\"data\":[{\"x\":20,\"y\":30,\"r\":15},{\"x\":40,\"y\":10,\"r\":10}],\"backgroundColor\":\"rgb(255, 99, 132)\"}]}}); Example Usage // For a bubble chart var myBubbleChart = new Chart(ctx,{ type: 'bubble', data: data, options: options }); Dataset Properties The bubble chart allows a number of properties to be specified for each dataset. These are used to set display properties for a specific dataset. For example, the colour of the bubbles is generally set this way. Name Type Scriptable Indexable Default backgroundColor Color Yes Yes 'rgba(0,0,0,0.1)' borderColor Color Yes Yes 'rgba(0,0,0,0.1)' borderWidth Number Yes Yes 3 data Object[] - - required hoverBackgroundColor Color Yes Yes undefined hoverBorderColor Color Yes Yes undefined hoverBorderWidth Number Yes Yes 1 hoverRadius Number Yes Yes 4 hitRadius Number Yes Yes 1 label String - - undefined pointStyle String Yes Yes circle radius Number Yes Yes 3 Labeling label defines the text associated to the dataset and which appears in the legend and tooltips. Styling The style of each bubble can be controlled with the following properties: Name Description backgroundColor bubble background color borderColor bubble border color borderWidth bubble border width (in pixels) pointStyle bubble shape style radius bubble radius (in pixels) All these values, if undefined, fallback to the associated elements.point.* options. Interactions The interaction with each bubble can be controlled with the following properties: Name Description hoverBackgroundColor bubble background color when hovered hoverBorderColor bubble border color hovered hoverBorderWidth bubble border width when hovered (in pixels) hoverRadius bubble additional radius when hovered (in pixels) hitRadius bubble additional radius for hit detection (in pixels) All these values, if undefined, fallback to the associated elements.point.* options. Default Options We can also change the default values for the Bubble chart type. Doing so will give all bubble charts created after this point the new defaults. The default configuration for the bubble chart can be accessed at Chart.defaults.bubble. Data Structure Bubble chart datasets need to contain a data array of points, each points represented by an object containing the following properties: { // X Value x: , // Y Value y: , // Bubble radius in pixels (not scaled). r: } Important: the radius property, r is not scaled by the chart, it is the raw radius in pixels of the bubble that is drawn on the canvas. "},"charts/scatter.html":{"url":"charts/scatter.html","title":"Scatter","keywords":"","body":"Scatter Chart Scatter charts are based on basic line charts with the x axis changed to a linear axis. To use a scatter chart, data must be passed as objects containing X and Y properties. The example below creates a scatter chart with 3 points. var scatterChart = new Chart(ctx, { type: 'scatter', data: { datasets: [{ label: 'Scatter Dataset', data: [{ x: -10, y: 0 }, { x: 0, y: 10 }, { x: 10, y: 5 }] }] }, options: { scales: { xAxes: [{ type: 'linear', position: 'bottom' }] } } }); Dataset Properties The scatter chart supports all of the same properties as the line chart. Data Structure Unlike the line chart where data can be supplied in two different formats, the scatter chart only accepts data in a point format. data: [{ x: 10, y: 20 }, { x: 15, y: 10 }] "},"charts/area.html":{"url":"charts/area.html","title":"Area","keywords":"","body":"Area Charts Both line and radar charts support a fill option on the dataset object which can be used to create area between two datasets or a dataset and a boundary, i.e. the scale origin, start or end (see filling modes). Note: this feature is implemented by the filler plugin. Filling modes Mode Type Values Absolute dataset index 1 Number 1, 2, 3, ... Relative dataset index 1 String '-1', '-2', '+1', ... Boundary 2 String 'start', 'end', 'origin' Disabled 3 Boolean false 1 dataset filling modes have been introduced in version 2.6.0 2 prior version 2.6.0, boundary values was 'zero', 'top', 'bottom' (deprecated) 3 for backward compatibility, fill: true (default) is equivalent to fill: 'origin' Example new Chart(ctx, { data: { datasets: [ {fill: 'origin'}, // 0: fill to 'origin' {fill: '+2'}, // 1: fill to dataset 3 {fill: 1}, // 2: fill to dataset 1 {fill: false}, // 3: no fill {fill: '-2'} // 4: fill to dataset 2 ] } }) Configuration Option Type Default Description plugins.filler.propagate Boolean true Fill propagation when target is hidden propagate Boolean (default: true) If true, the fill area will be recursively extended to the visible target defined by the fill value of hidden dataset targets: Example new Chart(ctx, { data: { datasets: [ {fill: 'origin'}, // 0: fill to 'origin' {fill: '-1'}, // 1: fill to dataset 0 {fill: 1}, // 2: fill to dataset 1 {fill: false}, // 3: no fill {fill: '-2'} // 4: fill to dataset 2 ] }, options: { plugins: { filler: { propagate: true } } } }) propagate: true: if dataset 2 is hidden, dataset 4 will fill to dataset 1 if dataset 2 and 1 are hidden, dataset 4 will fill to 'origin' propagate: false: if dataset 2 and/or 4 are hidden, dataset 4 will not be filled "},"charts/mixed.html":{"url":"charts/mixed.html","title":"Mixed","keywords":"","body":"Mixed Chart Types With Chart.js, it is possible to create mixed charts that are a combination of two or more different chart types. A common example is a bar chart that also includes a line dataset. Creating a mixed chart starts with the initialization of a basic chart. var myChart = new Chart(ctx, { type: 'bar', data: data, options: options }); At this point we have a standard bar chart. Now we need to convert one of the datasets to a line dataset. var mixedChart = new Chart(ctx, { type: 'bar', data: { datasets: [{ label: 'Bar Dataset', data: [10, 20, 30, 40] }, { label: 'Line Dataset', data: [50, 50, 50, 50], // Changes this dataset to become a line type: 'line' }], labels: ['January', 'February', 'March', 'April'] }, options: options }); At this point we have a chart rendering how we'd like. It's important to note that the default options for a line chart are not merged in this case. Only the options for the default type are merged in. In this case, that means that the default options for a bar chart are merged because that is the type specified by the type field. new Chart(document.getElementById(\"chartjs-7\"),{\"type\":\"bar\",\"data\":{\"labels\":[\"January\",\"February\",\"March\",\"April\"],\"datasets\":[{\"label\":\"Bar Dataset\",\"data\":[10,20,30,40],\"borderColor\":\"rgb(255, 99, 132)\",\"backgroundColor\":\"rgba(255, 99, 132, 0.2)\"},{\"label\":\"Line Dataset\",\"data\":[50,50,50,50],\"type\":\"line\",\"fill\":false,\"borderColor\":\"rgb(54, 162, 235)\"}]},\"options\":{\"scales\":{\"yAxes\":[{\"ticks\":{\"beginAtZero\":true}}]}}}); "},"axes/":{"url":"axes/","title":"Axes","keywords":"","body":"Axes Axes are an integral part of a chart. They are used to determine how data maps to a pixel value on the chart. In a cartesian chart, there is 1 or more X axis and 1 or more Y axis to map points onto the 2 dimensional canvas. These axes are know as 'cartesian axes'. In a radial chart, such as a radar chart or a polar area chart, there is a single axis that maps points in the angular and radial directions. These are known as 'radial axes'. Scales in Chart.js >V2.0 are significantly more powerful, but also different than those of v1.0. Multiple X & Y axes are supported. A built-in label auto-skip feature detects would-be overlapping ticks and labels and removes every nth label to keep things displaying normally. Scale titles are supported New scale types can be extended without writing an entirely new chart type Common Configuration The following properties are common to all axes provided by Chart.js Name Type Default Description display Boolean true If set to false the axis is hidden from view. Overrides gridLines.display, scaleLabel.display, and ticks.display. callbacks Object Callback functions to hook into the axis lifecycle. more... weight Number 0 The weight used to sort the axis. Higher weights are further away from the chart area. Callbacks There are a number of config callbacks that can be used to change parameters in the scale at different points in the update process. Name Arguments Description beforeUpdate axis Callback called before the update process starts. beforeSetDimensions axis Callback that runs before dimensions are set. afterSetDimensions axis Callback that runs after dimensions are set. beforeDataLimits axis Callback that runs before data limits are determined. afterDataLimits axis Callback that runs after data limits are determined. beforeBuildTicks axis Callback that runs before ticks are created. afterBuildTicks axis Callback that runs after ticks are created. Useful for filtering ticks. beforeTickToLabelConversion axis Callback that runs before ticks are converted into strings. afterTickToLabelConversion axis Callback that runs after ticks are converted into strings. beforeCalculateTickRotation axis Callback that runs before tick rotation is determined. afterCalculateTickRotation axis Callback that runs after tick rotation is determined. beforeFit axis Callback that runs before the scale fits to the canvas. afterFit axis Callback that runs after the scale fits to the canvas. afterUpdate axis Callback that runs at the end of the update process. Updating Axis Defaults The default configuration for a scale can be easily changed using the scale service. All you need to do is to pass in a partial configuration that will be merged with the current scale default configuration to form the new default. For example, to set the minimum value of 0 for all linear scales, you would do the following. Any linear scales created after this time would now have a minimum of 0. Chart.scaleService.updateScaleDefaults('linear', { ticks: { min: 0 } }); Creating New Axes To create a new axis, see the developer docs. "},"axes/cartesian/":{"url":"axes/cartesian/","title":"Cartesian","keywords":"","body":"Cartesian Axes Axes that follow a cartesian grid are known as 'Cartesian Axes'. Cartesian axes are used for line, bar, and bubble charts. Four cartesian axes are included in Chart.js by default. linear logarithmic category time Common Configuration All of the included cartesian axes support a number of common options. Name Type Default Description type String Type of scale being employed. Custom scales can be created and registered with a string key. This allows changing the type of an axis for a chart. position String Position of the axis in the chart. Possible values are: 'top', 'left', 'bottom', 'right' offset Boolean false If true, extra space is added to the both edges and the axis is scaled to fit into the chart area. This is set to true in the bar chart by default. id String The ID is used to link datasets and scale axes together. more... gridLines Object Grid line configuration. more... scaleLabel Object Scale title configuration. more... ticks Object Tick configuration. more... Tick Configuration The following options are common to all cartesian axes but do not apply to other axes. Name Type Default Description 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 autoSkipPadding Number 0 Padding between the ticks on the horizontal axis when autoSkip is enabled. Note: Only applicable to horizontal scales. labelOffset Number 0 Distance in pixels to offset the label from the centre point of the tick (in the y direction for the x axis, and the x direction for the y axis). Note: this can cause labels at the edges to be cropped by the edge of the canvas 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. minRotation Number 0 Minimum rotation for tick labels. Note: Only applicable to horizontal scales. mirror Boolean false Flips tick labels around axis, displaying the labels inside the chart instead of outside. Note: Only applicable to vertical scales. padding Number 10 Padding between the tick label and the axis. When set on a vertical axis, this applies in the horizontal (X) direction. When set on a horizontal axis, this applies in the vertical (Y) direction. Axis ID The properties dataset.xAxisID or dataset.yAxisID have to match the scale properties scales.xAxes.id or scales.yAxes.id. This is especially needed if multi-axes charts are used. var myChart = new Chart(ctx, { type: 'line', data: { datasets: [{ // This dataset appears on the first axis yAxisID: 'first-y-axis' }, { // This dataset appears on the second axis yAxisID: 'second-y-axis' }] }, options: { scales: { yAxes: [{ id: 'first-y-axis', type: 'linear' }, { id: 'second-y-axis', type: 'linear' }] } } }); Creating Multiple Axes With cartesian axes, it is possible to create multiple X and Y axes. To do so, you can add multiple configuration objects to the xAxes and yAxes properties. When adding new axes, it is important to ensure that you specify the type of the new axes as default types are not used in this case. In the example below, we are creating two Y axes. We then use the yAxisID property to map the datasets to their correct axes. var myChart = new Chart(ctx, { type: 'line', data: { datasets: [{ data: [20, 50, 100, 75, 25, 0], label: 'Left dataset', // This binds the dataset to the left y axis yAxisID: 'left-y-axis' }, { data: [0.1, 0.5, 1.0, 2.0, 1.5, 0], label: 'Right dataset', // This binds the dataset to the right y axis yAxisID: 'right-y-axis', }], labels: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun'] }, options: { scales: { yAxes: [{ id: 'left-y-axis', type: 'linear', position: 'left' }, { id: 'right-y-axis', type: 'linear', position: 'right' }] } } }); "},"axes/cartesian/category.html":{"url":"axes/cartesian/category.html","title":"Category","keywords":"","body":"Category Cartesian Axis If global configuration is used, labels are drawn from one of the label arrays included in the chart data. If only data.labels is defined, this will be used. If data.xLabels is defined and the axis is horizontal, this will be used. Similarly, if data.yLabels is defined and the axis is vertical, this property will be used. Using both xLabels and yLabels together can create a chart that uses strings for both the X and Y axes. Specifying any of the settings above defines the x axis as type: category if not defined otherwise. For more fine-grained control of category labels it is also possible to add labels as part of the category axis definition. Doing so does not apply the global defaults. Category Axis Definition Globally: let chart = new Chart(ctx, { type: ... data: { labels: ['January', 'February', 'March', 'April', 'May', 'June'], datasets: ... }, }); As part of axis definition: let chart = new Chart(ctx, { type: ... data: ... options: { scales: { xAxes: [{ type: 'category', labels: ['January', 'February', 'March', 'April', 'May', 'June'], }] } } }); Tick Configuration Options The category scale provides the following options for configuring tick marks. They are nested in the ticks sub object. These options extend the common tick configuration. Name Type Default Description labels Array[String] - An array of labels to display. min String The minimum item to display. more... max String The maximum item to display. more... Min Max Configuration For both the min and max properties, the value must be in the labels array. In the example below, the x axis would only display \"March\" through \"June\". let chart = new Chart(ctx, { type: 'line', data: { datasets: [{ data: [10, 20, 30, 40, 50, 60] }], labels: ['January', 'February', 'March', 'April', 'May', 'June'], }, options: { scales: { xAxes: [{ ticks: { min: 'March' } }] } } }); "},"axes/cartesian/linear.html":{"url":"axes/cartesian/linear.html","title":"Linear","keywords":"","body":"Linear Cartesian Axis The linear scale is use to chart 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. As the name suggests, linear interpolation is used to determine where a value lies on the axis. Tick Configuration Options The following options are provided by the linear scale. They are all located in the ticks sub options. These options extend the common tick configuration. Name Type Default Description beginAtZero Boolean if true, scale will include 0 if it is not already included. min Number User defined minimum number for the scale, overrides minimum value from data. more... max Number User defined maximum number for the scale, overrides maximum value from data. more... maxTicksLimit Number 11 Maximum number of ticks and gridlines to show. stepSize Number User defined fixed step size for the scale. more... suggestedMax Number Adjustment used when calculating the maximum data value. more... suggestedMin Number Adjustment used when calculating the minimum data value. more... Axis Range Settings Given the number of axis range settings, it is important to understand how they all interact with each other. The suggestedMax and suggestedMin settings only change the data values that are used to scale the axis. These are useful for extending the range of the axis while maintaining the auto fit behaviour. let minDataValue = Math.min(mostNegativeValue, options.ticks.suggestedMin); let maxDataValue = Math.max(mostPositiveValue, options.ticks.suggestedMax); In this example, the largest positive value is 50, but the data maximum is expanded out to 100. However, because the lowest data value is below the suggestedMin setting, it is ignored. let chart = new Chart(ctx, { type: 'line', data: { datasets: [{ label: 'First dataset', data: [0, 20, 40, 50] }], labels: ['January', 'February', 'March', 'April'] }, options: { scales: { yAxes: [{ ticks: { suggestedMin: 50, suggestedMax: 100 } }] } } }); In contrast to the suggested* settings, the min and max settings set explicit ends to the axes. When these are set, some data points may not be visible. Step Size 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. This example sets up a chart with a y axis that creates ticks at 0, 0.5, 1, 1.5, 2, 2.5, 3, 3.5, 4, 4.5, 5. let options = { scales: { yAxes: [{ ticks: { max: 5, min: 0, stepSize: 0.5 } }] } }; "},"axes/cartesian/logarithmic.html":{"url":"axes/cartesian/logarithmic.html","title":"Logarithmic","keywords":"","body":"Logarithmic Cartesian Axis The logarithmic scale is use to chart numerical data. It can be placed on either the x or y axis. As the name suggests, logarithmic interpolation is used to determine where a value lies on the axis. Tick Configuration Options The following options are provided by the logarithmic scale. They are all located in the ticks sub options. These options extend the common tick configuration. Name Type Default Description min Number User defined minimum number for the scale, overrides minimum value from data. max Number User defined maximum number for the scale, overrides maximum value from data. "},"axes/cartesian/time.html":{"url":"axes/cartesian/time.html","title":"Time","keywords":"","body":"Time Cartesian Axis The time scale is used to display times and dates. When building its ticks, it will automatically calculate the most comfortable unit base on the size of the scale. Data Sets Input Data The x-axis data points may additionally be specified via the t attribute when using the time scale. data: [{ x: new Date(), y: 1 }, { t: new Date(), y: 10 }] Date Formats When providing data for the time scale, Chart.js supports all of the formats that Moment.js accepts. See Moment.js docs for details. Configuration Options The following options are provided by the time scale. You may also set options provided by the common tick configuration. Name Type Default Description distribution String linear How data is plotted. more... bounds String data Determines the scale bounds. more... ticks.source String auto How ticks are generated. more... time.displayFormats Object Sets how different time units are displayed. more... time.isoWeekday Boolean false If true and the unit is set to 'week', then the first day of the week will be Monday. Otherwise, it will be Sunday. time.max Time If defined, this will override the data maximum time.min Time If defined, this will override the data minimum time.parser String/Function Custom parser for dates. more... time.round String false If defined, dates will be rounded to the start of this unit. See Time Units below for the allowed units. time.tooltipFormat String The moment js format string to use for the tooltip. time.unit String false If defined, will force the unit to be a certain type. See Time Units section below for details. time.stepSize Number 1 The number of units between grid lines. time.minUnit String 'millisecond' The minimum display format to be used for a time unit. Time Units The following time measurements are supported. The names can be passed as strings to the time.unit config option to force a certain unit. millisecond second minute hour day week month quarter year For example, to create a chart with a time scale that always displayed units per month, the following config could be used. var chart = new Chart(ctx, { type: 'line', data: data, options: { scales: { xAxes: [{ time: { unit: 'month' } }] } } }) Display Formats The following display formats are used to configure how different time units are formed into strings for the axis tick marks. See moment.js for the allowable format strings. Name Default Example millisecond 'h:mm:ss.SSS a' 11:20:01.123 AM second 'h:mm:ss a' 11:20:01 AM minute 'h:mm a' 11:20 AM hour 'hA' 11AM day 'MMM D' Sep 4 week 'll' Sep 4 2015 month 'MMM YYYY' Sep 2015 quarter '[Q]Q - YYYY' Q3 - 2015 year 'YYYY' 2015 For example, to set the display format for the 'quarter' unit to show the month and year, the following config would be passed to the chart constructor. var chart = new Chart(ctx, { type: 'line', data: data, options: { scales: { xAxes: [{ type: 'time', time: { displayFormats: { quarter: 'MMM YYYY' } } }] } } }) Scale Distribution The distribution property controls the data distribution along the scale: 'linear': data are spread according to their time (distances can vary) 'series': data are spread at the same distance from each other var chart = new Chart(ctx, { type: 'line', data: data, options: { scales: { xAxes: [{ type: 'time', distribution: 'series' }] } } }) Scale Bounds The bounds property controls the scale boundary strategy (bypassed by min/max time options) 'data': make sure data are fully visible, labels outside are removed 'ticks': make sure ticks are fully visible, data outside are truncated Ticks Source The ticks.source property controls the ticks generation 'auto': generates \"optimal\" ticks based on scale size and time options. 'data': generates ticks from data (including labels from data {t|x|y} objects) 'labels': generates ticks from user given data.labels values ONLY Parser If this property is defined as a string, it is interpreted as a custom format to be used by moment to parse the date. If this is a function, it must return a moment.js object given the appropriate data value. "},"axes/radial/":{"url":"axes/radial/","title":"Radial","keywords":"","body":"Radial Axes Radial axes are used specifically for the radar and polar area chart types. These axes overlay the chart area, rather than being positioned on one of the edges. One radial axis is included by default in Chart.js. linear "},"axes/radial/linear.html":{"url":"axes/radial/linear.html","title":"Linear","keywords":"","body":"Linear Radial Axis The linear scale is use to chart numerical data. As the name suggests, linear interpolation is used to determine where a value lies in relation the center of the axis. The following additional configuration options are provided by the radial linear scale. Configuration Options The axis has configuration properties for ticks, angle lines (line that appear in a radar chart outward from the center), pointLabels (labels around the edge in a radar chart). The following sections define each of the properties in those sections. Name Type Description angleLines Object Angle line configuration. more... gridLines Object Grid line configuration. more... pointLabels Object Point label configuration. more... ticks Object Tick configuration. more... Tick Options The following options are provided by the linear scale. They are all located in the ticks sub options. The common tick configuration options are supported by this axis. Name Type Default Description backdropColor Color 'rgba(255, 255, 255, 0.75)' Color of label backdrops backdropPaddingX Number 2 Horizontal padding of label backdrop. backdropPaddingY Number 2 Vertical padding of label backdrop. beginAtZero Boolean false if true, scale will include 0 if it is not already included. min Number User defined minimum number for the scale, overrides minimum value from data. more... max Number User defined maximum number for the scale, overrides maximum value from data. more... maxTicksLimit Number 11 Maximum number of ticks and gridlines to show. stepSize Number User defined fixed step size for the scale. more... suggestedMax Number Adjustment used when calculating the maximum data value. more... suggestedMin Number Adjustment used when calculating the minimum data value. more... showLabelBackdrop Boolean true If true, draw a background behind the tick labels Axis Range Settings Given the number of axis range settings, it is important to understand how they all interact with each other. The suggestedMax and suggestedMin settings only change the data values that are used to scale the axis. These are useful for extending the range of the axis while maintaining the auto fit behaviour. let minDataValue = Math.min(mostNegativeValue, options.ticks.suggestedMin); let maxDataValue = Math.max(mostPositiveValue, options.ticks.suggestedMax); In this example, the largest positive value is 50, but the data maximum is expanded out to 100. However, because the lowest data value is below the suggestedMin setting, it is ignored. let chart = new Chart(ctx, { type: 'radar', data: { datasets: [{ label: 'First dataset', data: [0, 20, 40, 50] }], labels: ['January', 'February', 'March', 'April'] }, options: { scale: { ticks: { suggestedMin: 50, suggestedMax: 100 } } } }); In contrast to the suggested* settings, the min and max settings set explicit ends to the axes. When these are set, some data points may not be visible. Step Size 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. This example sets up a chart with a y axis that creates ticks at 0, 0.5, 1, 1.5, 2, 2.5, 3, 3.5, 4, 4.5, 5. let options = { scales: { yAxes: [{ ticks: { max: 5, min: 0, stepSize: 0.5 } }] } }; Angle Line Options The following options are used to configure angled lines that radiate from the center of the chart to the point labels. They can be found in the angleLines sub options. Note that these options only apply if angleLines.display is true. Name Type Default Description display Boolean true if true, angle lines are shown color Color rgba(0, 0, 0, 0.1) Color of angled lines lineWidth Number 1 Width of angled lines Point Label Options The following options are used to configure the point labels that are shown on the perimeter of the scale. They can be found in the pointLabels sub options. Note that these options only apply if pointLabels.display is true. Name Type Default Description callback Function Callback function to transform data labels to point labels. The default implementation simply returns the current string. fontColor Color/Color[] '#666' Font color for point labels. fontFamily String \"'Helvetica Neue', 'Helvetica', 'Arial', sans-serif\" Font family to use when rendering labels. fontSize Number 10 font size in pixels fontStyle String 'normal' Font style to use when rendering point labels. "},"axes/labelling.html":{"url":"axes/labelling.html","title":"Labelling","keywords":"","body":"Labeling Axes When creating a chart, you want to tell the viewer what data they are viewing. To do this, you need to label the axis. Scale Title Configuration The scale label configuration is nested under the scale configuration in the scaleLabel key. It defines options for the scale title. Note that this only applies to cartesian axes. Name Type Default Description display Boolean false If true, display the axis title. labelString String '' The text for the title. (i.e. \"# of People\" or \"Response Choices\"). lineHeight Number/String 1.2 Height of an individual line of text (see MDN) fontColor Color '#666' Font color for scale title. fontFamily String \"'Helvetica Neue', 'Helvetica', 'Arial', sans-serif\" Font family for the scale title, follows CSS font-family options. fontSize Number 12 Font size for scale title. fontStyle String 'normal' Font style for the scale title, follows CSS font-style options (i.e. normal, italic, oblique, initial, inherit). padding Number/Object 4 Padding to apply around scale labels. Only top and bottom are implemented. Creating Custom Tick Formats It is also common to want to change the tick marks to include information about the data type. For example, adding a dollar sign ('$'). To do this, you need to override the ticks.callback method in the axis configuration. In the following example, every label of the Y axis would be displayed with a dollar sign at the front.. If the callback returns null or undefined the associated grid line will be hidden. var chart = new Chart(ctx, { type: 'line', data: data, options: { scales: { yAxes: [{ ticks: { // Include a dollar sign in the ticks callback: function(value, index, values) { return '$' + value; } } }] } } }); "},"axes/styling.html":{"url":"axes/styling.html","title":"Styling","keywords":"","body":"Styling There are a number of options to allow styling an axis. There are settings to control grid lines and ticks. Grid Line Configuration The grid line configuration is nested under the scale configuration in the gridLines key. It defines options for the grid lines that run perpendicular to the axis. Name Type Default Description display Boolean true If false, do not display grid lines for this axis. color Color/Color[] 'rgba(0, 0, 0, 0.1)' The color of the grid lines. If specified as an array, the first color applies to the first grid line, the second to the second grid line and so on. borderDash Number[] [] Length and spacing of dashes on grid lines. See MDN borderDashOffset Number 0 Offset for line dashes. See MDN lineWidth Number/Number[] 1 Stroke width of grid lines. drawBorder Boolean true If true, draw border at the edge between the axis and the chart area. 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. drawTicks Boolean true If true, draw lines beside the ticks in the axis area beside the chart. tickMarkLength Number 10 Length in pixels that the grid lines will draw into the axis area. zeroLineWidth Number 1 Stroke width of the grid line for the first index (index 0). zeroLineColor Color 'rgba(0, 0, 0, 0.25)' Stroke color of the grid line for the first index (index 0). zeroLineBorderDash Number[] [] Length and spacing of dashes of the grid line for the first index (index 0). See MDN zeroLineBorderDashOffset Number 0 Offset for line dashes of the grid line for the first index (index 0). See MDN offsetGridLines Boolean false If true, grid lines will be shifted to be between labels. This is set to true in the bar chart by default. Tick Configuration The tick configuration is nested under the scale configuration in the ticks key. It defines options for the tick marks that are generated by the axis. Name Type Default Description callback Function Returns the string representation of the tick value as it should be displayed on the chart. See callback. display Boolean true If true, show tick marks fontColor Color '#666' Font color for tick labels. fontFamily String \"'Helvetica Neue', 'Helvetica', 'Arial', sans-serif\" Font family for the tick labels, follows CSS font-family options. fontSize Number 12 Font size for the tick labels. fontStyle String 'normal' Font style for the tick labels, follows CSS font-style options (i.e. normal, italic, oblique, initial, inherit). reverse Boolean false Reverses order of tick labels. minor object {} Minor ticks configuration. Omitted options are inherited from options above. major object {} Major ticks configuration. Omitted options are inherited from options above. Minor Tick Configuration The minorTick configuration is nested under the ticks configuration in the minor key. It defines options for the minor tick marks that are generated by the axis. Omitted options are inherited from ticks configuration. Name Type Default Description callback Function Returns the string representation of the tick value as it should be displayed on the chart. See callback. fontColor Color '#666' Font color for tick labels. fontFamily String \"'Helvetica Neue', 'Helvetica', 'Arial', sans-serif\" Font family for the tick labels, follows CSS font-family options. fontSize Number 12 Font size for the tick labels. fontStyle String 'normal' Font style for the tick labels, follows CSS font-style options (i.e. normal, italic, oblique, initial, inherit). Major Tick Configuration The majorTick configuration is nested under the ticks configuration in the major key. It defines options for the major tick marks that are generated by the axis. Omitted options are inherited from ticks configuration. Name Type Default Description callback Function Returns the string representation of the tick value as it should be displayed on the chart. See callback. fontColor Color '#666' Font color for tick labels. fontFamily String \"'Helvetica Neue', 'Helvetica', 'Arial', sans-serif\" Font family for the tick labels, follows CSS font-family options. fontSize Number 12 Font size for the tick labels. fontStyle String 'normal' Font style for the tick labels, follows CSS font-style options (i.e. normal, italic, oblique, initial, inherit). "},"developers/":{"url":"developers/","title":"Developers","keywords":"","body":"Developers Developer features allow extending and enhancing Chart.js in many different ways. Latest resources Latest documentation and samples, including unreleased features, are available at: http://www.chartjs.org/docs/master/ http://www.chartjs.org/samples/master/ Development releases Latest builds are available for testing at: http://www.chartjs.org/dist/master/Chart.min.js http://www.chartjs.org/dist/master/Chart.bundle.min.js Note: Development builds are currently only available via HTTP, so in order to include them in JSFiddle or CodePen, you need to access these tools via HTTP as well. WARNING: Development builds MUST not be used for production purposes or as replacement for CDN. Browser support Chart.js offers support for the following browsers: Chrome 50+ Firefox 45+ Internet Explorer 11 Edge 14+ Safari 9+ Browser support for the canvas element is available in all modern & major mobile browsers. CanIUse Thanks to BrowserStack for allowing our team to test on thousands of browsers. Previous versions Version 2 has a completely different API than earlier versions. Most earlier version options have current equivalents or are the same. Please use the documentation that is available on chartjs.org for the current version of Chart.js. Please note - documentation for previous versions are available on the GitHub repo. 1.x Documentation "},"developers/api.html":{"url":"developers/api.html","title":"Chart.js API","keywords":"","body":"Chart 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(config) Triggers an update of the chart. This can be safely called after updating the 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 milliseconds // lazy is a boolean. if true, the animation can be interrupted 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. Note: replacing the data reference (e.g. myLineChart.data = {datasets: [...]} only works starting version 2.6. Prior that, replacing the entire data object could be achieved with the following workaround: myLineChart.config.data = {datasets: [...]}. A config object can be provided with additional configuration for the update process. This is useful when update is manually called inside an event handler and some different animation is desired. The following properties are supported: duration (number): Time for the animation of the redraw in milliseconds lazy (boolean): If true, the animation can be interrupted by other animations easing (string): The animation easing function. See Animation Easing for possible values. Example: myChart.update({ duration: 800, easing: 'easeOutBounce' }) See Updating Charts for more details. .reset() Reset the chart to it's state before the initial animation. A new animation can then be triggered using update. myLineChart.reset(); .render(config) Triggers a redraw of all chart elements. Note, this does not update elements for new data. Use .update() in that case. See .update(config) for more details on the config object. // duration is the time for the animation of the redraw in milliseconds // lazy is a boolean. if true, the animation can be interrupted by other animations myLineChart.render({ duration: 800, lazy: false, easing: 'easeOutBounce' }); .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. The value returned from this method is an array with a single parameter. An array is used to keep a consistent API between the get*AtEvent methods. myLineChart.getElementAtEvent(e); // => returns the first element at the event point. To get an item that was clicked on, getElementAtEvent can be used. function clickHandler(evt) { var firstPoint = myChart.getElementAtEvent(evt)[0]; if (firstPoint) { var label = myChart.data.labels[firstPoint._index]; var value = myChart.data.datasets[firstPoint._datasetIndex].data[firstPoint._index]; } } .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 .getDatasetMeta(index) Looks for the dataset that matches the current index and returns that metadata. This returned data has all of the metadata that is used to construct the chart. The data property of the metadata will contain information about each point, rectangle, etc. depending on the chart type. Extensive examples of usage are available in the Chart.js tests. var meta = myChart.getDatasetMeta(0); var x = meta.data[0]._model.x "},"developers/updates.html":{"url":"developers/updates.html","title":"Updating Charts","keywords":"","body":"Updating Charts It's pretty common to want to update charts after they've been created. When the chart data or options are changed, Chart.js will animate to the new data values and options. Adding or Removing Data Adding and removing data is supported by changing the data array. To add data, just add data into the data array as seen in this example. function addData(chart, label, data) { chart.data.labels.push(label); chart.data.datasets.forEach((dataset) => { dataset.data.push(data); }); chart.update(); } function removeData(chart) { chart.data.labels.pop(); chart.data.datasets.forEach((dataset) => { dataset.data.pop(); }); chart.update(); } Updating Options To update the options, mutating the options property in place or passing in a new options object are supported. If the options are mutated in place, other option properties would be preserved, including those calculated by Chart.js. If created as a new object, it would be like creating a new chart with the options - old options would be discarded. function updateConfigByMutating(chart) { chart.options.title.text = 'new title'; chart.update(); } function updateConfigAsNewObject(chart) { chart.options = { responsive: true, title:{ display:true, text: 'Chart.js' }, scales: { xAxes: [{ display: true }], yAxes: [{ display: true }] } } chart.update(); } Scales can be updated separately without changing other options. To update the scales, pass in an object containing all the customization including those unchanged ones. Variables referencing any one from chart.scales would be lost after updating scales with a new id or the changed type. function updateScales(chart) { var xScale = chart.scales['x-axis-0']; var yScale = chart.scales['y-axis-0']; chart.options.scales = { xAxes: [{ id: 'newId', display: true }], yAxes: [{ display: true, type: 'logarithmic' }] } chart.update(); // need to update the reference xScale = chart.scales['newId']; yScale = chart.scales['y-axis-0']; } You can also update a specific scale either by specifying its index or id. function updateScale(chart) { chart.options.scales.yAxes[0] = { type: 'logarithmic' } chart.update(); } Code sample for updating options can be found in toggle-scale-type.html. Preventing Animations Sometimes when a chart updates, you may not want an animation. To achieve this you can call update with a duration of 0. This will render the chart synchronously and without an animation. "},"developers/plugins.html":{"url":"developers/plugins.html","title":"Plugins","keywords":"","body":"Plugins Plugins are the most efficient way to customize or change the default behavior of a chart. They have been introduced at version 2.1.0 (global plugins only) and extended at version 2.5.0 (per chart plugins and options). Using plugins Plugins can be shared between chart instances: var plugin = { /* plugin implementation */ }; // chart1 and chart2 use \"plugin\" var chart1 = new Chart(ctx, { plugins: [plugin] }); var chart2 = new Chart(ctx, { plugins: [plugin] }); // chart3 doesn't use \"plugin\" var chart3 = new Chart(ctx, {}); Plugins can also be defined directly in the chart plugins config (a.k.a. inline plugins): var chart = new Chart(ctx, { plugins: [{ beforeInit: function(chart, options) { //.. } }] }); However, this approach is not ideal when the customization needs to apply to many charts. Global plugins Plugins can be registered globally to be applied on all charts (a.k.a. global plugins): Chart.plugins.register({ // plugin implementation }); Note: inline plugins can't be registered globally. Configuration Plugin ID Plugins must define a unique id in order to be configurable. This id should follow the npm package name convention: can't start with a dot or an underscore can't contain any non-URL-safe characters can't contain uppercase letters should be something short, but also reasonably descriptive If a plugin is intended to be released publicly, you may want to check the registry to see if there's something by that name already. Note that in this case, the package name should be prefixed by chartjs-plugin- to appear in Chart.js plugin registry. Plugin options Plugin options are located under the options.plugins config and are scoped by the plugin ID: options.plugins.{plugin-id}. var chart = new Chart(ctx, { config: { foo: { ... }, // chart 'foo' option plugins: { p1: { foo: { ... }, // p1 plugin 'foo' option bar: { ... } }, p2: { foo: { ... }, // p2 plugin 'foo' option bla: { ... } } } } }); Disable plugins To disable a global plugin for a specific chart instance, the plugin options must be set to false: Chart.plugins.register({ id: 'p1', // ... }); var chart = new Chart(ctx, { config: { plugins: { p1: false // disable plugin 'p1' for this instance } } }); Plugin Core API Available hooks (as of version 2.6): beforeInit afterInit beforeUpdate (cancellable) afterUpdate beforeLayout (cancellable) afterLayout beforeDatasetsUpdate (cancellable) afterDatasetsUpdate beforeDatasetUpdate (cancellable) afterDatasetUpdate beforeRender (cancellable) afterRender beforeDraw (cancellable) afterDraw beforeDatasetsDraw (cancellable) afterDatasetsDraw beforeDatasetDraw (cancellable) afterDatasetDraw beforeEvent (cancellable) afterEvent resize destroy "},"developers/charts.html":{"url":"developers/charts.html","title":"New Charts","keywords":"","body":"New Charts 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 For example, to derive a new chart type that extends from a bubble chart, you would do the following. // Sets the default config for 'derivedBubble' to be the same as the bubble defaults. // We look for the defaults by doing Chart.defaults[chartType] // It looks like a bug exists when the defaults don't exist Chart.defaults.derivedBubble = Chart.defaults.bubble; // I think the recommend using Chart.controllers.bubble.extend({ extensions here }); var custom = Chart.controllers.bubble.extend({ draw: function(ease) { // Call super method first Chart.controllers.bubble.prototype.draw.call(this, ease); // Now we can do some custom drawing for this dataset. Here we'll draw a red box around the first point in each dataset var meta = this.getMeta(); var pt0 = meta.data[0]; var radius = pt0._view.radius; var ctx = this.chart.chart.ctx; ctx.save(); ctx.strokeStyle = 'red'; ctx.lineWidth = 1; ctx.strokeRect(pt0._view.x - radius, pt0._view.y - radius, 2 * radius, 2 * radius); ctx.restore(); } }); // Stores the controller so that the chart initialization routine can look it up with // Chart.controllers[type] Chart.controllers.derivedBubble = custom; // Now we can create and use our new chart type new Chart(ctx, { type: 'derivedBubble', data: data, options: options, }); 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. "},"developers/axes.html":{"url":"developers/axes.html","title":"New Axes","keywords":"","body":"New Axes Axes in Chart.js can be individually extended. Axes should always derive from Chart.Scale but this is not a mandatory requirement. let 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 halfway 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 halfway 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) {}, } "},"developers/contributing.html":{"url":"developers/contributing.html","title":"Contributing","keywords":"","body":"Contributing New contributions to the library are welcome, but we ask that you please follow these guidelines: Use tabs for indentation, not spaces. Only change the individual files in /src. Check that your code will pass eslint code standards, gulp lint will run this for you. Check that your code will pass tests, gulp test will run tests for you. 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 plugin would be more appropriate. Avoid breaking changes unless there is an upcoming major release, which are infrequent. We encourage people to write plugins for most new advanced features, so care a lot about backwards compatibility. Joining the project Active committers and contributors are invited to introduce yourself and request commit access to this project. We have a very active Slack community that you can join here. If you think you can help, we'd love to have you! Building and Testing 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. The following commands are now available from the repository root: > gulp build // build Chart.js in ./dist > gulp unittest // run tests from ./test/specs > gulp unittest --watch // run tests and watch for source changes > gulp unittest --coverage // run tests and generate coverage reports in ./coverage > gulp lint // perform code linting (ESLint) > gulp test // perform code linting and run unit tests > gulp docs // build the documentation in ./dist/docs More information can be found in gulpfile.js. Bugs and Issues Please report these on the GitHub page - at github.com/chartjs/Chart.js. Please do not use issues for support requests. For help using Chart.js, please take a look at the chartjs tag on Stack Overflow. Well structured, detailed bug reports are hugely valuable for the project. Guidelines for reporting bugs: Check the issue search to see if it has already been reported Isolate the problem to a simple test case Please include a demonstration of the bug on a website such as JS Bin, JS Fiddle, or Codepen. (Template) Please provide any additional details associated with the bug, if it's browser or screen density specific, or only happens with a certain configuration or data. "},"notes/":{"url":"notes/","title":"Additional Notes","keywords":"","body":"Additional Notes "},"notes/comparison.html":{"url":"notes/comparison.html","title":"Comparison Table","keywords":"","body":"Comparison with Other Charting Libraries Library Features Feature Chart.js D3 HighCharts Chartist Completely Free ✓ ✓ ✓ Canvas ✓ SVG ✓ ✓ ✓ Built-in Charts ✓ ✓ ✓ 8+ Chart Types ✓ ✓ ✓ Extendable to Custom Charts ✓ ✓ Supports Modern Browsers ✓ ✓ ✓ ✓ Extensive Documentation ✓ ✓ ✓ ✓ Open Source ✓ ✓ ✓ Built in Chart Types Type Chart.js HighCharts Chartist Combined Types ✓ ✓ Line ✓ ✓ ✓ Bar ✓ ✓ ✓ Horizontal Bar ✓ ✓ ✓ Pie/Doughnut ✓ ✓ ✓ Polar Area ✓ ✓ Radar ✓ Scatter ✓ ✓ ✓ Bubble ✓ Gauges ✓ Maps (Heat/Tree/etc.) ✓ "},"notes/extensions.html":{"url":"notes/extensions.html","title":"Popular Extensions","keywords":"","body":"Popular Extensions Many extensions can be found on the Chart.js GitHub organization or on the npm registry. Charts chartjs-chart-financial - Adds financial chart types such as a candlestick. Chart.BarFunnel.js - Adds a bar funnel chart type. Chart.LinearGauge.js - Adds a linear gauge chart type. Chart.Smith.js - Adds a smith chart type. In addition, many charts can be found on the npm registry. Plugins chartjs-plugin-annotation - Draws lines and boxes on chart area. chartjs-plugin-datalabels - Displays labels on data for any type of charts. chartjs-plugin-deferred - Defers initial chart update until chart scrolls into viewport. chartjs-plugin-draggable - Makes select chart elements draggable with the mouse. chartjs-plugin-stacked100 - Draws 100% stacked bar chart. chartjs-plugin-waterfall - Enables easy use of waterfall charts. chartjs-plugin-zoom - Enables zooming and panning on charts. In addition, many plugins can be found on the npm registry. Integrations Angular (v2+) emn178/angular2-chartjs valor-software/ng2-charts Angular (v1) angular-chart.js tc-angular-chartjs angular-chartjs Angular Chart-js Directive React react-chartjs2 react-chartjs-2 Django Django JChart Django Chartjs Ruby on Rails chartjs-ror Laravel laravel-chartjs Vue.js vue-chartjs Java Chart.java GWT (Google Web toolkit) Charba Ember.js ember-cli-chart "},"notes/license.html":{"url":"notes/license.html","title":"License","keywords":"","body":"License Chart.js is open source and available under the MIT license. "}}