### Bar Chart Basic Setup Source: https://github.com/chartjs/chart.js/blob/master/docs/charts/bar.md Basic configuration for creating a bar chart with Chart.js. This example demonstrates how to set up chart data with labels, datasets, and styling options including background colors, border colors, and border width. ```APIDOC ## Bar Chart Configuration ### Description Basic setup for creating a bar chart with labeled datasets and custom styling. ### Configuration Structure ```javascript const config = { type: 'bar', data: { labels: ['Month 1', 'Month 2', 'Month 3', 'Month 4', 'Month 5', 'Month 6', 'Month 7'], datasets: [{ label: 'My First Dataset', data: [65, 59, 80, 81, 56, 55, 40], 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: { y: { beginAtZero: true } } } }; ``` ### Configuration Properties - **type** (string) - Chart type, must be 'bar' - **data** (object) - Contains labels and datasets - **options** (object) - Chart options including scales configuration ``` -------------------------------- ### Install Chart.js with Bower Source: https://github.com/chartjs/chart.js/wiki/Getting Started Install Chart.js package manager using Bower. ```bash bower install chartjs --save ``` -------------------------------- ### Configure Mixed Chart with Setup and Config Blocks Source: https://github.com/chartjs/chart.js/blob/master/docs/charts/mixed.md Example of a scatter-based chart containing bar and line datasets with specific styling and modular configuration. ```javascript // const data = { labels: [ 'January', 'February', 'March', 'April' ], datasets: [{ type: 'bar', label: 'Bar Dataset', data: [10, 20, 30, 40], borderColor: 'rgb(255, 99, 132)', backgroundColor: 'rgba(255, 99, 132, 0.2)' }, { type: 'line', label: 'Line Dataset', data: [50, 50, 50, 50], fill: false, borderColor: 'rgb(54, 162, 235)' }] }; // // const config = { type: 'scatter', data: data, options: { scales: { y: { beginAtZero: true } } } }; // module.exports = { actions: [], config: config, }; ``` -------------------------------- ### Hide and Show Transitions Example Source: https://github.com/chartjs/chart.js/blob/master/docs/configuration/animations.md Example demonstrating how to configure transitions for showing and hiding chart elements. Shows how to animate x and y properties during visibility state changes. ```APIDOC ## Hide and Show Transitions ### Description Example of configuring transitions for showing and hiding chart elements with animated x and y properties. ### Configuration ```javascript const config = { type: 'line', data: data, options: { transitions: { show: { animations: { x: { from: 0 }, y: { from: 0 } } }, hide: { animations: { x: { to: 0 }, y: { to: 0 } } } } } }; ``` ### Behavior - **show transition**: Elements animate from x=0, y=0 to their final positions - **hide transition**: Elements animate from their current positions to x=0, y=0 ``` -------------------------------- ### Bar Chart Dataset Configuration Example Source: https://github.com/chartjs/chart.js/blob/master/docs/charts/bar.md Example dataset configuration demonstrating how to set bar dimensions, thickness, and data values for a bar chart. ```APIDOC ## Example Dataset Configuration ### Description Sample configuration showing how to customize bar dimensions and data. ### Configuration Example ```javascript data: { datasets: [{ barPercentage: 0.5, barThickness: 6, maxBarThickness: 8, minBarLength: 2, data: [10, 20, 30, 40, 50, 60, 70] }] }; ``` ### Property Descriptions - **barPercentage** (number) - Percentage of the bar group's container width that each bar should occupy. Default: 0.9 - **barThickness** (number|string) - The width of each bar in pixels. Can be set to 'flex' for automatic sizing - **maxBarThickness** (number) - Set this to ensure bars do not become too thick - **minBarLength** (number) - Set the minimum bar length, in pixel units - **data** (number[]) - Array of numeric values representing the bar heights ``` -------------------------------- ### Basic Title Configuration Example Source: https://github.com/chartjs/chart.js/blob/master/docs/configuration/title.md Simple example demonstrating how to enable and configure a basic chart title with custom text in Chart.js. ```APIDOC ## Basic Title Setup ### Description Enables a title on the chart with custom text. ### Code Example ```javascript const chart = new Chart(ctx, { type: 'line', data: data, options: { plugins: { title: { display: true, text: 'Custom Chart Title' } } } }); ``` ### Configuration Details - `display: true` - Enables the title display - `text: 'Custom Chart Title'` - Sets the title text to display ``` -------------------------------- ### Run documentation server locally Source: https://github.com/chartjs/chart.js/blob/master/docs/developers/contributing.md Start the Vuepress documentation server locally to preview documentation changes. ```bash > pnpm run docs:dev ``` -------------------------------- ### Dataset Parsing Configuration Example Source: https://github.com/chartjs/chart.js/blob/master/docs/general/data-structures.md Illustrates how to configure the `parsing` property for datasets to map data fields to chart axes using a JavaScript example. ```javascript const data = [{x: 'Jan', net: 100, cogs: 50, gm: 50}, {x: 'Feb', net: 120, cogs: 55, gm: 75}]; const cfg = { type: 'bar', data: { labels: ['Jan', 'Feb'], datasets: [{ label: 'Net sales', data: data, parsing: { yAxisKey: 'net' } }, { label: 'Cost of goods sold', data: data, parsing: { yAxisKey: 'cogs' } }, { label: 'Gross margin', data: data, parsing: { yAxisKey: 'gm' } }] } }; ``` -------------------------------- ### Install Chart.js development dependencies Source: https://github.com/chartjs/chart.js/blob/master/docs/developers/contributing.md Install local development dependencies using pnpm after cloning the Chart.js repository. ```bash > pnpm install ``` -------------------------------- ### Quick Start with Bundlers Source: https://github.com/chartjs/chart.js/blob/master/docs/getting-started/integration.md Import the auto package to include all controllers, elements, scales, and plugins automatically. This is the simplest method if bundle size optimization is not a priority. ```javascript import Chart from 'chart.js/auto'; ``` -------------------------------- ### Looping Tension Animation Example Source: https://github.com/chartjs/chart.js/blob/master/docs/configuration/animations.md Example demonstrating how to configure a looping animation on the tension property of a line chart. Shows how to use animation configuration with duration, easing, from/to values, and loop settings. ```APIDOC ## Looping Tension Animation ### Description Example of configuring a looping animation on the tension property of a line chart. ### Configuration ```javascript const config = { type: 'line', data: data, options: { animations: { tension: { duration: 1000, easing: 'linear', from: 1, to: 0, loop: true } }, scales: { y: { min: 0, max: 100 } } } }; ``` ### Parameters Explained - **duration**: `1000` - Animation takes 1 second - **easing**: `'linear'` - Uses linear easing function - **from**: `1` - Animation starts with tension value of 1 - **to**: `0` - Animation ends with tension value of 0 - **loop**: `true` - Animation repeats endlessly ``` -------------------------------- ### Install Chart.js using npm Source: https://github.com/chartjs/chart.js/blob/master/docs/getting-started/installation.md Use this command to install Chart.js as a dependency in your project via npm. ```sh npm install chart.js ``` -------------------------------- ### Install Chart.js Development Dependencies Source: https://github.com/chartjs/chart.js/wiki/Advanced-Usage Before building, install the project's local development dependencies and the global Gulp CLI tool. This prepares your environment for custom Chart.js builds. ```bash npm install npm install -g gulp ``` -------------------------------- ### Doughnut Chart Implementation with Actions Source: https://github.com/chartjs/chart.js/blob/master/docs/samples/other-charts/doughnut.md Complete setup for a doughnut chart including data configuration and action handlers for dynamic updates. Requires a 'Utils' utility for data generation. ```javascript // const actions = [ { name: 'Randomize', handler(chart) { chart.data.datasets.forEach(dataset => { dataset.data = Utils.numbers({count: chart.data.labels.length, min: 0, max: 100}); }); chart.update(); } }, { name: 'Add Dataset', handler(chart) { const data = chart.data; const newDataset = { label: 'Dataset ' + (data.datasets.length + 1), backgroundColor: [], data: [], }; for (let i = 0; i < data.labels.length; i++) { newDataset.data.push(Utils.numbers({count: 1, min: 0, max: 100})); const colorIndex = i % Object.keys(Utils.CHART_COLORS).length; newDataset.backgroundColor.push(Object.values(Utils.CHART_COLORS)[colorIndex]); } chart.data.datasets.push(newDataset); chart.update(); } }, { name: 'Add Data', handler(chart) { const data = chart.data; if (data.datasets.length > 0) { data.labels.push('data #' + (data.labels.length + 1)); for (let index = 0; index < data.datasets.length; ++index) { data.datasets[index].data.push(Utils.rand(0, 100)); } chart.update(); } } }, { name: 'Hide(0)', handler(chart) { chart.hide(0); } }, { name: 'Show(0)', handler(chart) { chart.show(0); } }, { name: 'Hide (0, 1)', handler(chart) { chart.hide(0, 1); } }, { name: 'Show (0, 1)', handler(chart) { chart.show(0, 1); } }, { name: 'Remove Dataset', handler(chart) { chart.data.datasets.pop(); chart.update(); } }, { name: 'Remove Data', handler(chart) { chart.data.labels.splice(-1, 1); // remove the label first chart.data.datasets.forEach(dataset => { dataset.data.pop(); }); chart.update(); } } ]; // // const DATA_COUNT = 5; const NUMBER_CFG = {count: DATA_COUNT, min: 0, max: 100}; const data = { labels: ['Red', 'Orange', 'Yellow', 'Green', 'Blue'], datasets: [ { label: 'Dataset 1', data: Utils.numbers(NUMBER_CFG), backgroundColor: Object.values(Utils.CHART_COLORS), } ] }; // // const config = { type: 'doughnut', data: data, options: { responsive: true, plugins: { legend: { position: 'top', }, title: { display: true, text: 'Chart.js Doughnut Chart' } } }, }; // module.exports = { actions: actions, config: config, }; ``` -------------------------------- ### Title with Custom Padding Example Source: https://github.com/chartjs/chart.js/blob/master/docs/configuration/title.md Example showing how to configure separate top and bottom padding for chart titles in Chart.js. ```APIDOC ## Title with Custom Padding ### Description Configures a title with separate top and bottom padding values. ### Code Example ```javascript const chart = new Chart(ctx, { type: 'line', data: data, options: { plugins: { title: { display: true, text: 'Custom Chart Title', padding: { top: 10, bottom: 30 } } } } }); ``` ### Configuration Details - `padding.top: 10` - Sets top padding to 10 pixels - `padding.bottom: 30` - Sets bottom padding to 30 pixels - Note: Only `top` and `bottom` padding values are implemented ``` -------------------------------- ### Complete Chart.js Polar Area Chart Example Source: https://github.com/chartjs/chart.js/blob/master/docs/samples/other-charts/polar-area.md This comprehensive example demonstrates how to initialize a Chart.js Polar Area chart, define its dataset and labels, configure chart options, and implement interactive actions to modify chart data dynamically. ```javascript // const actions = [ { name: 'Randomize', handler(chart) { chart.data.datasets.forEach(dataset => { dataset.data = Utils.numbers({count: chart.data.labels.length, min: 0, max: 100}); }); chart.update(); } }, { name: 'Add Data', handler(chart) { const data = chart.data; if (data.datasets.length > 0) { data.labels.push('data #' + (data.labels.length + 1)); for (let index = 0; index < data.datasets.length; ++index) { data.datasets[index].data.push(Utils.rand(0, 100)); } chart.update(); } } }, { name: 'Remove Data', handler(chart) { chart.data.labels.splice(-1, 1); // remove the label first chart.data.datasets.forEach(dataset => { dataset.data.pop(); }); chart.update(); } } ]; // // const DATA_COUNT = 5; const NUMBER_CFG = {count: DATA_COUNT, min: 0, max: 100}; const labels = ['Red', 'Orange', 'Yellow', 'Green', 'Blue']; const data = { labels: labels, datasets: [ { label: 'Dataset 1', data: Utils.numbers(NUMBER_CFG), backgroundColor: [ Utils.transparentize(Utils.CHART_COLORS.red, 0.5), Utils.transparentize(Utils.CHART_COLORS.orange, 0.5), Utils.transparentize(Utils.CHART_COLORS.yellow, 0.5), Utils.transparentize(Utils.CHART_COLORS.green, 0.5), Utils.transparentize(Utils.CHART_COLORS.blue, 0.5) ] } ] }; // // const config = { type: 'polarArea', data: data, options: { responsive: true, plugins: { legend: { position: 'top' }, title: { display: true, text: 'Chart.js Polar Area Chart' } } } }; // module.exports = { actions: actions, config: config }; ``` -------------------------------- ### HTML Setup for Chart.js Bubble Chart Source: https://github.com/chartjs/chart.js/blob/master/docs/getting-started/usage.md Uncomment these lines in `src/index.html` to include the canvas element and import the `dimensions.js` module for the bubble chart. ```html

