chart.js
Version:
Simple HTML5 charts using the canvas element.
1 lines • 130 kB
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 attatched 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 that are available for your use. Stand-Alone Build Files: dist/Chart.js dist/Chart.min.js This version only includes Chart.js. If this version is used and you require the use of the time axis, Moment.js will need to be included before Chart.js. Bundled Build Files: dist/Chart.bundle.js dist/Chart.bundle.min.js The bundled version includes Moment.js built into the same file. This version should be used if you wish to use time axes and want a single file to include. Do not use this build if your application already includes Moment.js. If you do, Moment.js will be included twice, increasing the page load time and potentially introducing version 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'; "},"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. } } }); "},"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 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 fotter 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 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: { 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.left = position.left + tooltipModel.caretX + 'px'; tooltipEl.style.top = position.top + tooltipModel.caretY + 'px'; tooltipEl.style.fontFamily = tooltipModel._fontFamily; tooltipEl.style.fontSize = tooltipModel.fontSize; tooltipEl.style.fontStyle = tooltipModel._fontStyle; tooltipEl.style.padding = tooltipModel.yPadding + 'px ' + tooltipModel.xPadding + 'px'; } } } }); See samples/tooltips/line-customTooltips.html for examples on how to get started. 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 thi