Chart.js
repository·master·Indexed 13 days ago
https://github.com/chartjs/chart.jsA flexible JavaScript library for creating HTML5 data visualizations and charts using the canvas element. Version 4.5.1 provides a wide range of configurable chart types, including linear, logarithmic, category, time, and timeseries Cartesian axes.
What's inside Chart.js
- Chart.js is a simple yet flexible JavaScript library designed for designers and developers to create charts. It provides a wide range of chart types and is highly configurable. The current documentation and library version is v4.
Core features and customization of Chart.js
masterChart.js provides several key capabilities for data visualization:
- Built-in Chart Types: A variety of standard charts (e.g., area charts) are available out of the box.
- Mixed Charts: You can combine multiple chart types into a single visualization on the same canvas.
- Plugins: Extend functionality using custom or community-maintained plugins for features like annotations, zooming, or drag-and-drop.
- Customization: Highly configurable via a sound default configuration and extensive options for styling and animations.
Overview of Cartesian Axes
masterCartesian Axes are used for line, bar, and bubble charts. Chart.js includes five default Cartesian axis types:
linearlogarithmiccategorytimetimeseries
Use multiple datasets in a single chart
masterChart.js supports multiple datasets for most chart types. You can provide an array of objects to the
datasetsproperty. Each dataset is plotted independently and can be toggled via the legend.data: { labels: ['Jan', 'Feb', 'Mar'], datasets: [ { label: 'Dataset 1', data: [10, 20, 30] }, { label: 'Dataset 2', data: [5, 15, 25] } ] }Configure Chart.js Interaction Modes
masterInteraction modes determine how Chart.js detects elements during hover or touch events (e.g., for tooltips). You can configure these via the
options.interactionobject.Key properties include:
mode: Defines the algorithm used to find elements. Common values include'index','dataset','point','nearest','x', and'y'.axis: Determines the axis used for interaction (e.g.,'x','y', or'xy').intersect: A boolean that determines whether the interaction should only trigger when the cursor is directly intersecting an element (set tofalseto trigger based on proximity/axis alignment).
To apply changes dynamically, update the
chart.options.interactionobject and callchart.update().const config = { type: 'line', data: data, options: { interaction: { intersect: false, mode: 'index', axis: 'x' } } }; // To update dynamically: chart.options.interaction.mode = 'nearest'; chart.update();Configure element-level styling for all datasets
masterWhile dataset-specific settings allow for individual styling, you can use Element Configuration to style all objects of a specific type (e.g., all bars or all points) the same way. This is useful for applying a uniform border color across all datasets while allowing individual fill colors.
Element options can be configured in two ways:
- Per Chart: Using the
options.elements.<type>namespace in your chart configuration. - Globally: Modifying
Chart.defaults.elements.<type>to affect every chart instance in your application.
Supported element types are:
arc,line,point, andbar.// Set the border width of all bar charts globally Chart.defaults.elements.bar.borderWidth = 2;- Per Chart: Using the
Format data for Scatter Charts
masterUnlike line charts which support multiple data formats, scatter charts strictly require data to be provided in a point format. Each data point must be an object containing
xandykeys. Because the x-axis is alinearscale, the values forxandymust be numbers or strings that are parsable as numbers.data: [{ x: 10, y: 20 }, { x: 15, y: 10 }]Configure Bubble Chart data structure
masterBubble chart datasets require a
dataarray where each element is an object representing a point. Each point must contain the following properties:x: The horizontal axis value.y: The vertical axis value.r: The bubble radius in pixels.
Note: The
rproperty is not scaled by the chart; it represents the raw pixel radius used to draw the bubble on the canvas.{ x: number, y: number, r: number }Use scriptable options for dynamic styling
masterChart.js allows you to pass a function to many configuration options (like
borderColor,backgroundColor,borderWidth, etc.). These are called Scriptable Options.When a function is provided, Chart.js calls it for every element in the dataset. The function receives a
contextobject which contains:chart: The chart instance.datasetIndex: The index of the dataset.dataIndex: The index of the specific data point.raw: The raw data value.parsed: The parsed data value.
This is the recommended way to implement gradients or colors that change based on the data value or the chart's dimensions.
Data Structure for Polar Area Charts
masterA Polar Area chart requires a
dataobject with:datasets: An array of objects, where each object contains adataarray of numbers. Chart.js calculates the relative proportions based on these values.labels: An array of strings. These labels are used in the legend and in tooltips when hovering over specific arcs.
data = { datasets: [{ data: [10, 20, 30] }], labels: [ 'Red', 'Yellow', 'Blue' ] };Create and use custom plugins
masterPlugins allow you to extend Chart.js functionality by hooking into the chart lifecycle. A plugin is an object with a
name(orid) and callback functions (e.g.,beforeDraw,afterDraw).To use a plugin:
- Define the plugin object.
- Pass it to the
pluginsarray in the Chart constructor, OR - Configure its specific options under
options.plugins.[pluginId].
const myPlugin = { id: 'myCustomPlugin', beforeDraw(chart, args, options) { // Access canvas context via chart.ctx // Use options provided in the chart config } }; new Chart(ctx, { plugins: [myPlugin], options: { plugins: { myCustomPlugin: { borderColor: 'red' } } } });Use scriptable options for animations
masterChart.js supports Scriptable Options, allowing you to define configuration values as functions. This is particularly useful for animations where the
delay,duration, or starting position (from) depends on the data context (ctx).When using a function for an animation property, the
ctx(context) object provides access to:ctx.index: The index of the current element.ctx.datasetIndex: The index of the dataset.ctx.type: The type of animation (e.g.,'data').ctx.chart: The chart instance.ctx.chart.scales: Access to scale methods likegetPixelForValue.ctx.chart.getDatasetMeta(index): Access to metadata for a specific dataset, useful for retrieving the properties of previous elements.