``` -------------------------------- ### Radar Chart Stacked Setup and Configuration Source: https://github.com/chartjs/chart.js/blob/master/docs/samples/area/radar.md Complete setup for a stacked radar chart with six datasets using different fill modes and colors. Includes data generation utilities and interactive action handlers for randomizing data, toggling propagation, and smoothing. ```javascript // const inputs = { min: 8, max: 16, count: 8, decimals: 2, continuity: 1 }; const generateLabels = () => { return Utils.months({count: inputs.count}); }; const generateData = () => { const values = Utils.numbers(inputs); inputs.from = values; return values; }; const labels = Utils.months({count: 8}); const data = { labels: generateLabels(), datasets: [ { label: 'D0', data: generateData(), borderColor: Utils.CHART_COLORS.red, backgroundColor: Utils.transparentize(Utils.CHART_COLORS.red), }, { label: 'D1', data: generateData(), borderColor: Utils.CHART_COLORS.orange, hidden: true, backgroundColor: Utils.transparentize(Utils.CHART_COLORS.orange), fill: '-1' }, { label: 'D2', data: generateData(), borderColor: Utils.CHART_COLORS.yellow, backgroundColor: Utils.transparentize(Utils.CHART_COLORS.yellow), fill: 1 }, { label: 'D3', data: generateData(), borderColor: Utils.CHART_COLORS.green, backgroundColor: Utils.transparentize(Utils.CHART_COLORS.green), fill: false }, { label: 'D4', data: generateData(), borderColor: Utils.CHART_COLORS.blue, backgroundColor: Utils.transparentize(Utils.CHART_COLORS.blue), fill: '-1' }, { label: 'D5', data: generateData(), borderColor: Utils.CHART_COLORS.purple, backgroundColor: Utils.transparentize(Utils.CHART_COLORS.purple), fill: '-1' }, { label: 'D6', data: generateData(), borderColor: Utils.CHART_COLORS.grey, backgroundColor: Utils.transparentize(Utils.CHART_COLORS.grey), fill: {value: 85} } ] }; // ``` ```javascript // let smooth = false; let propagate = false; const actions = [ { name: 'Randomize', handler(chart) { inputs.from = []; chart.data.datasets.forEach(dataset => { dataset.data = generateData(); }); chart.update(); } }, { name: 'Propagate', handler(chart) { propagate = !propagate; chart.options.plugins.filler.propagate = propagate; chart.update(); } }, { name: 'Smooth', handler(chart) { smooth = !smooth; chart.options.elements.line.tension = smooth ? 0.4 : 0; chart.update(); } } ]; // ``` ```javascript // const config = { type: 'radar', data: data, options: { plugins: { filler: { propagate: false }, 'samples-filler-analyser': { target: 'chart-analyser' } }, interaction: { intersect: false } } }; // ``` ```javascript module.exports = { actions: actions, config: config }; ``` -------------------------------- ### Basic Line Chart Configuration Source: https://github.com/chartjs/chart.js/blob/master/docs/charts/line.md This snippet demonstrates the basic setup for a Chart.js line chart, including data definition with labels and a single dataset, and the chart configuration object. ```javascript // const labels = Utils.months({count: 7}); const data = { labels: labels, datasets: [{ label: 'My First Dataset', data: [65, 59, 80, 81, 56, 55, 40], fill: false, borderColor: 'rgb(75, 192, 192)', tension: 0.1 }] }; // // const config = { type: 'line', data: data, }; // module.exports = { actions: [], config: config, }; ``` -------------------------------- ### Chart.js Bar Dataset Property Configuration Source: https://github.com/chartjs/chart.js/blob/master/docs/charts/bar.md This example shows how to configure specific properties for a bar chart dataset, such as `barPercentage`, `barThickness`, `maxBarThickness`, and `minBarLength`. ```javascript data: { datasets: [{ barPercentage: 0.5, barThickness: 6, maxBarThickness: 8, minBarLength: 2, data: [10, 20, 30, 40, 50, 60, 70] }] }; ``` -------------------------------- ### Chart.js Bubble Chart Data Setup Source: https://github.com/chartjs/chart.js/blob/master/docs/samples/other-charts/bubble.md Initializes the dataset configuration for a Chart.js bubble chart, including data points generated by Utils.bubbles and styling properties. ```javascript const DATA_COUNT = 7; const NUMBER_CFG = {count: DATA_COUNT, rmin: 5, rmax: 15, min: 0, max: 100}; const data = { datasets: [ { label: 'Dataset 1', data: Utils.bubbles(NUMBER_CFG), borderColor: Utils.CHART_COLORS.red, backgroundColor: Utils.transparentize(Utils.CHART_COLORS.red, 0.5), }, { label: 'Dataset 2', data: Utils.bubbles(NUMBER_CFG), borderColor: Utils.CHART_COLORS.orange, backgroundColor: Utils.transparentize(Utils.CHART_COLORS.orange, 0.5), } ] }; ``` -------------------------------- ### Basic Bubble Chart Configuration Source: https://github.com/chartjs/chart.js/blob/master/docs/charts/bubble.md Standard setup for a bubble chart including data points with x, y, and r values, and the main configuration object. ```javascript // const data = { datasets: [{ label: 'First Dataset', data: [{ x: 20, y: 30, r: 15 }, { x: 40, y: 10, r: 10 }], backgroundColor: 'rgb(255, 99, 132)' }] }; // // const config = { type: 'bubble', data: data, options: {} }; // module.exports = { actions: [], config: config, }; ``` -------------------------------- ### Horizontal Bar Chart Implementation Source: https://github.com/chartjs/chart.js/blob/master/docs/charts/bar.md Configure a bar chart to be horizontal by setting indexAxis to 'y'. This example includes the full setup for labels, datasets, and styling. ```javascript // const labels = Utils.months({count: 7}); const data = { labels: labels, datasets: [{ axis: 'y', 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 }] }; // // const config = { type: 'bar', data, options: { indexAxis: 'y', } }; // module.exports = { actions: [], config: config, }; ``` -------------------------------- ### Configuring Min and Max for Category Axis Source: https://github.com/chartjs/chart.js/blob/master/docs/axes/cartesian/category.md The min and max properties accept either a string matching a label or a numeric index. This example restricts the x-axis to display labels starting from 'March'. ```javascript 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: { x: { min: 'March' } } } }); ``` -------------------------------- ### Radar Chart Configuration with Null Data Points Source: https://github.com/chartjs/chart.js/blob/master/docs/samples/other-charts/radar-skip-points.md Use null values in the data array to create gaps in radar chart lines. This setup shows how to handle missing points at the start, middle, and end of datasets. ```javascript // const actions = [ { name: 'Randomize', handler(chart) { chart.data.datasets.forEach((dataset, i) => { const data = Utils.numbers({count: chart.data.labels.length, min: 0, max: 100}); if (i === 0) { data[0] = null; } else if (i === 1) { data[Number.parseInt(data.length / 2, 10)] = null; } else { data[data.length - 1] = null; } dataset.data = data; }); chart.update(); } } ]; // // const DATA_COUNT = 7; const NUMBER_CFG = {count: DATA_COUNT, min: 0, max: 100}; const labels = Utils.months({count: 7}); const dataFirstSkip = Utils.numbers(NUMBER_CFG); const dataMiddleSkip = Utils.numbers(NUMBER_CFG); const dataLastSkip = Utils.numbers(NUMBER_CFG); dataFirstSkip[0] = null; dataMiddleSkip[Number.parseInt(dataMiddleSkip.length / 2, 10)] = null; dataLastSkip[dataLastSkip.length - 1] = null; const data = { labels: labels, datasets: [ { label: 'Skip first dataset', data: dataFirstSkip, borderColor: Utils.CHART_COLORS.red, backgroundColor: Utils.transparentize(Utils.CHART_COLORS.red, 0.5), }, { label: 'Skip mid dataset', data: dataMiddleSkip, borderColor: Utils.CHART_COLORS.blue, backgroundColor: Utils.transparentize(Utils.CHART_COLORS.blue, 0.5), }, { label: 'Skip last dataset', data: dataLastSkip, borderColor: Utils.CHART_COLORS.green, backgroundColor: Utils.transparentize(Utils.CHART_COLORS.green, 0.5), } ] }; // // const config = { type: 'radar', data: data, options: { responsive: true, plugins: { title: { display: true, text: 'Chart.js Radar Skip Points Chart' } } }, }; // module.exports = { actions: actions, config: config }; ``` -------------------------------- ### Chart Data Setup with Two Datasets Source: https://github.com/chartjs/chart.js/blob/master/docs/samples/animations/drop.md Initializes chart data with 7 months of labels and two datasets (red and blue) with random values between -100 and 100. The first dataset includes a 2-second animation with 500ms delay. ```javascript const DATA_COUNT = 7; const NUMBER_CFG = {count: DATA_COUNT, min: -100, max: 100}; const labels = Utils.months({count: 7}); const data = { labels: labels, datasets: [ { label: 'Dataset 1', animations: { y: { duration: 2000, delay: 500 } }, data: Utils.numbers(NUMBER_CFG), borderColor: Utils.CHART_COLORS.red, backgroundColor: Utils.transparentize(Utils.CHART_COLORS.red, 0.5), fill: 1, tension: 0.5 }, { label: 'Dataset 2', data: Utils.numbers(NUMBER_CFG), borderColor: Utils.CHART_COLORS.blue, backgroundColor: Utils.transparentize(Utils.CHART_COLORS.blue, 0.5), } ] }; ``` -------------------------------- ### Implement Custom HTML Tooltip in Chart.js Source: https://github.com/chartjs/chart.js/blob/master/docs/samples/tooltip/html.md This comprehensive example demonstrates how to create and configure an external HTML tooltip for a Chart.js line chart. It includes the logic for dynamically generating the tooltip's HTML structure and styling, as well as the chart setup and configuration to enable the custom tooltip handler. ```javascript // const getOrCreateTooltip = (chart) => { let tooltipEl = chart.canvas.parentNode.querySelector('div'); if (!tooltipEl) { tooltipEl = document.createElement('div'); tooltipEl.style.background = 'rgba(0, 0, 0, 0.7)'; tooltipEl.style.borderRadius = '3px'; tooltipEl.style.color = 'white'; tooltipEl.style.opacity = 1; tooltipEl.style.pointerEvents = 'none'; tooltipEl.style.position = 'absolute'; tooltipEl.style.transform = 'translate(-50%, 0)'; tooltipEl.style.transition = 'all .1s ease'; const table = document.createElement('table'); table.style.margin = '0px'; tooltipEl.appendChild(table); chart.canvas.parentNode.appendChild(tooltipEl); } return tooltipEl; }; const externalTooltipHandler = (context) => { // Tooltip Element const {chart, tooltip} = context; const tooltipEl = getOrCreateTooltip(chart); // Hide if no tooltip if (tooltip.opacity === 0) { tooltipEl.style.opacity = 0; return; } // Set Text if (tooltip.body) { const titleLines = tooltip.title || []; const bodyLines = tooltip.body.map(b => b.lines); const tableHead = document.createElement('thead'); titleLines.forEach(title => { const tr = document.createElement('tr'); tr.style.borderWidth = 0; const th = document.createElement('th'); th.style.borderWidth = 0; const text = document.createTextNode(title); th.appendChild(text); tr.appendChild(th); tableHead.appendChild(tr); }); const tableBody = document.createElement('tbody'); bodyLines.forEach((body, i) => { const colors = tooltip.labelColors[i]; const span = document.createElement('span'); span.style.background = colors.backgroundColor; span.style.borderColor = colors.borderColor; span.style.borderWidth = '2px'; span.style.marginRight = '10px'; span.style.height = '10px'; span.style.width = '10px'; span.style.display = 'inline-block'; const tr = document.createElement('tr'); tr.style.backgroundColor = 'inherit'; tr.style.borderWidth = 0; const td = document.createElement('td'); td.style.borderWidth = 0; const text = document.createTextNode(body); td.appendChild(span); td.appendChild(text); tr.appendChild(td); tableBody.appendChild(tr); }); const tableRoot = tooltipEl.querySelector('table'); // Remove old children while (tableRoot.firstChild) { tableRoot.firstChild.remove(); } // Add new children tableRoot.appendChild(tableHead); tableRoot.appendChild(tableBody); } const {offsetLeft: positionX, offsetTop: positionY} = chart.canvas; // Display, position, and set styles for font tooltipEl.style.opacity = 1; tooltipEl.style.left = positionX + tooltip.caretX + 'px'; tooltipEl.style.top = positionY + tooltip.caretY + 'px'; tooltipEl.style.font = tooltip.options.bodyFont.string; tooltipEl.style.padding = tooltip.options.padding + 'px ' + tooltip.options.padding + 'px'; }; // // const DATA_COUNT = 7; const NUMBER_CFG = {count: DATA_COUNT, min: -100, max: 100, decimals: 0}; const data = { labels: Utils.months({count: DATA_COUNT}), datasets: [ { label: 'Dataset 1', data: Utils.numbers(NUMBER_CFG), fill: false, borderColor: Utils.CHART_COLORS.red, backgroundColor: Utils.transparentize(Utils.CHART_COLORS.red, 0.5), }, { label: 'Dataset 2', data: Utils.numbers(NUMBER_CFG), fill: false, borderColor: Utils.CHART_COLORS.blue, backgroundColor: Utils.transparentize(Utils.CHART_COLORS.blue, 0.5), }, ] }; // // const config = { type: 'line', data: data, options: { interaction: { mode: 'index', intersect: false, }, plugins: { title: { display: true, text: 'Chart.js Line Chart - External Tooltips' }, tooltip: { enabled: false, position: 'nearest', external: externalTooltipHandler } } } }; // module.exports = { actions: [], config: config, }; ``` -------------------------------- ### Set Up Chart Data with Multiple Datasets Source: https://github.com/chartjs/chart.js/blob/master/docs/samples/animations/delay.md Initialize chart data with labels and three datasets using utility functions to generate random values. Each dataset is assigned a distinct background color. ```javascript const DATA_COUNT = 7; const NUMBER_CFG = {count: DATA_COUNT, min: -100, max: 100}; const labels = Utils.months({count: 7}); const data = { labels: labels, datasets: [ { label: 'Dataset 1', data: Utils.numbers(NUMBER_CFG), backgroundColor: Utils.CHART_COLORS.red, }, { label: 'Dataset 2', data: Utils.numbers(NUMBER_CFG), backgroundColor: Utils.CHART_COLORS.blue, }, { label: 'Dataset 3', data: Utils.numbers(NUMBER_CFG), backgroundColor: Utils.CHART_COLORS.green, }, ] }; ``` -------------------------------- ### Chart.js Line Chart with drawTime Configuration and Interactive Actions Source: https://github.com/chartjs/chart.js/blob/master/docs/samples/area/line-drawtime.md This example sets up a Chart.js line chart with two datasets, demonstrating various `drawTime` options for the filler plugin. It includes interactive actions to change `drawTime`, randomize data, and toggle line tension. ```javascript // const inputs = { min: -100, max: 100, count: 8, decimals: 2, continuity: 1 }; const generateLabels = () => { return Utils.months({count: inputs.count}); }; Utils.srand(3); const generateData = () => (Utils.numbers(inputs)); // // const data = { labels: generateLabels(), datasets: [ { label: 'Dataset 1', data: generateData(), borderColor: Utils.CHART_COLORS.red, backgroundColor: Utils.CHART_COLORS.red, fill: true }, { label: 'Dataset 2', data: generateData(), borderColor: Utils.CHART_COLORS.blue, backgroundColor: Utils.transparentize(Utils.CHART_COLORS.blue), fill: true } ] }; // // let smooth = false; const actions = [ { name: 'drawTime: beforeDatasetDraw (default)', handler: (chart) => { chart.options.plugins.filler.drawTime = 'beforeDatasetDraw'; chart.update(); } }, { name: 'drawTime: beforeDatasetsDraw', handler: (chart) => { chart.options.plugins.filler.drawTime = 'beforeDatasetsDraw'; chart.update(); } }, { name: 'drawTime: beforeDraw', handler: (chart) => { chart.options.plugins.filler.drawTime = 'beforeDraw'; chart.update(); } }, { name: 'Randomize', handler(chart) { chart.data.datasets.forEach(dataset => { dataset.data = generateData(); }); chart.update(); } }, { name: 'Smooth', handler(chart) { smooth = !smooth; chart.options.elements.line.tension = smooth ? 0.4 : 0; chart.update(); } } ]; // // const config = { type: 'line', data: data, options: { plugins: { filler: { propagate: false, }, title: { display: true, text: (ctx) => 'drawTime: ' + ctx.chart.options.plugins.filler.drawTime } }, pointBackgroundColor: '#fff', radius: 10, interaction: { intersect: false, } } }; // module.exports = { actions: actions, config: config, }; ``` -------------------------------- ### Setup Data and Labels for Time Scale Combo Chart Source: https://github.com/chartjs/chart.js/blob/master/docs/samples/scales/time-combo.md Initializes chart data with time-based labels and three datasets (two bar, one line) with random values. Requires Utils helper functions for date generation and color utilities. ```javascript const DATA_COUNT = 7; const NUMBER_CFG = {count: DATA_COUNT, min: 0, max: 100}; const labels = []; for (let i = 0; i < DATA_COUNT; ++i) { labels.push(Utils.newDate(i)); } const data = { labels: labels, datasets: [{ type: 'bar', label: 'Dataset 1', backgroundColor: Utils.transparentize(Utils.CHART_COLORS.red, 0.5), borderColor: Utils.CHART_COLORS.red, data: Utils.numbers(NUMBER_CFG), }, { type: 'bar', label: 'Dataset 2', backgroundColor: Utils.transparentize(Utils.CHART_COLORS.blue, 0.5), borderColor: Utils.CHART_COLORS.blue, data: Utils.numbers(NUMBER_CFG), }, { type: 'line', label: 'Dataset 3', backgroundColor: Utils.transparentize(Utils.CHART_COLORS.green, 0.5), borderColor: Utils.CHART_COLORS.green, fill: false, data: Utils.numbers(NUMBER_CFG), }] }; ``` -------------------------------- ### Build output comparison Source: https://github.com/chartjs/chart.js/blob/master/docs/getting-started/usage.md Comparison of build logs showing bundle size before and after tree-shaking optimizations. ```bash % yarn build yarn run v1.22.17 $ parcel build src/index.html ✨ Built in 88ms dist/index.html 381 B 164ms dist/index.74a47636.js 265.48 KB 1.25s dist/index.ba0c2e17.js 881 B 63ms ✨ Done in 0.51s. ``` ```bash % yarn build yarn run v1.22.17 $ parcel build src/index.html ✨ Built in 88ms dist/index.html 381 B 176ms dist/index.5888047.js 208.66 KB 1.23s dist/index.dcb2e865.js 932 B 58ms ✨ Done in 0.51s. ``` -------------------------------- ### Initialize a Line Chart in Chart.js Source: https://github.com/chartjs/chart.js/wiki/Advanced-Usage Creates a new line chart instance using the provided context and data. ```javascript // For example: var myLineChart = new Chart(ctx).Line(data); ``` -------------------------------- ### Chart.js Animation Progress Callback Example Source: https://github.com/chartjs/chart.js/blob/master/docs/configuration/animations.md This example uses the `onProgress` callback to update a progress bar during the chart's animation, showing the animation's completion percentage. ```javascript const chart = new Chart(ctx, { type: 'line', data: data, options: { animation: { onProgress: function(animation) { progress.value = animation.currentStep / animation.numSteps; } } } }); ``` -------------------------------- ### Chart Data Setup with Multi-line Labels Source: https://github.com/chartjs/chart.js/blob/master/docs/samples/scale-options/ticks.md Configures sample data for a line chart with two datasets and multi-line labels (arrays) for certain months. Uses utility functions for generating random data and colors. ```javascript const DATA_COUNT = 12; const NUMBER_CFG = {count: DATA_COUNT, min: 0, max: 100}; const data = { labels: [['June', '2015'], 'July', 'August', 'September', 'October', 'November', 'December', ['January', '2016'], 'February', 'March', 'April', 'May'], datasets: [ { label: 'Dataset 1', data: Utils.numbers(NUMBER_CFG), fill: false, borderColor: Utils.CHART_COLORS.red, backgroundColor: Utils.transparentize(Utils.CHART_COLORS.red, 0.5), }, { label: 'Dataset 2', data: Utils.numbers(NUMBER_CFG), fill: false, borderColor: Utils.CHART_COLORS.blue, backgroundColor: Utils.transparentize(Utils.CHART_COLORS.blue, 0.5), } ] }; ``` -------------------------------- ### Set Up Line Chart Data Source: https://github.com/chartjs/chart.js/blob/master/docs/samples/tooltip/position.md Configure sample data for a line chart with two datasets using utility functions for labels and random numbers. Includes styling with colors and transparency. ```javascript const DATA_COUNT = 7; const NUMBER_CFG = {count: DATA_COUNT, min: -100, max: 100}; const data = { labels: Utils.months({count: DATA_COUNT}), datasets: [ { label: 'Dataset 1', data: Utils.numbers(NUMBER_CFG), fill: false, borderColor: Utils.CHART_COLORS.red, backgroundColor: Utils.transparentize(Utils.CHART_COLORS.red, 0.5), }, { label: 'Dataset 2', data: Utils.numbers(NUMBER_CFG), fill: false, borderColor: Utils.CHART_COLORS.blue, backgroundColor: Utils.transparentize(Utils.CHART_COLORS.blue, 0.5), }, ] }; ``` -------------------------------- ### GET /chartInstance.getSegmentsAtEvent Source: https://github.com/chartjs/chart.js/wiki/Pie-Doughnut-Charts Retrieves the chart segments located at the coordinates of a specific event, such as a mouse click. ```APIDOC ## GET /chartInstance.getSegmentsAtEvent ### Description Returns the segment elements that are at the same position as the provided event or jQuery event. ### Method GET ### Endpoint chartInstance.getSegmentsAtEvent(event) ### Parameters #### Path Parameters - **event** (Event) - Required - The browser event or jQuery event object. ### Request Example canvas.onclick = function(evt){ var activePoints = myDoughnutChart.getSegmentsAtEvent(evt); }; ### Response #### Success Response (200) - **segments** (array) - An array of segment objects found at the event position. ``` -------------------------------- ### Chart.js Line Chart Data Setup Source: https://github.com/chartjs/chart.js/blob/master/docs/samples/advanced/progress-bar.md Initialize chart data with two datasets containing random values. Includes configuration for labels, dataset colors, and transparency settings using utility functions. ```javascript const initProgress = document.getElementById('initialProgress'); const progress = document.getElementById('animationProgress'); const DATA_COUNT = 7; const NUMBER_CFG = {count: DATA_COUNT, min: -100, max: 100}; const labels = Utils.months({count: 7}); const data = { labels: labels, datasets: [ { label: 'Dataset 1', data: Utils.numbers(NUMBER_CFG), borderColor: Utils.CHART_COLORS.red, backgroundColor: Utils.transparentize(Utils.CHART_COLORS.red, 0.5), }, { label: 'Dataset 2', data: Utils.numbers(NUMBER_CFG), borderColor: Utils.CHART_COLORS.blue, backgroundColor: Utils.transparentize(Utils.CHART_COLORS.blue, 0.5), } ] }; ``` -------------------------------- ### Overriding Default Options Source: https://github.com/chartjs/chart.js/wiki/Polar-Area-Chart Example of how to override default Polar Area chart options for a specific instance. ```APIDOC ## Overriding Default Options ### Description To override default options for a specific Polar Area chart instance, pass an options object as the second argument to the `PolarArea` method. ### Example ```javascript new Chart(ctx).PolarArea(data, { segmentStrokeColor: "#000000" }); ``` This example creates a Polar Area chart with a black segment stroke, overriding the default white stroke. ```