This commit is contained in:
Xes
2025-08-14 22:44:47 +02:00
parent 8ce45119b6
commit 791cb748ab
39112 changed files with 975901 additions and 0 deletions

View File

@@ -0,0 +1,65 @@
# Chart.js
[![slack](https://img.shields.io/badge/slack-chartjs-blue.svg?style=flat-square&maxAge=3600)](https://chartjs-slack.herokuapp.com/)
## Installation
You can download the latest version of Chart.js from the [GitHub releases](https://github.com/chartjs/Chart.js/releases/latest) or use a [Chart.js CDN](https://www.jsdelivr.com/package/npm/chart.js). Detailed installation instructions can be found on the [installation](./getting-started/installation.md) 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 `<canvas>` 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](./getting-started/usage.md).
```html
<canvas id="myChart" width="400" height="400"></canvas>
<script>
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
}
}]
}
}
});
</script>
```
## Contributing
Before submitting an issue or a pull request to the project, please take a moment to look over the [contributing guidelines](https://github.com/chartjs/Chart.js/blob/master/docs/developers/contributing.md) first.
For support using Chart.js, please post questions with the [`chartjs` tag on Stack Overflow](https://stackoverflow.com/questions/tagged/chartjs).
## License
Chart.js is available under the [MIT license](https://opensource.org/licenses/MIT).

View File

@@ -0,0 +1,57 @@
# Summary
* [Chart.js](https://www.chartjs.org)
* [Introduction](README.md)
* [Getting Started](getting-started/README.md)
* [Installation](getting-started/installation.md)
* [Integration](getting-started/integration.md)
* [Usage](getting-started/usage.md)
* [General](general/README.md)
* [Accessibility](general/accessibility.md)
* [Responsive](general/responsive.md)
* [Pixel Ratio](general/device-pixel-ratio.md)
* [Interactions](general/interactions/README.md)
* [Events](general/interactions/events.md)
* [Modes](general/interactions/modes.md)
* [Options](general/options.md)
* [Colors](general/colors.md)
* [Fonts](general/fonts.md)
* [Performance](general/performance.md)
* [Configuration](configuration/README.md)
* [Animations](configuration/animations.md)
* [Layout](configuration/layout.md)
* [Legend](configuration/legend.md)
* [Title](configuration/title.md)
* [Tooltip](configuration/tooltip.md)
* [Elements](configuration/elements.md)
* [Charts](charts/README.md)
* [Line](charts/line.md)
* [Bar](charts/bar.md)
* [Radar](charts/radar.md)
* [Doughnut & Pie](charts/doughnut.md)
* [Polar Area](charts/polar.md)
* [Bubble](charts/bubble.md)
* [Scatter](charts/scatter.md)
* [Area](charts/area.md)
* [Mixed](charts/mixed.md)
* [Axes](axes/README.md)
* [Cartesian](axes/cartesian/README.md)
* [Category](axes/cartesian/category.md)
* [Linear](axes/cartesian/linear.md)
* [Logarithmic](axes/cartesian/logarithmic.md)
* [Time](axes/cartesian/time.md)
* [Radial](axes/radial/README.md)
* [Linear](axes/radial/linear.md)
* [Labelling](axes/labelling.md)
* [Styling](axes/styling.md)
* [Developers](developers/README.md)
* [Chart.js API](developers/api.md)
* [Updating Charts](developers/updates.md)
* [Plugins](developers/plugins.md)
* [New Charts](developers/charts.md)
* [New Axes](developers/axes.md)
* [Contributing](developers/contributing.md)
* [Additional Notes](notes/README.md)
* [Comparison Table](notes/comparison.md)
* [Popular Extensions](notes/extensions.md)
* [License](notes/license.md)

View File

@@ -0,0 +1,58 @@
# Axes
Axes are an integral part of a chart. They are used to determine how data maps to a pixel value on the chart. In a cartesian chart, there is 1 or more X axis and 1 or more Y axis to map points onto the 2 dimensional canvas. These axes are know as ['cartesian axes'](./cartesian/README.md#cartesian-axes).
In a radial chart, such as a radar chart or a polar area chart, there is a single axis that maps points in the angular and radial directions. These are known as ['radial axes'](./radial/README.md#radial-axes).
Scales in Chart.js >v2.0 are significantly more powerful, but also different than those of v1.0.
* Multiple X & Y axes are supported.
* A built-in label auto-skip feature detects would-be overlapping ticks and labels and removes every nth label to keep things displaying normally.
* Scale titles are supported.
* New scale types can be extended without writing an entirely new chart type.
## Common Configuration
The following properties are common to all axes provided by Chart.js.
| Name | Type | Default | Description
| ---- | ---- | ------- | -----------
| `display` | <code>boolean&#124;string</code> | `true` | Controls the axis global visibility (visible when `true`, hidden when `false`). When `display: 'auto'`, the axis is visible only if at least one associated dataset is visible.
| `callbacks` | `object` | | Callback functions to hook into the axis lifecycle. [more...](#callbacks)
| `weight` | `number` | `0` | The weight used to sort the axis. Higher weights are further away from the chart area.
### Callbacks
There are a number of config callbacks that can be used to change parameters in the scale at different points in the update process.
| Name | Arguments | Description
| ---- | --------- | -----------
| `beforeUpdate` | `axis` | Callback called before the update process starts.
| `beforeSetDimensions` | `axis` | Callback that runs before dimensions are set.
| `afterSetDimensions` | `axis` | Callback that runs after dimensions are set.
| `beforeDataLimits` | `axis` | Callback that runs before data limits are determined.
| `afterDataLimits` | `axis` | Callback that runs after data limits are determined.
| `beforeBuildTicks` | `axis` | Callback that runs before ticks are created.
| `afterBuildTicks` | `axis`, `ticks` | Callback that runs after ticks are created. Useful for filtering ticks. Should return the filtered ticks.
| `beforeTickToLabelConversion` | `axis` | Callback that runs before ticks are converted into strings.
| `afterTickToLabelConversion` | `axis` | Callback that runs after ticks are converted into strings.
| `beforeCalculateTickRotation` | `axis` | Callback that runs before tick rotation is determined.
| `afterCalculateTickRotation` | `axis` | Callback that runs after tick rotation is determined.
| `beforeFit` | `axis` | Callback that runs before the scale fits to the canvas.
| `afterFit` | `axis` | Callback that runs after the scale fits to the canvas.
| `afterUpdate` | `axis` | Callback that runs at the end of the update process.
### Updating Axis Defaults
The default configuration for a scale can be easily changed using the scale service. All you need to do is to pass in a partial configuration that will be merged with the current scale default configuration to form the new default.
For example, to set the minimum value of 0 for all linear scales, you would do the following. Any linear scales created after this time would now have a minimum of 0.
```javascript
Chart.scaleService.updateScaleDefaults('linear', {
ticks: {
min: 0
}
});
```
## Creating New Axes
To create a new axis, see the [developer docs](../developers/axes.md).

View File

@@ -0,0 +1,108 @@
# Cartesian Axes
Axes that follow a cartesian grid are known as 'Cartesian Axes'. Cartesian axes are used for line, bar, and bubble charts. Four cartesian axes are included in Chart.js by default.
* [linear](./linear.md#linear-cartesian-axis)
* [logarithmic](./logarithmic.md#logarithmic-cartesian-axis)
* [category](./category.md#category-cartesian-axis)
* [time](./time.md#time-cartesian-axis)
## Common Configuration
All of the included cartesian axes support a number of common options.
| Name | Type | Default | Description
| ---- | ---- | ------- | -----------
| `type` | `string` | | Type of scale being employed. Custom scales can be created and registered with a string key. This allows changing the type of an axis for a chart.
| `position` | `string` | | Position of the axis in the chart. Possible values are: `'top'`, `'left'`, `'bottom'`, `'right'`
| `offset` | `boolean` | `false` | If true, extra space is added to the both edges and the axis is scaled to fit into the chart area. This is set to `true` for a bar chart by default.
| `id` | `string` | | The ID is used to link datasets and scale axes together. [more...](#axis-id)
| `gridLines` | `object` | | Grid line configuration. [more...](../styling.md#grid-line-configuration)
| `scaleLabel` | `object` | | Scale title configuration. [more...](../labelling.md#scale-title-configuration)
| `ticks` | `object` | | Tick configuration. [more...](#tick-configuration)
### Tick Configuration
The following options are common to all cartesian axes but do not apply to other axes.
| Name | Type | Default | Description
| ---- | ---- | ------- | -----------
| `min` | `number` | | User defined minimum value for the scale, overrides minimum value from data.
| `max` | `number` | | User defined maximum value for the scale, overrides maximum value from data.
| `sampleSize` | `number` | `ticks.length` | The number of ticks to examine when deciding how many labels will fit. Setting a smaller value will be faster, but may be less accurate when there is large variability in label length.
| `autoSkip` | `boolean` | `true` | If true, automatically calculates how many labels can be shown and hides labels accordingly. Labels will be rotated up to `maxRotation` before skipping any. Turn `autoSkip` off to show all labels no matter what.
| `autoSkipPadding` | `number` | `0` | Padding between the ticks on the horizontal axis when `autoSkip` is enabled.
| `labelOffset` | `number` | `0` | Distance in pixels to offset the label from the centre point of the tick (in the x direction for the x axis, and the y direction for the y axis). *Note: this can cause labels at the edges to be cropped by the edge of the canvas*
| `maxRotation` | `number` | `50` | Maximum rotation for tick labels when rotating to condense labels. Note: Rotation doesn't occur until necessary. *Note: Only applicable to horizontal scales.*
| `minRotation` | `number` | `0` | Minimum rotation for tick labels. *Note: Only applicable to horizontal scales.*
| `mirror` | `boolean` | `false` | Flips tick labels around axis, displaying the labels inside the chart instead of outside. *Note: Only applicable to vertical scales.*
| `padding` | `number` | `0` | Padding between the tick label and the axis. When set on a vertical axis, this applies in the horizontal (X) direction. When set on a horizontal axis, this applies in the vertical (Y) direction.
### Axis ID
The properties `dataset.xAxisID` or `dataset.yAxisID` have to match the scale properties `scales.xAxes.id` or `scales.yAxes.id`. This is especially needed if multi-axes charts are used.
```javascript
var myChart = new Chart(ctx, {
type: 'line',
data: {
datasets: [{
// This dataset appears on the first axis
yAxisID: 'first-y-axis'
}, {
// This dataset appears on the second axis
yAxisID: 'second-y-axis'
}]
},
options: {
scales: {
yAxes: [{
id: 'first-y-axis',
type: 'linear'
}, {
id: 'second-y-axis',
type: 'linear'
}]
}
}
});
```
## Creating Multiple Axes
With cartesian axes, it is possible to create multiple X and Y axes. To do so, you can add multiple configuration objects to the `xAxes` and `yAxes` properties. When adding new axes, it is important to ensure that you specify the type of the new axes as default types are **not** used in this case.
In the example below, we are creating two Y axes. We then use the `yAxisID` property to map the datasets to their correct axes.
```javascript
var myChart = new Chart(ctx, {
type: 'line',
data: {
datasets: [{
data: [20, 50, 100, 75, 25, 0],
label: 'Left dataset',
// This binds the dataset to the left y axis
yAxisID: 'left-y-axis'
}, {
data: [0.1, 0.5, 1.0, 2.0, 1.5, 0],
label: 'Right dataset',
// This binds the dataset to the right y axis
yAxisID: 'right-y-axis'
}],
labels: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun']
},
options: {
scales: {
yAxes: [{
id: 'left-y-axis',
type: 'linear',
position: 'left'
}, {
id: 'right-y-axis',
type: 'linear',
position: 'right'
}]
}
}
});
```

View File

@@ -0,0 +1,69 @@
# Category Cartesian Axis
If global configuration is used, labels are drawn from one of the label arrays included in the chart data. If only `data.labels` is defined, this will be used. If `data.xLabels` is defined and the axis is horizontal, this will be used. Similarly, if `data.yLabels` is defined and the axis is vertical, this property will be used. Using both `xLabels` and `yLabels` together can create a chart that uses strings for both the X and Y axes.
Specifying any of the settings above defines the x axis as `type: 'category'` if not defined otherwise. For more fine-grained control of category labels it is also possible to add `labels` as part of the category axis definition. Doing so does not apply the global defaults.
## Category Axis Definition
Globally:
```javascript
let chart = new Chart(ctx, {
type: ...
data: {
labels: ['January', 'February', 'March', 'April', 'May', 'June'],
datasets: ...
}
});
```
As part of axis definition:
```javascript
let chart = new Chart(ctx, {
type: ...
data: ...
options: {
scales: {
xAxes: [{
type: 'category',
labels: ['January', 'February', 'March', 'April', 'May', 'June']
}]
}
}
});
```
## Tick Configuration Options
The category scale provides the following options for configuring tick marks. They are nested in the `ticks` sub object. These options extend the [common tick configuration](README.md#tick-configuration).
| Name | Type | Default | Description
| ---- | ---- | ------- | -----------
| `labels` | `string[]` | - | An array of labels to display.
| `min` | `string` | | The minimum item to display. [more...](#min-max-configuration)
| `max` | `string` | | The maximum item to display. [more...](#min-max-configuration)
## Min Max Configuration
For both the `min` and `max` properties, the value must be in the `labels` array. In the example below, the x axis would only display "March" through "June".
```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: {
xAxes: [{
ticks: {
min: 'March'
}
}]
}
}
});
```

View File

@@ -0,0 +1,73 @@
# Linear Cartesian Axis
The linear scale is use to chart numerical data. It can be placed on either the x or y axis. The scatter chart type automatically configures a line chart to use one of these scales for the x axis. As the name suggests, linear interpolation is used to determine where a value lies on the axis.
## Tick Configuration Options
The following options are provided by the linear scale. They are all located in the `ticks` sub options. These options extend the [common tick configuration](README.md#tick-configuration).
| Name | Type | Default | Description
| ---- | ---- | ------- | -----------
| `beginAtZero` | `boolean` | | if true, scale will include 0 if it is not already included.
| `maxTicksLimit` | `number` | `11` | Maximum number of ticks and gridlines to show.
| `precision` | `number` | | if defined and `stepSize` is not specified, the step size will be rounded to this many decimal places.
| `stepSize` | `number` | | User defined fixed step size for the scale. [more...](#step-size)
| `suggestedMax` | `number` | | Adjustment used when calculating the maximum data value. [more...](#axis-range-settings)
| `suggestedMin` | `number` | | Adjustment used when calculating the minimum data value. [more...](#axis-range-settings)
## Axis Range Settings
Given the number of axis range settings, it is important to understand how they all interact with each other.
The `suggestedMax` and `suggestedMin` settings only change the data values that are used to scale the axis. These are useful for extending the range of the axis while maintaining the auto fit behaviour.
```javascript
let minDataValue = Math.min(mostNegativeValue, options.ticks.suggestedMin);
let maxDataValue = Math.max(mostPositiveValue, options.ticks.suggestedMax);
```
In this example, the largest positive value is 50, but the data maximum is expanded out to 100. However, because the lowest data value is below the `suggestedMin` setting, it is ignored.
```javascript
let chart = new Chart(ctx, {
type: 'line',
data: {
datasets: [{
label: 'First dataset',
data: [0, 20, 40, 50]
}],
labels: ['January', 'February', 'March', 'April']
},
options: {
scales: {
yAxes: [{
ticks: {
suggestedMin: 50,
suggestedMax: 100
}
}]
}
}
});
```
In contrast to the `suggested*` settings, the `min` and `max` settings set explicit ends to the axes. When these are set, some data points may not be visible.
## Step Size
If set, the scale ticks will be enumerated by multiple of `stepSize`, having one tick per increment. If not set, the ticks are labeled automatically using the nice numbers algorithm.
This example sets up a chart with a y axis that creates ticks at `0, 0.5, 1, 1.5, 2, 2.5, 3, 3.5, 4, 4.5, 5`.
```javascript
let options = {
scales: {
yAxes: [{
ticks: {
max: 5,
min: 0,
stepSize: 0.5
}
}]
}
};
```

View File

@@ -0,0 +1,7 @@
# Logarithmic Cartesian Axis
The logarithmic scale is use to chart numerical data. It can be placed on either the x or y axis. As the name suggests, logarithmic interpolation is used to determine where a value lies on the axis.
## Tick Configuration Options
The logarithmic scale options extend the [common tick configuration](README.md#tick-configuration). This scale does not define any options that are unique to it.

View File

@@ -0,0 +1,157 @@
# Time Cartesian Axis
The time scale is used to display times and dates. When building its ticks, it will automatically calculate the most comfortable unit base on the size of the scale.
## Date Adapters
The time scale requires both a date library and corresponding adapter to be present. By default, Chart.js includes an adapter for Moment.js. You may wish to [exclude moment](../../getting-started/integration.md) and choose from [other available adapters](https://github.com/chartjs/awesome#adapters) instead.
## Data Sets
### Input Data
The x-axis data points may additionally be specified via the `t` or `x` attribute when using the time scale.
```javascript
data: [{
x: new Date(),
y: 1
}, {
t: new Date(),
y: 10
}]
```
### Date Formats
When providing data for the time scale, Chart.js supports all of the formats that Moment.js accepts. See [Moment.js docs](https://momentjs.com/docs/#/parsing/) for details.
## Configuration Options
The following options are provided by the time scale. You may also set options provided by the [common tick configuration](README.md#tick-configuration).
| Name | Type | Default | Description
| ---- | ---- | ------- | -----------
| `adapters.date` | `object` | `{}` | Options for adapter for external date library if that adapter needs or supports options
| `distribution` | `string` | `'linear'` | How data is plotted. [more...](#scale-distribution)
| `bounds` | `string` | `'data'` | Determines the scale bounds. [more...](#scale-bounds)
| `ticks.source` | `string` | `'auto'` | How ticks are generated. [more...](#ticks-source)
| `time.displayFormats` | `object` | | Sets how different time units are displayed. [more...](#display-formats)
| `time.isoWeekday` | `boolean` | `false` | If true and the unit is set to 'week', then the first day of the week will be Monday. Otherwise, it will be Sunday.
| `time.parser` | <code>string&#124;function</code> | | Custom parser for dates. [more...](#parser)
| `time.round` | `string` | `false` | If defined, dates will be rounded to the start of this unit. See [Time Units](#time-units) below for the allowed units.
| `time.tooltipFormat` | `string` | | The Moment.js format string to use for the tooltip.
| `time.unit` | `string` | `false` | If defined, will force the unit to be a certain type. See [Time Units](#time-units) section below for details.
| `time.stepSize` | `number` | `1` | The number of units between grid lines.
| `time.minUnit` | `string` | `'millisecond'` | The minimum display format to be used for a time unit.
### Time Units
The following time measurements are supported. The names can be passed as strings to the `time.unit` config option to force a certain unit.
* `'millisecond'`
* `'second'`
* `'minute'`
* `'hour'`
* `'day'`
* `'week'`
* `'month'`
* `'quarter'`
* `'year'`
For example, to create a chart with a time scale that always displayed units per month, the following config could be used.
```javascript
var chart = new Chart(ctx, {
type: 'line',
data: data,
options: {
scales: {
xAxes: [{
type: 'time',
time: {
unit: 'month'
}
}]
}
}
});
```
### Display Formats
The following display formats are used to configure how different time units are formed into strings for the axis tick marks. See [Moment.js](https://momentjs.com/docs/#/displaying/format/) for the allowable format strings.
Name | Default | Example
--- | --- | ---
`millisecond` | `'h:mm:ss.SSS a'` | `'11:20:01.123 AM'`
`second` | `'h:mm:ss a'` | `'11:20:01 AM'`
`minute` | `'h:mm a'` | `'11:20 AM'`
`hour` | `'hA'` | `'11AM'`
`day` | `'MMM D'` | `'Sep 4'`
`week` | `'ll'` | `'Sep 4 2015'`
`month` | `'MMM YYYY'` | `'Sep 2015'`
`quarter` | `'[Q]Q - YYYY'` | `'Q3 - 2015'`
`year` | `'YYYY'` | `'2015'`
For example, to set the display format for the `quarter` unit to show the month and year, the following config would be passed to the chart constructor.
```javascript
var chart = new Chart(ctx, {
type: 'line',
data: data,
options: {
scales: {
xAxes: [{
type: 'time',
time: {
displayFormats: {
quarter: 'MMM YYYY'
}
}
}]
}
}
});
```
### Scale Distribution
The `distribution` property controls the data distribution along the scale:
* `'linear'`: data are spread according to their time (distances can vary)
* `'series'`: data are spread at the same distance from each other
```javascript
var chart = new Chart(ctx, {
type: 'line',
data: data,
options: {
scales: {
xAxes: [{
type: 'time',
distribution: 'series'
}]
}
}
});
```
### Scale Bounds
The `bounds` property controls the scale boundary strategy (bypassed by `min`/`max` time options).
* `'data'`: makes sure data are fully visible, labels outside are removed
* `'ticks'`: makes sure ticks are fully visible, data outside are truncated
### Ticks Source
The `ticks.source` property controls the ticks generation.
* `'auto'`: generates "optimal" ticks based on scale size and time options
* `'data'`: generates ticks from data (including labels from data `{t|x|y}` objects)
* `'labels'`: generates ticks from user given `labels` ONLY
### Parser
If this property is defined as a string, it is interpreted as a custom format to be used by Moment.js to parse the date.
If this is a function, it must return a Moment.js object given the appropriate data value.

View File

@@ -0,0 +1,46 @@
# Labeling Axes
When creating a chart, you want to tell the viewer what data they are viewing. To do this, you need to label the axis.
## Scale Title Configuration
The scale label configuration is nested under the scale configuration in the `scaleLabel` key. It defines options for the scale title. Note that this only applies to cartesian axes.
| Name | Type | Default | Description
| ---- | ---- | ------- | -----------
| `display` | `boolean` | `false` | If true, display the axis title.
| `labelString` | `string` | `''` | The text for the title. (i.e. "# of People" or "Response Choices").
| `lineHeight` | <code>number&#124;string</code> | `1.2` | Height of an individual line of text (see [MDN](https://developer.mozilla.org/en-US/docs/Web/CSS/line-height)).
| `fontColor` | `Color` | `'#666'` | Font color for scale title.
| `fontFamily` | `string` | `"'Helvetica Neue', 'Helvetica', 'Arial', sans-serif"` | Font family for the scale title, follows CSS font-family options.
| `fontSize` | `number` | `12` | Font size for scale title.
| `fontStyle` | `string` | `'normal'` | Font style for the scale title, follows CSS font-style options (i.e. normal, italic, oblique, initial, inherit).
| `padding` | <code>number&#124;object</code> | `4` | Padding to apply around scale labels. Only `top` and `bottom` are implemented.
## Creating Custom Tick Formats
It is also common to want to change the tick marks to include information about the data type. For example, adding a dollar sign ('$'). To do this, you need to override the `ticks.callback` method in the axis configuration.
In the following example, every label of the Y axis would be displayed with a dollar sign at the front.
If the callback returns `null` or `undefined` the associated grid line will be hidden.
```javascript
var chart = new Chart(ctx, {
type: 'line',
data: data,
options: {
scales: {
yAxes: [{
ticks: {
// Include a dollar sign in the ticks
callback: function(value, index, values) {
return '$' + value;
}
}
}]
}
}
});
```
The third parameter passed to the callback function is an array of labels, but in the time scale, it is an array of `{label: string, major: boolean}` objects.

View File

@@ -0,0 +1,5 @@
# Radial Axes
Radial axes are used specifically for the radar and polar area chart types. These axes overlay the chart area, rather than being positioned on one of the edges. One radial axis is included by default in Chart.js.
* [linear](./linear.md#linear-radial-axis)

View File

@@ -0,0 +1,113 @@
# Linear Radial Axis
The linear scale is used to chart numerical data. As the name suggests, linear interpolation is used to determine where a value lies in relation the center of the axis.
The following additional configuration options are provided by the radial linear scale.
## Configuration Options
The axis has configuration properties for ticks, angle lines (line that appear in a radar chart outward from the center), pointLabels (labels around the edge in a radar chart). The following sections define each of the properties in those sections.
| Name | Type | Description
| ---- | ---- | -----------
| `angleLines` | `object` | Angle line configuration. [more...](#angle-line-options)
| `gridLines` | `object` | Grid line configuration. [more...](../styling.md#grid-line-configuration)
| `pointLabels` | `object` | Point label configuration. [more...](#point-label-options)
| `ticks` | `object` | Tick configuration. [more...](#tick-options)
## Tick Options
The following options are provided by the linear scale. They are all located in the `ticks` sub options. The [common tick configuration](../styling.md#tick-configuration) options are supported by this axis.
| Name | Type | Default | Description
| ---- | ---- | ------- | -----------
| `backdropColor` | `Color` | `'rgba(255, 255, 255, 0.75)'` | Color of label backdrops.
| `backdropPaddingX` | `number` | `2` | Horizontal padding of label backdrop.
| `backdropPaddingY` | `number` | `2` | Vertical padding of label backdrop.
| `beginAtZero` | `boolean` | `false` | if true, scale will include 0 if it is not already included.
| `min` | `number` | | User defined minimum number for the scale, overrides minimum value from data. [more...](#axis-range-settings)
| `max` | `number` | | User defined maximum number for the scale, overrides maximum value from data. [more...](#axis-range-settings)
| `maxTicksLimit` | `number` | `11` | Maximum number of ticks and gridlines to show.
| `precision` | `number` | | if defined and `stepSize` is not specified, the step size will be rounded to this many decimal places.
| `stepSize` | `number` | | User defined fixed step size for the scale. [more...](#step-size)
| `suggestedMax` | `number` | | Adjustment used when calculating the maximum data value. [more...](#axis-range-settings)
| `suggestedMin` | `number` | | Adjustment used when calculating the minimum data value. [more...](#axis-range-settings)
| `showLabelBackdrop` | `boolean` | `true` | If true, draw a background behind the tick labels.
## Axis Range Settings
Given the number of axis range settings, it is important to understand how they all interact with each other.
The `suggestedMax` and `suggestedMin` settings only change the data values that are used to scale the axis. These are useful for extending the range of the axis while maintaining the auto fit behaviour.
```javascript
let minDataValue = Math.min(mostNegativeValue, options.ticks.suggestedMin);
let maxDataValue = Math.max(mostPositiveValue, options.ticks.suggestedMax);
```
In this example, the largest positive value is 50, but the data maximum is expanded out to 100. However, because the lowest data value is below the `suggestedMin` setting, it is ignored.
```javascript
let chart = new Chart(ctx, {
type: 'radar',
data: {
datasets: [{
label: 'First dataset',
data: [0, 20, 40, 50]
}],
labels: ['January', 'February', 'March', 'April']
},
options: {
scale: {
ticks: {
suggestedMin: 50,
suggestedMax: 100
}
}
}
});
```
In contrast to the `suggested*` settings, the `min` and `max` settings set explicit ends to the axes. When these are set, some data points may not be visible.
## Step Size
If set, the scale ticks will be enumerated by multiple of `stepSize`, having one tick per increment. If not set, the ticks are labeled automatically using the nice numbers algorithm.
This example sets up a chart with a y axis that creates ticks at `0, 0.5, 1, 1.5, 2, 2.5, 3, 3.5, 4, 4.5, 5`.
```javascript
let options = {
scale: {
ticks: {
max: 5,
min: 0,
stepSize: 0.5
}
}
};
```
## Angle Line Options
The following options are used to configure angled lines that radiate from the center of the chart to the point labels. They can be found in the `angleLines` sub options.
| Name | Type | Default | Description
| ---- | ---- | ------- | -----------
| `display` | `boolean` | `true` | if true, angle lines are shown.
| `color` | `Color` | `'rgba(0, 0, 0, 0.1)'` | Color of angled lines.
| `lineWidth` | `number` | `1` | Width of angled lines.
| `borderDash` | `number[]` | `[]` | Length and spacing of dashes on angled lines. See [MDN](https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/setLineDash).
| `borderDashOffset` | `number` | `0.0` | Offset for line dashes. See [MDN](https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/lineDashOffset).
## Point Label Options
The following options are used to configure the point labels that are shown on the perimeter of the scale. They can be found in the `pointLabels` sub options.
| Name | Type | Default | Description
| ---- | ---- | ------- | -----------
| `display` | `boolean` | `true` | if true, point labels are shown.
| `callback` | `function` | | Callback function to transform data labels to point labels. The default implementation simply returns the current string.
| `fontColor` | <code>Color&#124;Color[]</code> | `'#666'` | Font color for point labels.
| `fontFamily` | `string` | `"'Helvetica Neue', 'Helvetica', 'Arial', sans-serif"` | Font family to use when rendering labels.
| `fontSize` | `number` | `10` | font size in pixels.
| `fontStyle` | `string` | `'normal'` | Font style to use when rendering point labels.
| `lineHeight` | <code>number&#124;string</code> | `1.2` | Height of an individual line of text (see [MDN](https://developer.mozilla.org/en-US/docs/Web/CSS/line-height)).

View File

@@ -0,0 +1,69 @@
# Styling
There are a number of options to allow styling an axis. There are settings to control [grid lines](#grid-line-configuration) and [ticks](#tick-configuration).
## Grid Line Configuration
The grid line configuration is nested under the scale configuration in the `gridLines` key. It defines options for the grid lines that run perpendicular to the axis.
| Name | Type | Default | Description
| ---- | ---- | ------- | -----------
| `display` | `boolean` | `true` | If false, do not display grid lines for this axis.
| `circular` | `boolean` | `false` | If true, gridlines are circular (on radar chart only).
| `color` | <code>Color&#124;Color[]</code> | `'rgba(0, 0, 0, 0.1)'` | The color of the grid lines. If specified as an array, the first color applies to the first grid line, the second to the second grid line and so on.
| `borderDash` | `number[]` | `[]` | Length and spacing of dashes on grid lines. See [MDN](https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/setLineDash).
| `borderDashOffset` | `number` | `0.0` | Offset for line dashes. See [MDN](https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/lineDashOffset).
| `lineWidth` | <code>number&#124;number[]</code> | `1` | Stroke width of grid lines.
| `drawBorder` | `boolean` | `true` | If true, draw border at the edge between the axis and the chart area.
| `drawOnChartArea` | `boolean` | `true` | If true, draw lines on the chart area inside the axis lines. This is useful when there are multiple axes and you need to control which grid lines are drawn.
| `drawTicks` | `boolean` | `true` | If true, draw lines beside the ticks in the axis area beside the chart.
| `tickMarkLength` | `number` | `10` | Length in pixels that the grid lines will draw into the axis area.
| `zeroLineWidth` | `number` | `1` | Stroke width of the grid line for the first index (index 0).
| `zeroLineColor` | `Color` | `'rgba(0, 0, 0, 0.25)'` | Stroke color of the grid line for the first index (index 0).
| `zeroLineBorderDash` | `number[]` | `[]` | Length and spacing of dashes of the grid line for the first index (index 0). See [MDN](https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/setLineDash).
| `zeroLineBorderDashOffset` | `number` | `0.0` | Offset for line dashes of the grid line for the first index (index 0). See [MDN](https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/lineDashOffset).
| `offsetGridLines` | `boolean` | `false` | If true, grid lines will be shifted to be between labels. This is set to `true` for a bar chart by default.
| `z` | `number` | `0` | z-index of gridline layer. Values &lt;= 0 are drawn under datasets, &gt; 0 on top.
## Tick Configuration
The tick configuration is nested under the scale configuration in the `ticks` key. It defines options for the tick marks that are generated by the axis.
| Name | Type | Default | Description
| ---- | ---- | ------- | -----------
| `callback` | `function` | | Returns the string representation of the tick value as it should be displayed on the chart. See [callback](../axes/labelling.md#creating-custom-tick-formats).
| `display` | `boolean` | `true` | If true, show tick labels.
| `fontColor` | `Color` | `'#666'` | Font color for tick labels.
| `fontFamily` | `string` | `"'Helvetica Neue', 'Helvetica', 'Arial', sans-serif"` | Font family for the tick labels, follows CSS font-family options.
| `fontSize` | `number` | `12` | Font size for the tick labels.
| `fontStyle` | `string` | `'normal'` | Font style for the tick labels, follows CSS font-style options (i.e. normal, italic, oblique, initial, inherit).
| `lineHeight` | <code>number&#124;string</code> | `1.2` | Height of an individual line of text (see [MDN](https://developer.mozilla.org/en-US/docs/Web/CSS/line-height)).
| `reverse` | `boolean` | `false` | Reverses order of tick labels.
| `minor` | `object` | `{}` | Minor ticks configuration. Omitted options are inherited from options above.
| `major` | `object` | `{}` | Major ticks configuration. Omitted options are inherited from options above.
| `padding` | `number` | `0` | Sets the offset of the tick labels from the axis
| `z` | `number` | `0` | z-index of tick layer. Useful when ticks are drawn on chart area. Values &lt;= 0 are drawn under datasets, &gt; 0 on top.
## Minor Tick Configuration
The minorTick configuration is nested under the ticks configuration in the `minor` key. It defines options for the minor tick marks that are generated by the axis. Omitted options are inherited from `ticks` configuration.
| Name | Type | Default | Description
| ---- | ---- | ------- | -----------
| `callback` | `function` | | Returns the string representation of the tick value as it should be displayed on the chart. See [callback](../axes/labelling.md#creating-custom-tick-formats).
| `fontColor` | `Color` | `'#666'` | Font color for tick labels.
| `fontFamily` | `string` | `"'Helvetica Neue', 'Helvetica', 'Arial', sans-serif"` | Font family for the tick labels, follows CSS font-family options.
| `fontSize` | `number` | `12` | Font size for the tick labels.
| `fontStyle` | `string` | `'normal'` | Font style for the tick labels, follows CSS font-style options (i.e. normal, italic, oblique, initial, inherit).
| `lineHeight` | <code>number&#124;string</code> | `1.2` | Height of an individual line of text (see [MDN](https://developer.mozilla.org/en-US/docs/Web/CSS/line-height)).
## Major Tick Configuration
The majorTick configuration is nested under the ticks configuration in the `major` key. It defines options for the major tick marks that are generated by the axis. Omitted options are inherited from `ticks` configuration. These options are disabled by default.
| Name | Type | Default | Description
| ---- | ---- | ------- | -----------
| `enabled` | `boolean` | `false` | If true, major tick options are used to show major ticks.
| `callback` | `function` | | Returns the string representation of the tick value as it should be displayed on the chart. See [callback](../axes/labelling.md#creating-custom-tick-formats).
| `fontColor` | `Color` | `'#666'` | Font color for tick labels.
| `fontFamily` | `string` | `"'Helvetica Neue', 'Helvetica', 'Arial', sans-serif"` | Font family for the tick labels, follows CSS font-family options.
| `fontSize` | `number` | `12` | Font size for the tick labels.
| `fontStyle` | `string` | `'normal'` | Font style for the tick labels, follows CSS font-style options (i.e. normal, italic, oblique, initial, inherit).
| `lineHeight` | <code>number&#124;string</code> | `1.2` | Height of an individual line of text (see [MDN](https://developer.mozilla.org/en-US/docs/Web/CSS/line-height)).

View File

@@ -0,0 +1,14 @@
# Charts
Chart.js comes with built-in chart types:
* [line](./line.md)
* [bar](./bar.md)
* [radar](./radar.md)
* [doughnut and pie](./doughnut.md)
* [polar area](./polar.md)
* [bubble](./bubble.md)
* [scatter](./scatter.md)
[Area charts](area.md) can be built from a line or radar chart using the dataset `fill` option.
To create a new chart type, see the [developer notes](../developers/charts.md#new-charts).

View File

@@ -0,0 +1,72 @@
# Area Charts
Both [line](line.md) and [radar](radar.md) charts support a `fill` option on the dataset object which can be used to create area between two datasets or a dataset and a boundary, i.e. the scale `origin`, `start` or `end` (see [filling modes](#filling-modes)).
> **Note:** this feature is implemented by the [`filler` plugin](https://github.com/chartjs/Chart.js/blob/master/src/plugins/plugin.filler.js).
## Filling modes
| Mode | Type | Values |
| :--- | :--- | :--- |
| Absolute dataset index <sup>1</sup> | `number` | `1`, `2`, `3`, ... |
| Relative dataset index <sup>1</sup> | `string` | `'-1'`, `'-2'`, `'+1'`, ... |
| Boundary <sup>2</sup> | `string` | `'start'`, `'end'`, `'origin'` |
| Disabled <sup>3</sup> | `boolean` | `false` |
> <sup>1</sup> dataset filling modes have been introduced in version 2.6.0<br>
> <sup>2</sup> prior version 2.6.0, boundary values was `'zero'`, `'top'`, `'bottom'` (deprecated)<br>
> <sup>3</sup> for backward compatibility, `fill: true` (default) is equivalent to `fill: 'origin'`<br>
**Example**
```javascript
new Chart(ctx, {
data: {
datasets: [
{fill: 'origin'}, // 0: fill to 'origin'
{fill: '+2'}, // 1: fill to dataset 3
{fill: 1}, // 2: fill to dataset 1
{fill: false}, // 3: no fill
{fill: '-2'} // 4: fill to dataset 2
]
}
});
```
## Configuration
| Option | Type | Default | Description |
| :--- | :--- | :--- | :--- |
| [`plugins.filler.propagate`](#propagate) | `boolean` | `true` | Fill propagation when target is hidden.
### propagate
`propagate` takes a `boolean` value (default: `true`).
If `true`, the fill area will be recursively extended to the visible target defined by the `fill` value of hidden dataset targets:
**Example**
```javascript
new Chart(ctx, {
data: {
datasets: [
{fill: 'origin'}, // 0: fill to 'origin'
{fill: '-1'}, // 1: fill to dataset 0
{fill: 1}, // 2: fill to dataset 1
{fill: false}, // 3: no fill
{fill: '-2'} // 4: fill to dataset 2
]
},
options: {
plugins: {
filler: {
propagate: true
}
}
}
});
```
`propagate: true`:
- if dataset 2 is hidden, dataset 4 will fill to dataset 1
- if dataset 2 and 1 are hidden, dataset 4 will fill to `'origin'`
`propagate: false`:
- if dataset 2 and/or 4 are hidden, dataset 4 will not be filled

View File

@@ -0,0 +1,323 @@
# Bar
A bar chart provides a way of showing data values represented as vertical bars. It is sometimes used to show trend data, and the comparison of multiple data sets side by side.
{% chartjs %}
{
"type": "bar",
"data": {
"labels": [
"January",
"February",
"March",
"April",
"May",
"June",
"July"
],
"datasets": [{
"label": "My First Dataset",
"data": [65, 59, 80, 81, 56, 55, 40],
"fill": false,
"backgroundColor": [
"rgba(255, 99, 132, 0.2)",
"rgba(255, 159, 64, 0.2)",
"rgba(255, 205, 86, 0.2)",
"rgba(75, 192, 192, 0.2)",
"rgba(54, 162, 235, 0.2)",
"rgba(153, 102, 255, 0.2)",
"rgba(201, 203, 207, 0.2)"
],
"borderColor": [
"rgb(255, 99, 132)",
"rgb(255, 159, 64)",
"rgb(255, 205, 86)",
"rgb(75, 192, 192)",
"rgb(54, 162, 235)",
"rgb(153, 102, 255)",
"rgb(201, 203, 207)"
],
"borderWidth": 1
}]
},
"options": {
"scales": {
"yAxes": [{
"ticks": {
"beginAtZero": true
}
}]
}
}
}
{% endchartjs %}
## Example Usage
```javascript
var myBarChart = new Chart(ctx, {
type: 'bar',
data: data,
options: options
});
```
## Dataset Properties
The bar chart allows a number of properties to be specified for each dataset.
These are used to set display properties for a specific dataset. For example,
the color of the bars is generally set this way.
| Name | Type | [Scriptable](../general/options.md#scriptable-options) | [Indexable](../general/options.md#indexable-options) | Default
| ---- | ---- | :----: | :----: | ----
| [`backgroundColor`](#styling) | [`Color`](../general/colors.md) | Yes | Yes | `'rgba(0, 0, 0, 0.1)'`
| [`borderColor`](#styling) | [`Color`](../general/colors.md) | Yes | Yes | `'rgba(0, 0, 0, 0.1)'`
| [`borderSkipped`](#borderskipped) | `string` | Yes | Yes | `'bottom'`
| [`borderWidth`](#borderwidth) | <code>number&#124;object</code> | Yes | Yes | `0`
| [`data`](#data-structure) | `object[]` | - | - | **required**
| [`hoverBackgroundColor`](#interactions) | [`Color`](../general/colors.md) | - | Yes | `undefined`
| [`hoverBorderColor`](#interactions) | [`Color`](../general/colors.md) | - | Yes | `undefined`
| [`hoverBorderWidth`](#interactions) | `number` | - | Yes | `1`
| [`label`](#general) | `string` | - | - | `''`
| [`order`](#general) | `number` | - | - | `0`
| [`xAxisID`](#general) | `string` | - | - | first x axis
| [`yAxisID`](#general) | `string` | - | - | first y axis
### General
| Name | Description
| ---- | ----
| `label` | The label for the dataset which appears in the legend and tooltips.
| `order` | The drawing order of dataset. Also affects order for stacking, tooltip, and legend.
| `xAxisID` | The ID of the x axis to plot this dataset on.
| `yAxisID` | The ID of the y axis to plot this dataset on.
### Styling
The style of each bar can be controlled with the following properties:
| Name | Description
| ---- | ----
| `backgroundColor` | The bar background color.
| `borderColor` | The bar border color.
| [`borderSkipped`](#borderskipped) | The edge to skip when drawing bar.
| [`borderWidth`](#borderwidth) | The bar border width (in pixels).
All these values, if `undefined`, fallback to the associated [`elements.rectangle.*`](../configuration/elements.md#rectangle-configuration) options.
#### borderSkipped
This setting is used to avoid drawing the bar stroke at the base of the fill.
In general, this does not need to be changed except when creating chart types
that derive from a bar chart.
**Note:** for negative bars in vertical chart, `top` and `bottom` are flipped. Same goes for `left` and `right` in horizontal chart.
Options are:
* `'bottom'`
* `'left'`
* `'top'`
* `'right'`
* `false`
#### borderWidth
If this value is a number, it is applied to all sides of the rectangle (left, top, right, bottom), except [`borderSkipped`](#borderskipped). If this value is an object, the `left` property defines the left border width. Similarly the `right`, `top` and `bottom` properties can also be specified. Omitted borders and [`borderSkipped`](#borderskipped) are skipped.
### Interactions
The interaction with each bar can be controlled with the following properties:
| Name | Description
| ---- | -----------
| `hoverBackgroundColor` | The bar background color when hovered.
| `hoverBorderColor` | The bar border color when hovered.
| `hoverBorderWidth` | The bar border width when hovered (in pixels).
All these values, if `undefined`, fallback to the associated [`elements.rectangle.*`](../configuration/elements.md#rectangle-configuration) options.
## Dataset Configuration
The bar chart accepts the following configuration from the associated dataset options:
| Name | Type | Default | Description
| ---- | ---- | ------- | -----------
| `barPercentage` | `number` | `0.9` | Percent (0-1) of the available width each bar should be within the category width. 1.0 will take the whole category width and put the bars right next to each other. [more...](#barpercentage-vs-categorypercentage)
| `categoryPercentage` | `number` | `0.8` | Percent (0-1) of the available width each category should be within the sample width. [more...](#barpercentage-vs-categorypercentage)
| `barThickness` | <code>number&#124;string</code> | | Manually set width of each bar in pixels. If set to `'flex'`, it computes "optimal" sample widths that globally arrange bars side by side. If not set (default), bars are equally sized based on the smallest interval. [more...](#barthickness)
| `maxBarThickness` | `number` | | Set this to ensure that bars are not sized thicker than this.
| `minBarLength` | `number` | | Set this to ensure that bars have a minimum length in pixels.
### Example Usage
```javascript
data: {
datasets: [{
barPercentage: 0.5,
barThickness: 6,
maxBarThickness: 8,
minBarLength: 2,
data: [10, 20, 30, 40, 50, 60, 70]
}]
};
```
### barThickness
If this value is a number, it is applied to the width of each bar, in pixels. When this is enforced, `barPercentage` and `categoryPercentage` are ignored.
If set to `'flex'`, the base sample widths are calculated automatically based on the previous and following samples so that they take the full available widths without overlap. Then, bars are sized using `barPercentage` and `categoryPercentage`. There is no gap when the percentage options are 1. This mode generates bars with different widths when data are not evenly spaced.
If not set (default), the base sample widths are calculated using the smallest interval that prevents bar overlapping, and bars are sized using `barPercentage` and `categoryPercentage`. This mode always generates bars equally sized.
## Scale Configuration
The bar chart sets unique default values for the following configuration from the associated `scale` options:
| Name | Type | Default | Description
| ---- | ---- | ------- | -----------
| `offset` | `boolean` | `true` | If true, extra space is added to the both edges and the axis is scaled to fit into the chart area.
| `gridLines.offsetGridLines` | `boolean` | `true` | If true, the bars for a particular data point fall between the grid lines. The grid line will move to the left by one half of the tick interval. If false, the grid line will go right down the middle of the bars. [more...](#offsetgridlines)
### Example Usage
```javascript
options = {
scales: {
xAxes: [{
gridLines: {
offsetGridLines: true
}
}]
}
};
```
### offsetGridLines
If true, the bars for a particular data point fall between the grid lines. The grid line will move to the left by one half of the tick interval, which is the space between the grid lines. If false, the grid line will go right down the middle of the bars. This is set to true for a category scale in a bar chart while false for other scales or chart types by default.
## Default Options
It is common to want to apply a configuration setting to all created bar charts. The global bar chart settings are stored in `Chart.defaults.bar`. Changing the global options only affects charts created after the change. Existing charts are not changed.
## barPercentage vs categoryPercentage
The following shows the relationship between the bar percentage option and the category percentage option.
```text
// categoryPercentage: 1.0
// barPercentage: 1.0
Bar: | 1.0 | 1.0 |
Category: | 1.0 |
Sample: |===========|
// categoryPercentage: 1.0
// barPercentage: 0.5
Bar: |.5| |.5|
Category: | 1.0 |
Sample: |==============|
// categoryPercentage: 0.5
// barPercentage: 1.0
Bar: |1.||1.|
Category: | .5 |
Sample: |==============|
```
## Data Structure
The `data` property of a dataset for a bar chart is specified as an array of numbers. Each point in the data array corresponds to the label at the same index on the x axis.
```javascript
data: [20, 10]
```
You can also specify the dataset as x/y coordinates when using the [time scale](../axes/cartesian/time.md#time-cartesian-axis).
```javascript
data: [{x:'2016-12-25', y:20}, {x:'2016-12-26', y:10}]
```
You can also specify the dataset for a bar chart as arrays of two numbers. This will force rendering of bars with gaps between them (floating-bars). First and second numbers in array will correspond the start and the end point of a bar respectively.
```javascript
data: [[5,6], [-3,-6]]
```
## Stacked Bar Chart
Bar charts can be configured into stacked bar charts by changing the settings on the X and Y axes to enable stacking. Stacked bar charts can be used to show how one data series is made up of a number of smaller pieces.
```javascript
var stackedBar = new Chart(ctx, {
type: 'bar',
data: data,
options: {
scales: {
xAxes: [{
stacked: true
}],
yAxes: [{
stacked: true
}]
}
}
});
```
The following dataset properties are specific to stacked bar charts.
| Name | Type | Description
| ---- | ---- | -----------
| `stack` | `string` | The ID of the group to which this dataset belongs to (when stacked, each group will be a separate stack).
## Horizontal Bar Chart
A horizontal bar chart is a variation on a vertical bar chart. It is sometimes used to show trend data, and the comparison of multiple data sets side by side.
{% chartjs %}
{
"type": "horizontalBar",
"data": {
"labels": ["January", "February", "March", "April", "May", "June", "July"],
"datasets": [{
"label": "My First Dataset",
"data": [65, 59, 80, 81, 56, 55, 40],
"fill": false,
"backgroundColor": [
"rgba(255, 99, 132, 0.2)",
"rgba(255, 159, 64, 0.2)",
"rgba(255, 205, 86, 0.2)",
"rgba(75, 192, 192, 0.2)",
"rgba(54, 162, 235, 0.2)",
"rgba(153, 102, 255, 0.2)",
"rgba(201, 203, 207, 0.2)"
],
"borderColor": [
"rgb(255, 99, 132)",
"rgb(255, 159, 64)",
"rgb(255, 205, 86)",
"rgb(75, 192, 192)",
"rgb(54, 162, 235)",
"rgb(153, 102, 255)",
"rgb(201, 203, 207)"
],
"borderWidth": 1
}]
},
"options": {
"scales": {
"xAxes": [{
"ticks": {
"beginAtZero": true
}
}]
}
}
}
{% endchartjs %}
## Example
```javascript
var myBarChart = new Chart(ctx, {
type: 'horizontalBar',
data: data,
options: options
});
```
### Config Options
The configuration options for the horizontal bar chart are the same as for the [bar chart](#scale-configuration). However, any options specified on the x axis in a bar chart, are applied to the y axis in a horizontal bar chart.
The default horizontal bar configuration is specified in `Chart.defaults.horizontalBar`.

View File

@@ -0,0 +1,115 @@
# Bubble Chart
A bubble chart is used to display three dimensions of data at the same time. The location of the bubble is determined by the first two dimensions and the corresponding horizontal and vertical axes. The third dimension is represented by the size of the individual bubbles.
{% chartjs %}
{
"type": "bubble",
"data": {
"datasets": [{
"label": "First Dataset",
"data": [{
"x": 20,
"y": 30,
"r": 15
}, {
"x": 40,
"y": 10,
"r": 10
}],
"backgroundColor": "rgb(255, 99, 132)"
}]
}
}
{% endchartjs %}
## Example Usage
```javascript
// For a bubble chart
var myBubbleChart = new Chart(ctx, {
type: 'bubble',
data: data,
options: options
});
```
## Dataset Properties
The bubble chart allows a number of properties to be specified for each dataset. These are used to set display properties for a specific dataset. For example, the colour of the bubbles is generally set this way.
| Name | Type | [Scriptable](../general/options.md#scriptable-options) | [Indexable](../general/options.md#indexable-options) | Default
| ---- | ---- | :----: | :----: | ----
| [`backgroundColor`](#styling) | [`Color`](../general/colors.md) | Yes | Yes | `'rgba(0, 0, 0, 0.1)'`
| [`borderColor`](#styling) | [`Color`](../general/colors.md) | Yes | Yes | `'rgba(0, 0, 0, 0.1)'`
| [`borderWidth`](#styling) | `number` | Yes | Yes | `3`
| [`data`](#data-structure) | `object[]` | - | - | **required**
| [`hoverBackgroundColor`](#interactions) | [`Color`](../general/colors.md) | Yes | Yes | `undefined`
| [`hoverBorderColor`](#interactions) | [`Color`](../general/colors.md) | Yes | Yes | `undefined`
| [`hoverBorderWidth`](#interactions) | `number` | Yes | Yes | `1`
| [`hoverRadius`](#interactions) | `number` | Yes | Yes | `4`
| [`hitRadius`](#interactions) | `number` | Yes | Yes | `1`
| [`label`](#general) | `string` | - | - | `undefined`
| [`order`](#general) | `number` | - | - | `0`
| [`pointStyle`](#styling) | `string` | Yes | Yes | `'circle'`
| [`rotation`](#styling) | `number` | Yes | Yes | `0`
| [`radius`](#styling) | `number` | Yes | Yes | `3`
### General
| Name | Description
| ---- | ----
| `label` | The label for the dataset which appears in the legend and tooltips.
| `order` | The drawing order of dataset.
### Styling
The style of each bubble can be controlled with the following properties:
| Name | Description
| ---- | ----
| `backgroundColor` | bubble background color.
| `borderColor` | bubble border color.
| `borderWidth` | bubble border width (in pixels).
| `pointStyle` | bubble [shape style](../configuration/elements#point-styles).
| `rotation` | bubble rotation (in degrees).
| `radius` | bubble radius (in pixels).
All these values, if `undefined`, fallback to the associated [`elements.point.*`](../configuration/elements.md#point-configuration) options.
### Interactions
The interaction with each bubble can be controlled with the following properties:
| Name | Description
| ---- | -----------
| `hoverBackgroundColor` | bubble background color when hovered.
| `hoverBorderColor` | bubble border color when hovered.
| `hoverBorderWidth` | bubble border width when hovered (in pixels).
| `hoverRadius` | bubble **additional** radius when hovered (in pixels).
| `hitRadius` | bubble **additional** radius for hit detection (in pixels).
All these values, if `undefined`, fallback to the associated [`elements.point.*`](../configuration/elements.md#point-configuration) options.
## Default Options
We can also change the default values for the Bubble chart type. Doing so will give all bubble charts created after this point the new defaults. The default configuration for the bubble chart can be accessed at `Chart.defaults.bubble`.
## Data Structure
Bubble chart datasets need to contain a `data` array of points, each points represented by an object containing the following properties:
```javascript
{
// X Value
x: number,
// Y Value
y: number,
// Bubble radius in pixels (not scaled).
r: number
}
```
**Important:** the radius property, `r` is **not** scaled by the chart, it is the raw radius in pixels of the bubble that is drawn on the canvas.

View File

@@ -0,0 +1,136 @@
# Doughnut and Pie
Pie and doughnut charts are probably the most commonly used charts. They are divided into segments, the arc of each segment shows the proportional value of each piece of data.
They are excellent at showing the relational proportions between data.
Pie and doughnut charts are effectively the same class in Chart.js, but have one different default value - their `cutoutPercentage`. This equates what percentage of the inner should be cut out. This defaults to `0` for pie charts, and `50` for doughnuts.
They are also registered under two aliases in the `Chart` core. Other than their different default value, and different alias, they are exactly the same.
{% chartjs %}
{
"type": "doughnut",
"data": {
"labels": [
"Red",
"Blue",
"Yellow"
],
"datasets": [{
"label": "My First Dataset",
"data": [300, 50, 100],
"backgroundColor": [
"rgb(255, 99, 132)",
"rgb(54, 162, 235)",
"rgb(255, 205, 86)"
]
}]
}
}
{% endchartjs %}
## Example Usage
```javascript
// For a pie chart
var myPieChart = new Chart(ctx, {
type: 'pie',
data: data,
options: options
});
```
```javascript
// And for a doughnut chart
var myDoughnutChart = new Chart(ctx, {
type: 'doughnut',
data: data,
options: options
});
```
## Dataset Properties
The doughnut/pie chart allows a number of properties to be specified for each dataset. These are used to set display properties for a specific dataset. For example, the colours of the dataset's arcs are generally set this way.
| Name | Type | [Scriptable](../general/options.md#scriptable-options) | [Indexable](../general/options.md#indexable-options) | Default
| ---- | ---- | :----: | :----: | ----
| [`backgroundColor`](#styling) | [`Color`](../general/colors.md) | Yes | Yes | `'rgba(0, 0, 0, 0.1)'`
| [`borderAlign`](#border-alignment) | `string` | Yes | Yes | `'center'`
| [`borderColor`](#styling) | [`Color`](../general/colors.md) | Yes | Yes | `'#fff'`
| [`borderWidth`](#styling) | `number` | Yes | Yes | `2`
| [`data`](#data-structure) | `number[]` | - | - | **required**
| [`hoverBackgroundColor`](#interations) | [`Color`](../general/colors.md) | Yes | Yes | `undefined`
| [`hoverBorderColor`](#interactions) | [`Color`](../general/colors.md) | Yes | Yes | `undefined`
| [`hoverBorderWidth`](#interactions) | `number` | Yes | Yes | `undefined`
| [`weight`](#styling) | `number` | - | - | `1`
### Styling
The style of each arc can be controlled with the following properties:
| Name | Description
| ---- | ----
| `backgroundColor` | arc background color.
| `borderColor` | arc border color.
| `borderWidth` | arc border width (in pixels).
| `weight` | The relative thickness of the dataset. Providing a value for weight will cause the pie or doughnut dataset to be drawn with a thickness relative to the sum of all the dataset weight values.
All these values, if `undefined`, fallback to the associated [`elements.arc.*`](../configuration/elements.md#arc-configuration) options.
### Border Alignment
The following values are supported for `borderAlign`.
* `'center'` (default)
* `'inner'`
When `'center'` is set, the borders of arcs next to each other will overlap. When `'inner'` is set, it is guaranteed that all borders will not overlap.
### Interactions
The interaction with each arc can be controlled with the following properties:
| Name | Description
| ---- | -----------
| `hoverBackgroundColor` | arc background color when hovered.
| `hoverBorderColor` | arc border color when hovered.
| `hoverBorderWidth` | arc border width when hovered (in pixels).
All these values, if `undefined`, fallback to the associated [`elements.arc.*`](../configuration/elements.md#arc-configuration) options.
## Config Options
These are the customisation options specific to Pie & Doughnut charts. These options are merged with the global chart configuration options, and form the options of the chart.
| Name | Type | Default | Description
| ---- | ---- | ------- | -----------
| `cutoutPercentage` | `number` | `50` - for doughnut, `0` - for pie | The percentage of the chart that is cut out of the middle.
| `rotation` | `number` | `-0.5 * Math.PI` | Starting angle to draw arcs from.
| `circumference` | `number` | `2 * Math.PI` | Sweep to allow arcs to cover.
| `animation.animateRotate` | `boolean` | `true` | If true, the chart will animate in with a rotation animation. This property is in the `options.animation` object.
| `animation.animateScale` | `boolean` | `false` | If true, will animate scaling the chart from the center outwards.
## Default Options
We can also change these default values for each Doughnut type that is created, this object is available at `Chart.defaults.doughnut`. Pie charts also have a clone of these defaults available to change at `Chart.defaults.pie`, with the only difference being `cutoutPercentage` being set to 0.
## Data Structure
For a pie chart, datasets need to contain an array of data points. The data points should be a number, Chart.js will total all of the numbers and calculate the relative proportion of each.
You also need to specify an array of labels so that tooltips appear correctly.
```javascript
data = {
datasets: [{
data: [10, 20, 30]
}],
// These labels appear in the legend and in the tooltips when hovering different arcs
labels: [
'Red',
'Yellow',
'Blue'
]
};
```

View File

@@ -0,0 +1,220 @@
# 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.
{% chartjs %}
{
"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": {
}
}
{% endchartjs %}
## Example Usage
```javascript
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.
| Name | Type | [Scriptable](../general/options.md#scriptable-options) | [Indexable](../general/options.md#indexable-options) | Default
| ---- | ---- | :----: | :----: | ----
| [`backgroundColor`](#line-styling) | [`Color`](../general/colors.md) | Yes | - | `'rgba(0, 0, 0, 0.1)'`
| [`borderCapStyle`](#line-styling) | `string` | Yes | - | `'butt'`
| [`borderColor`](#line-styling) | [`Color`](../general/colors.md) | Yes | - | `'rgba(0, 0, 0, 0.1)'`
| [`borderDash`](#line-styling) | `number[]` | Yes | - | `[]`
| [`borderDashOffset`](#line-styling) | `number` | Yes | - | `0.0`
| [`borderJoinStyle`](#line-styling) | `string` | Yes | - | `'miter'`
| [`borderWidth`](#line-styling) | `number` | Yes | - | `3`
| [`cubicInterpolationMode`](#cubicinterpolationmode) | `string` | Yes | - | `'default'`
| [`clip`](#line-styling) | <code>number&#124;object</code> | - | - | `borderWidth / 2`
| [`fill`](#line-styling) | <code>boolean&#124;string</code> | Yes | - | `true`
| [`hoverBackgroundColor`](#line-styling) | [`Color`](../general/colors.md) | Yes | - | `undefined`
| [`hoverBorderCapStyle`](#line-styling) | `string` | Yes | - | `undefined`
| [`hoverBorderColor`](#line-styling) | [`Color`](../general/colors.md) | Yes | - | `undefined`
| [`hoverBorderDash`](#line-styling) | `number[]` | Yes | - | `undefined`
| [`hoverBorderDashOffset`](#line-styling) | `number` | Yes | - | `undefined`
| [`hoverBorderJoinStyle`](#line-styling) | `string` | Yes | - | `undefined`
| [`hoverBorderWidth`](#line-styling) | `number` | Yes | - | `undefined`
| [`label`](#general) | `string` | - | - | `''`
| [`lineTension`](#line-styling) | `number` | - | - | `0.4`
| [`order`](#general) | `number` | - | - | `0`
| [`pointBackgroundColor`](#point-styling) | `Color` | Yes | Yes | `'rgba(0, 0, 0, 0.1)'`
| [`pointBorderColor`](#point-styling) | `Color` | Yes | Yes | `'rgba(0, 0, 0, 0.1)'`
| [`pointBorderWidth`](#point-styling) | `number` | Yes | Yes | `1`
| [`pointHitRadius`](#point-styling) | `number` | Yes | Yes | `1`
| [`pointHoverBackgroundColor`](#interactions) | `Color` | Yes | Yes | `undefined`
| [`pointHoverBorderColor`](#interactions) | `Color` | Yes | Yes | `undefined`
| [`pointHoverBorderWidth`](#interactions) | `number` | Yes | Yes | `1`
| [`pointHoverRadius`](#interactions) | `number` | Yes | Yes | `4`
| [`pointRadius`](#point-styling) | `number` | Yes | Yes | `3`
| [`pointRotation`](#point-styling) | `number` | Yes | Yes | `0`
| [`pointStyle`](#point-styling) | <code>string&#124;Image</code> | Yes | Yes | `'circle'`
| [`showLine`](#line-styling) | `boolean` | - | - | `undefined`
| [`spanGaps`](#line-styling) | `boolean` | - | - | `undefined`
| [`steppedLine`](#stepped-line) | <code>boolean&#124;string</code> | - | - | `false`
| [`xAxisID`](#general) | `string` | - | - | first x axis
| [`yAxisID`](#general) | `string` | - | - | first y axis
### General
| Name | Description
| ---- | ----
| `label` | The label for the dataset which appears in the legend and tooltips.
| `order` | The drawing order of dataset. Also affects order for stacking, tooltip, and legend.
| `xAxisID` | The ID of the x axis to plot this dataset on.
| `yAxisID` | The ID of the y axis to plot this dataset on.
### Point Styling
The style of each point can be controlled with the following properties:
| Name | Description
| ---- | ----
| `pointBackgroundColor` | The fill color for points.
| `pointBorderColor` | The border color for points.
| `pointBorderWidth` | The width of the point border in pixels.
| `pointHitRadius` | The pixel size of the non-displayed point that reacts to mouse events.
| `pointRadius` | The radius of the point shape. If set to 0, the point is not rendered.
| `pointRotation` | The rotation of the point in degrees.
| `pointStyle` | Style of the point. [more...](../configuration/elements.md#point-styles)
All these values, if `undefined`, fallback first to the dataset options then to the associated [`elements.point.*`](../configuration/elements.md#point-configuration) options.
### Line Styling
The style of the line can be controlled with the following properties:
| Name | Description
| ---- | ----
| `backgroundColor` | The line fill color.
| `borderCapStyle` | Cap style of the line. See [MDN](https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/lineCap).
| `borderColor` | The line color.
| `borderDash` | Length and spacing of dashes. See [MDN](https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/setLineDash).
| `borderDashOffset` | Offset for line dashes. See [MDN](https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/lineDashOffset).
| `borderJoinStyle` | Line joint style. See [MDN](https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/lineJoin).
| `borderWidth` | The line width (in pixels).
| `clip` | How to clip relative to chartArea. Positive value allows overflow, negative value clips that many pixels inside chartArea. `0` = clip at chartArea. Clipping can also be configured per side: `clip: {left: 5, top: false, right: -2, bottom: 0}`
| `fill` | How to fill the area under the line. See [area charts](area.md).
| `lineTension` | Bezier curve tension of the line. Set to 0 to draw straightlines. This option is ignored if monotone cubic interpolation is used.
| `showLine` | If false, the line is not drawn for this dataset.
| `spanGaps` | 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.
If the value is `undefined`, `showLine` and `spanGaps` fallback to the associated [chart configuration options](#configuration-options). The rest of the values fallback to the associated [`elements.line.*`](../configuration/elements.md#line-configuration) options.
### Interactions
The interaction with each point can be controlled with the following properties:
| Name | Description
| ---- | -----------
| `pointHoverBackgroundColor` | Point background color when hovered.
| `pointHoverBorderColor` | Point border color when hovered.
| `pointHoverBorderWidth` | Border width of point when hovered.
| `pointHoverRadius` | The radius of the point when hovered.
### 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
* `'middle'`: Step-middle 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:
```javascript
Chart.defaults.line.spanGaps = true;
```
## Data Structure
The `data` property of a dataset for a line chart can be passed in two formats.
### number[]
```javascript
data: [20, 10]
```
When the `data` array is an array of numbers, the x axis is generally a [category](../axes/cartesian/category.md#category-cartesian-axis). 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[]
```javascript
data: [{
x: 10,
y: 20
}, {
x: 15,
y: 10
}]
```
This alternate is used for sparse datasets, such as those in [scatter charts](./scatter.md#scatter-chart). 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.
```javascript
var stackedLine = new Chart(ctx, {
type: 'line',
data: data,
options: {
scales: {
yAxes: [{
stacked: true
}]
}
}
});
```

View File

@@ -0,0 +1,98 @@
# Mixed Chart Types
With Chart.js, it is possible to create mixed charts that are a combination of two or more different chart types. A common example is a bar chart that also includes a line dataset.
Creating a mixed chart starts with the initialization of a basic chart.
```javascript
var myChart = new Chart(ctx, {
type: 'bar',
data: data,
options: options
});
```
At this point we have a standard bar chart. Now we need to convert one of the datasets to a line dataset.
```javascript
var mixedChart = new Chart(ctx, {
type: 'bar',
data: {
datasets: [{
label: 'Bar Dataset',
data: [10, 20, 30, 40]
}, {
label: 'Line Dataset',
data: [50, 50, 50, 50],
// Changes this dataset to become a line
type: 'line'
}],
labels: ['January', 'February', 'March', 'April']
},
options: options
});
```
At this point we have a chart rendering how we'd like. It's important to note that the default options for a line chart are not merged in this case. Only the options for the default type are merged in. In this case, that means that the default options for a bar chart are merged because that is the type specified by the `type` field.
{% chartjs %}
{
"type": "bar",
"data": {
"labels": [
"January",
"February",
"March",
"April"
],
"datasets": [{
"label": "Bar Dataset",
"data": [10, 20, 30, 40],
"borderColor": "rgb(255, 99, 132)",
"backgroundColor": "rgba(255, 99, 132, 0.2)"
}, {
"label": "Line Dataset",
"data": [50, 50, 50, 50],
"type": "line",
"fill": false,
"borderColor": "rgb(54, 162, 235)"
}]
},
"options": {
"scales": {
"yAxes": [{
"ticks": {
"beginAtZero": true
}
}]
}
}
}
{% endchartjs %}
## Drawing order
By default, datasets are drawn so that first one is top-most. This can be altered by specifying `order` option to datasets. `order` defaults to `0`.
```javascript
var mixedChart = new Chart(ctx, {
type: 'bar',
data: {
datasets: [{
label: 'Bar Dataset',
data: [10, 20, 30, 40],
// this dataset is drawn below
order: 1
}, {
label: 'Line Dataset',
data: [10, 10, 10, 10],
type: 'line',
// this dataset is drawn on top
order: 2
}],
labels: ['January', 'February', 'March', 'April']
},
options: options
});
```

View File

@@ -0,0 +1,129 @@
# Polar Area
Polar area charts are similar to pie charts, but each segment has the same angle - the radius of the segment differs depending on the value.
This type of chart is often useful when we want to show a comparison data similar to a pie chart, but also show a scale of values for context.
{% chartjs %}
{
"type": "polarArea",
"data": {
"labels": [
"Red",
"Green",
"Yellow",
"Grey",
"Blue"
],
"datasets": [{
"label": "My First Dataset",
"data": [11, 16, 7, 3, 14],
"backgroundColor": [
"rgb(255, 99, 132)",
"rgb(75, 192, 192)",
"rgb(255, 205, 86)",
"rgb(201, 203, 207)",
"rgb(54, 162, 235)"
]
}]
}
}
{% endchartjs %}
## Example Usage
```javascript
new Chart(ctx, {
data: data,
type: 'polarArea',
options: options
});
```
## Dataset Properties
The following options can be included in a polar area chart dataset to configure options for that specific dataset.
| Name | Type | [Scriptable](../general/options.md#scriptable-options) | [Indexable](../general/options.md#indexable-options) | Default
| ---- | ---- | :----: | :----: | ----
| [`backgroundColor`](#styling) | [`Color`](../general/colors.md) | Yes | Yes | `'rgba(0, 0, 0, 0.1)'`
| [`borderAlign`](#border-alignment) | `string` | Yes | Yes | `'center'`
| [`borderColor`](#styling) | [`Color`](../general/colors.md) | Yes | Yes | `'#fff'`
| [`borderWidth`](#styling) | `number` | Yes | Yes | `2`
| [`data`](#data-structure) | `number[]` | - | - | **required**
| [`hoverBackgroundColor`](#interations) | [`Color`](../general/colors.md) | Yes | Yes | `undefined`
| [`hoverBorderColor`](#interactions) | [`Color`](../general/colors.md) | Yes | Yes | `undefined`
| [`hoverBorderWidth`](#interactions) | `number` | Yes | Yes | `undefined`
### Styling
The style of each arc can be controlled with the following properties:
| Name | Description
| ---- | ----
| `backgroundColor` | arc background color.
| `borderColor` | arc border color.
| `borderWidth` | arc border width (in pixels).
All these values, if `undefined`, fallback to the associated [`elements.arc.*`](../configuration/elements.md#arc-configuration) options.
### Border Alignment
The following values are supported for `borderAlign`.
* `'center'` (default)
* `'inner'`
When `'center'` is set, the borders of arcs next to each other will overlap. When `'inner'` is set, it is guaranteed that all the borders are not overlap.
### Interactions
The interaction with each arc can be controlled with the following properties:
| Name | Description
| ---- | -----------
| `hoverBackgroundColor` | arc background color when hovered.
| `hoverBorderColor` | arc border color when hovered.
| `hoverBorderWidth` | arc border width when hovered (in pixels).
All these values, if `undefined`, fallback to the associated [`elements.arc.*`](../configuration/elements.md#arc-configuration) options.
## Config Options
These are the customisation options specific to Polar Area charts. These options are merged with the [global chart default options](#default-options), and form the options of the chart.
| Name | Type | Default | Description
| ---- | ---- | ------- | -----------
| `startAngle` | `number` | `-0.5 * Math.PI` | Starting angle to draw arcs for the first item in a dataset.
| `animation.animateRotate` | `boolean` | `true` | If true, the chart will animate in with a rotation animation. This property is in the `options.animation` object.
| `animation.animateScale` | `boolean` | `true` | If true, will animate scaling the chart from the center outwards.
## Default Options
We can also change these defaults values for each PolarArea type that is created, this object is available at `Chart.defaults.polarArea`. Changing the global options only affects charts created after the change. Existing charts are not changed.
For example, to configure all new polar area charts with `animateScale = false` you would do:
```javascript
Chart.defaults.polarArea.animation.animateScale = false;
```
## Data Structure
For a polar area chart, datasets need to contain an array of data points. The data points should be a number, Chart.js will total all of the numbers and calculate the relative proportion of each.
You also need to specify an array of labels so that tooltips appear correctly for each slice.
```javascript
data = {
datasets: [{
data: [10, 20, 30]
}],
// These labels appear in the legend and in the tooltips when hovering different arcs
labels: [
'Red',
'Yellow',
'Blue'
]
};
```

View File

@@ -0,0 +1,202 @@
# Radar
A radar chart is a way of showing multiple data points and the variation between them.
They are often useful for comparing the points of two or more different data sets.
{% chartjs %}
{
"type": "radar",
"data": {
"labels": [
"Eating",
"Drinking",
"Sleeping",
"Designing",
"Coding",
"Cycling",
"Running"
],
"datasets": [{
"label": "My First Dataset",
"data": [65, 59, 90, 81, 56, 55, 40],
"fill": true,
"backgroundColor": "rgba(255, 99, 132, 0.2)",
"borderColor": "rgb(255, 99, 132)",
"pointBackgroundColor": "rgb(255, 99, 132)",
"pointBorderColor": "#fff",
"pointHoverBackgroundColor": "#fff",
"pointHoverBorderColor": "rgb(255, 99, 132)",
"fill": true
}, {
"label": "My Second Dataset",
"data": [28, 48, 40, 19, 96, 27, 100],
"fill": true,
"backgroundColor": "rgba(54, 162, 235, 0.2)",
"borderColor": "rgb(54, 162, 235)",
"pointBackgroundColor": "rgb(54, 162, 235)",
"pointBorderColor": "#fff",
"pointHoverBackgroundColor": "#fff",
"pointHoverBorderColor": "rgb(54, 162, 235)",
"fill": true
}]
},
"options": {
"elements": {
"line": {
"tension": 0,
"borderWidth": 3
}
}
}
}
{% endchartjs %}
## Example Usage
```javascript
var myRadarChart = new Chart(ctx, {
type: 'radar',
data: data,
options: options
});
```
## Dataset Properties
The radar chart allows a number of properties to be specified for each dataset. These are used to set display properties for a specific dataset. For example, the colour of a line is generally set this way.
| Name | Type | [Scriptable](../general/options.md#scriptable-options) | [Indexable](../general/options.md#indexable-options) | Default
| ---- | ---- | :----: | :----: | ----
| [`backgroundColor`](#line-styling) | [`Color`](../general/colors.md) | Yes | - | `'rgba(0, 0, 0, 0.1)'`
| [`borderCapStyle`](#line-styling) | `string` | Yes | - | `'butt'`
| [`borderColor`](#line-styling) | [`Color`](../general/colors.md) | Yes | - | `'rgba(0, 0, 0, 0.1)'`
| [`borderDash`](#line-styling) | `number[]` | Yes | - | `[]`
| [`borderDashOffset`](#line-styling) | `number` | Yes | - | `0.0`
| [`borderJoinStyle`](#line-styling) | `string` | Yes | - | `'miter'`
| [`borderWidth`](#line-styling) | `number` | Yes | - | `3`
| [`hoverBackgroundColor`](#line-styling) | [`Color`](../general/colors.md) | Yes | - | `undefined`
| [`hoverBorderCapStyle`](#line-styling) | `string` | Yes | - | `undefined`
| [`hoverBorderColor`](#line-styling) | [`Color`](../general/colors.md) | Yes | - | `undefined`
| [`hoverBorderDash`](#line-styling) | `number[]` | Yes | - | `undefined`
| [`hoverBorderDashOffset`](#line-styling) | `number` | Yes | - | `undefined`
| [`hoverBorderJoinStyle`](#line-styling) | `string` | Yes | - | `undefined`
| [`hoverBorderWidth`](#line-styling) | `number` | Yes | - | `undefined`
| [`fill`](#line-styling) | <code>boolean&#124;string</code> | Yes | - | `true`
| [`label`](#general) | `string` | - | - | `''`
| [`order`](#general) | `number` | - | - | `0`
| [`lineTension`](#line-styling) | `number` | - | - | `0`
| [`pointBackgroundColor`](#point-styling) | `Color` | Yes | Yes | `'rgba(0, 0, 0, 0.1)'`
| [`pointBorderColor`](#point-styling) | `Color` | Yes | Yes | `'rgba(0, 0, 0, 0.1)'`
| [`pointBorderWidth`](#point-styling) | `number` | Yes | Yes | `1`
| [`pointHitRadius`](#point-styling) | `number` | Yes | Yes | `1`
| [`pointHoverBackgroundColor`](#interactions) | `Color` | Yes | Yes | `undefined`
| [`pointHoverBorderColor`](#interactions) | `Color` | Yes | Yes | `undefined`
| [`pointHoverBorderWidth`](#interactions) | `number` | Yes | Yes | `1`
| [`pointHoverRadius`](#interactions) | `number` | Yes | Yes | `4`
| [`pointRadius`](#point-styling) | `number` | Yes | Yes | `3`
| [`pointRotation`](#point-styling) | `number` | Yes | Yes | `0`
| [`pointStyle`](#point-styling) | <code>string&#124;Image</code> | Yes | Yes | `'circle'`
| [`spanGaps`](#line-styling) | `boolean` | - | - | `undefined`
### General
| Name | Description
| ---- | ----
| `label` | The label for the dataset which appears in the legend and tooltips.
| `order` | The drawing order of dataset.
### Point Styling
The style of each point can be controlled with the following properties:
| Name | Description
| ---- | ----
| `pointBackgroundColor` | The fill color for points.
| `pointBorderColor` | The border color for points.
| `pointBorderWidth` | The width of the point border in pixels.
| `pointHitRadius` | The pixel size of the non-displayed point that reacts to mouse events.
| `pointRadius` | The radius of the point shape. If set to 0, the point is not rendered.
| `pointRotation` | The rotation of the point in degrees.
| `pointStyle` | Style of the point. [more...](../configuration/elements#point-styles)
All these values, if `undefined`, fallback first to the dataset options then to the associated [`elements.point.*`](../configuration/elements.md#point-configuration) options.
### Line Styling
The style of the line can be controlled with the following properties:
| Name | Description
| ---- | ----
| `backgroundColor` | The line fill color.
| `borderCapStyle` | Cap style of the line. See [MDN](https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/lineCap).
| `borderColor` | The line color.
| `borderDash` | Length and spacing of dashes. See [MDN](https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/setLineDash).
| `borderDashOffset` | Offset for line dashes. See [MDN](https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/lineDashOffset).
| `borderJoinStyle` | Line joint style. See [MDN](https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/lineJoin).
| `borderWidth` | The line width (in pixels).
| `fill` | How to fill the area under the line. See [area charts](area.md).
| `lineTension` | Bezier curve tension of the line. Set to 0 to draw straightlines.
| `spanGaps` | 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.
If the value is `undefined`, `spanGaps` fallback to the associated [chart configuration options](#configuration-options). The rest of the values fallback to the associated [`elements.line.*`](../configuration/elements.md#line-configuration) options.
### Interactions
The interaction with each point can be controlled with the following properties:
| Name | Description
| ---- | -----------
| `pointHoverBackgroundColor` | Point background color when hovered.
| `pointHoverBorderColor` | Point border color when hovered.
| `pointHoverBorderWidth` | Border width of point when hovered.
| `pointHoverRadius` | The radius of the point when hovered.
## Configuration Options
The radar 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
| ---- | ---- | ------- | -----------
| `spanGaps` | `boolean` | `false` | If false, NaN data causes a break in the line.
## Scale Options
The radar chart supports only a single scale. The options for this scale are defined in the `scale` property.
The options for this scale are defined in the `scale` property, which can be referenced from the [Linear Radial Axis page](../axes/radial/linear).
```javascript
options = {
scale: {
angleLines: {
display: false
},
ticks: {
suggestedMin: 50,
suggestedMax: 100
}
}
};
```
## Default Options
It is common to want to apply a configuration setting to all created radar charts. The global radar chart settings are stored in `Chart.defaults.radar`. Changing the global options only affects charts created after the change. Existing charts are not changed.
## Data Structure
The `data` property of a dataset for a radar chart is specified as an array of numbers. Each point in the data array corresponds to the label at the same index.
```javascript
data: [20, 10]
```
For a radar chart, to provide context of what each point means, we include an array of strings that show around each point in the chart.
```javascript
data: {
labels: ['Running', 'Swimming', 'Eating', 'Cycling'],
datasets: [{
data: [20, 10, 4, 2]
}]
}
```

View File

@@ -0,0 +1,50 @@
# Scatter Chart
Scatter charts are based on basic line charts with the x axis changed to a linear axis. To use a scatter chart, data must be passed as objects containing X and Y properties. The example below creates a scatter chart with 3 points.
```javascript
var scatterChart = new Chart(ctx, {
type: 'scatter',
data: {
datasets: [{
label: 'Scatter Dataset',
data: [{
x: -10,
y: 0
}, {
x: 0,
y: 10
}, {
x: 10,
y: 5
}]
}]
},
options: {
scales: {
xAxes: [{
type: 'linear',
position: 'bottom'
}]
}
}
});
```
## Dataset Properties
The scatter chart supports all of the same properties as the [line chart](./line.md#dataset-properties).
## Data Structure
Unlike the line chart where data can be supplied in two different formats, the scatter chart only accepts data in a point format.
```javascript
data: [{
x: 10,
y: 20
}, {
x: 15,
y: 10
}]
```

View File

@@ -0,0 +1,70 @@
# 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](https://en.wikipedia.org/wiki/Don%27t_repeat_yourself), 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.
```javascript
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'
}
}
});
```
## Dataset Configuration
Options may be configured directly on the dataset. The dataset options can be changed at 3 different levels and are evaluated with the following priority:
- per dataset: dataset.*
- per chart: options.datasets[type].*
- or globally: Chart.defaults.global.datasets[type].*
where type corresponds to the dataset type.
*Note:* dataset options take precedence over element options.
The following example would set the `showLine` option to 'false' for all line datasets except for those overridden by options passed to the dataset on creation.
```javascript
// Do not show lines for all datasets by default
Chart.defaults.global.datasets.line.showLine = false;
// This chart would show a line only for the third dataset
var chart = new Chart(ctx, {
type: 'line',
data: {
datasets: [{
data: [0, 0],
}, {
data: [0, 1]
}, {
data: [1, 0],
showLine: true // overrides the `line` dataset default
}, {
type: 'scatter', // 'line' dataset default does not affect this dataset since it's a 'scatter'
data: [1, 1]
}]
}
});
```

View File

@@ -0,0 +1,97 @@
# 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...](#easing)
| `onProgress` | `function` | `null` | Callback called on each step of an animation. [more...](#animation-callbacks)
| `onComplete` | `function` | `null` | Callback called at the end of an animation. [more...](#animation-callbacks)
## 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](http://robertpenner.com/easing/).
## 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:
```javascript
{
// 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.
```javascript
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](https://github.com/chartjs/Chart.js/blob/master/samples/advanced/progress-bar.html): this sample displays a progress bar showing how far along the animation is.

View File

@@ -0,0 +1,89 @@
# 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](#arc-configuration)**, **[lines](#line-configuration)**, **[points](#point-configuration)**, and **[rectangles](#rectangle-configuration)**. 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:
```javascript
Chart.defaults.global.elements.rectangle.borderWidth = 2;
```
## Point Configuration
Point elements are used to represent the points in a line, radar or bubble chart.
Global point options: `Chart.defaults.global.elements.point`.
| Name | Type | Default | Description
| ---- | ---- | ------- | -----------
| `radius` | `number` | `3` | Point radius.
| [`pointStyle`](#point-styles) | <code>string&#124;Image</code> | `'circle'` | Point style.
| `rotation` | `number` | `0` | Point rotation (in degrees).
| `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](https://developer.mozilla.org/en/docs/Web/API/CanvasRenderingContext2D/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](https://developer.mozilla.org/en/docs/Web/API/CanvasRenderingContext2D/lineCap).
| `borderDash` | `number[]` | `[]` | Line dash. See [MDN](https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/setLineDash).
| `borderDashOffset` | `number` | `0.0` | Line dash offset. See [MDN](https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/lineDashOffset).
| `borderJoinStyle` | `string` | `'miter'` | Line join style. See [MDN](https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/lineJoin).
| `capBezierPoints` | `boolean` | `true` | `true` to keep Bézier control inside the chart, `false` for no restriction.
| `cubicInterpolationMode` | `string` | `'default'` | Interpolation mode to apply. [See more...](../charts/line.md#cubicinterpolationmode)
| `fill` | <code>boolean&#124;string</code> | `true` | How to fill the area under the line. See [area charts](../charts/area.md#filling-modes).
| `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
| ---- | ---- | ------- | -----------
| `angle` - for polar only | `number` | `circumference / (arc count)` | Arc angle to cover.
| `backgroundColor` | `Color` | `'rgba(0, 0, 0, 0.1)'` | Arc fill color.
| `borderAlign` | `string` | `'center'` | Arc stroke alignment.
| `borderColor` | `Color` | `'#fff'` | Arc stroke color.
| `borderWidth`| `number` | `2` | Arc stroke width.

View File

@@ -0,0 +1,29 @@
# 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` | <code>number&#124;object</code> | `0` | The padding to add inside the chart. [more...](#padding)
## 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:
```javascript
let chart = new Chart(ctx, {
type: 'line',
data: data,
options: {
layout: {
padding: {
left: 50,
right: 0,
top: 0,
bottom: 0
}
}
}
});
```

View File

@@ -0,0 +1,185 @@
# Legend Configuration
The chart legend displays data about the datasets that are 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...](#position)
| `align` | `string` | `'center'` | Alignment of the legend. [more...](#align)
| `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.
| `onLeave` | `function` | | A callback that is called when a 'mousemove' event is registered outside of a previously hovered label item.
| `reverse` | `boolean` | `false` | Legend will show datasets in reverse order.
| `labels` | `object` | | See the [Legend Label Configuration](#legend-label-configuration) section below.
| `rtl` | `boolean` | | `true` for rendering the legends from right to left.
| `textDirection` | `string` | canvas' default | This will force the text direction `'rtl'|'ltr` on the canvas for rendering the legend, regardless of the css specified on the canvas
## Position
Position of the legend. Options are:
* `'top'`
* `'left'`
* `'bottom'`
* `'right'`
## Align
Alignment of the legend. Options are:
* `'start'`
* `'center'`
* `'end'`
Defaults to `'center'` for unrecognized values.
## 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](#legend-item-interface) for details.
| `filter` | `function` | `null` | Filters legend items out of the legend. Receives 2 parameters, a [Legend Item](#legend-item-interface) and the chart data.
| `usePointStyle` | `boolean` | `false` | Label style will match corresponding point style (size is based on the mimimum value between boxWidth and fontSize).
## Legend Item Interface
Items passed to the legend `onClick` function are the ones returned from `labels.generateLabels`. These items must implement the following interface.
```javascript
{
// 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: 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 | Image,
// Rotation of the point in degrees (only used if usePointStyle is true)
rotation: number
}
```
## Example
The following example will create a chart with the legend enabled and turn all of the text red in color.
```javascript
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:
```javascript
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.
```javascript
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: {
onClick: newLegendClickHandler
}
}
});
```
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.
```javascript
var chart = new Chart(ctx, {
type: 'line',
data: data,
options: {
legendCallback: function(chart) {
// Return the HTML string here.
}
}
});
```
Note that legendCallback is not called automatically and you must call `generateLegend()` yourself in code when creating a legend using this method.

View File

@@ -0,0 +1,42 @@
# 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...](#position)
| `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` | <code>number&#124;string</code> | `1.2` | Height of an individual line of text. See [MDN](https://developer.mozilla.org/en-US/docs/Web/CSS/line-height).
| `text` | <code>string&#124;string[]</code> | `''` | 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.
```javascript
var chart = new Chart(ctx, {
type: 'line',
data: data,
options: {
title: {
display: true,
text: 'Custom Chart Title'
}
}
});
```

View File

@@ -0,0 +1,378 @@
# Tooltips
## Tooltip Configuration
The tooltip configuration is passed into the `options.tooltips` namespace. The global options for the chart tooltips is defined in `Chart.defaults.global.tooltips`.
| Name | Type | Default | Description
| ---- | ---- | ------- | -----------
| `enabled` | `boolean` | `true` | Are on-canvas tooltips enabled?
| `custom` | `function` | `null` | See [custom tooltip](#external-custom-tooltips) section.
| `mode` | `string` | `'nearest'` | Sets which elements appear in the tooltip. [more...](../general/interactions/modes.md#interaction-modes).
| `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...](#position-modes)
| `callbacks` | `object` | | See the [callbacks section](#tooltip-callbacks).
| `itemSort` | `function` | | Sort tooltip items. [more...](#sort-callback)
| `filter` | `function` | | Filter tooltip items. [more...](#filter-callback)
| `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.
| `titleAlign` | `string` | `'left'` | Horizontal alignment of the title text lines. [more...](#alignment)
| `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.
| `bodyAlign` | `string` | `'left'` | Horizontal alignment of the body text lines. [more...](#alignment)
| `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.
| `footerAlign` | `string` | `'left'` | Horizontal alignment of the footer text lines. [more...](#alignment)
| `footerSpacing` | `number` | `2` | Spacing to add to top and bottom of each footer line.
| `footerMarginTop` | `number` | `6` | Margin to add before drawing the footer.
| `xPadding` | `number` | `6` | Padding to add on left and right of tooltip.
| `yPadding` | `number` | `6` | Padding to add on top and bottom of tooltip.
| `caretPadding` | `number` | `2` | Extra distance to move the end of the tooltip arrow away from the tooltip point.
| `caretSize` | `number` | `5` | Size, in px, of the tooltip arrow.
| `cornerRadius` | `number` | `6` | Radius of tooltip corner curves.
| `multiKeyBackground` | `Color` | `'#fff'` | Color to draw behind the colored boxes when multiple items are in the tooltip.
| `displayColors` | `boolean` | `true` | If true, color boxes are shown in the tooltip.
| `borderColor` | `Color` | `'rgba(0, 0, 0, 0)'` | Color of the border.
| `borderWidth` | `number` | `0` | Size of the border.
| `rtl` | `boolean` | | `true` for rendering the legends from right to left.
| `textDirection` | `string` | canvas' default | This will force the text direction `'rtl'|'ltr` on the canvas for rendering the tooltips, regardless of the css specified on the canvas
### 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:
```javascript
/**
* 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
};
};
```
### Alignment
The `titleAlign`, `bodyAlign` and `footerAlign` options define the horizontal position of the text lines with respect to the tooltip box. The following values are supported.
* `'left'` (default)
* `'right'`
* `'center'`
These options are only applied to text lines. Color boxes are always aligned to the left edge.
### Sort Callback
Allows sorting of [tooltip items](#tooltip-item-interface). Must implement at minimum a function that can be passed to [Array.prototype.sort](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/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](#tooltip-item-interface). Must implement at minimum a function that can be passed to [Array.prototype.filter](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/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](#tooltip-item-interface) 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` | `TooltipItem[], object` | Returns the text to render before the title.
| `title` | `TooltipItem[], object` | Returns text to render as the title of the tooltip.
| `afterTitle` | `TooltipItem[], object` | Returns text to render after the title.
| `beforeBody` | `TooltipItem[], object` | Returns text to render before the body section.
| `beforeLabel` | `TooltipItem, object` | Returns text to render before an individual label. This will be called for each item in the tooltip.
| `label` | `TooltipItem, object` | Returns text to render for an individual item in the tooltip. [more...](#label-callback)
| `labelColor` | `TooltipItem, Chart` | Returns the colors to render for the tooltip item. [more...](#label-color-callback)
| `labelTextColor` | `TooltipItem, Chart` | Returns the colors for the text of the label for the tooltip item.
| `afterLabel` | `TooltipItem, object` | Returns text to render after an individual label.
| `afterBody` | `TooltipItem[], object` | Returns text to render after the body section.
| `beforeFooter` | `TooltipItem[], object` | Returns text to render before the footer section.
| `footer` | `TooltipItem[], object` | Returns text to render as the footer of the tooltip.
| `afterFooter` | `TooltipItem[], object` | Text to render after the footer section.
### Label Callback
The `label` callback can change the text that displays for a given data point. A common example to round data values; the following example rounds the data to two decimal places.
```javascript
var chart = new Chart(ctx, {
type: 'line',
data: data,
options: {
tooltips: {
callbacks: {
label: function(tooltipItem, data) {
var label = data.datasets[tooltipItem.datasetIndex].label || '';
if (label) {
label += ': ';
}
label += Math.round(tooltipItem.yLabel * 100) / 100;
return label;
}
}
}
}
});
```
### Label Color Callback
For example, to return a red box for each item in the tooltip you could do:
```javascript
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.
```javascript
{
// Label for the tooltip
label: string,
// Value for the tooltip
value: string,
// X Value of the tooltip
// (deprecated) use `value` or `label` instead
xLabel: number | string,
// Y value of the tooltip
// (deprecated) use `value` or `label` instead
yLabel: number | 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:
```javascript
var myPieChart = new Chart(ctx, {
type: 'pie',
data: data,
options: {
tooltips: {
// Disable the on-canvas tooltip
enabled: false,
custom: function(tooltipModel) {
// Tooltip Element
var tooltipEl = document.getElementById('chartjs-tooltip');
// Create element on first render
if (!tooltipEl) {
tooltipEl = document.createElement('div');
tooltipEl.id = 'chartjs-tooltip';
tooltipEl.innerHTML = '<table></table>';
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 = '<thead>';
titleLines.forEach(function(title) {
innerHtml += '<tr><th>' + title + '</th></tr>';
});
innerHtml += '</thead><tbody>';
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 = '<span style="' + style + '"></span>';
innerHtml += '<tr><td>' + span + body + '</td></tr>';
});
innerHtml += '</tbody>';
var tableRoot = tooltipEl.querySelector('table');
tableRoot.innerHTML = innerHtml;
}
// `this` will be the overall tooltip
var position = this._chart.canvas.getBoundingClientRect();
// Display, position, and set styles for font
tooltipEl.style.opacity = 1;
tooltipEl.style.position = 'absolute';
tooltipEl.style.left = position.left + window.pageXOffset + tooltipModel.caretX + 'px';
tooltipEl.style.top = position.top + window.pageYOffset + tooltipModel.caretY + 'px';
tooltipEl.style.fontFamily = tooltipModel._bodyFontFamily;
tooltipEl.style.fontSize = tooltipModel.bodyFontSize + 'px';
tooltipEl.style.fontStyle = tooltipModel._bodyFontStyle;
tooltipEl.style.padding = tooltipModel.yPadding + 'px ' + tooltipModel.xPadding + 'px';
tooltipEl.style.pointerEvents = 'none';
}
}
}
});
```
See [samples](https://www.chartjs.org/samples/) for examples on how to get started with custom tooltips.
## Tooltip Model
The tooltip model contains parameters that can be used to render the tooltip.
```javascript
{
// 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,
caretPadding: 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[],
labelTextColors: Color[],
// 0 opacity is a hidden tooltip
opacity: number,
legendColorBackground: Color,
displayColors: boolean,
borderColor: Color,
borderWidth: number
}
```

View File

@@ -0,0 +1,46 @@
# Developers
Developer features allow extending and enhancing Chart.js in many different ways.
## Latest resources
Latest documentation and samples, including unreleased features, are available at:
- https://www.chartjs.org/docs/master/
- https://www.chartjs.org/samples/master/
## Development releases
Latest builds are available for testing at:
- https://www.chartjs.org/dist/master/Chart.min.js
- https://www.chartjs.org/dist/master/Chart.bundle.min.js
> Note: Development builds are currently only available via HTTP, so in order to include them in [JSFiddle](https://jsfiddle.net) or [CodePen](https://codepen.io), you need to access these tools via HTTP as well.
**WARNING: Development builds MUST not be used for production purposes or as replacement for CDN.**
## Browser support
Chart.js offers support for the following browsers:
* Chrome 50+
* Firefox 45+
* Internet Explorer 11
* Edge 14+
* Safari 9+
Browser support for the canvas element is available in all modern & major mobile browsers. [CanIUse](https://caniuse.com/#feat=canvas)
Thanks to [BrowserStack](https://browserstack.com) for allowing our team to test on thousands of browsers.
## Previous versions
Version 2 has a completely different API than earlier versions.
Most earlier version options have current equivalents or are the same.
Please use the documentation that is available on [chartjs.org](https://www.chartjs.org/docs/) for the current version of Chart.js.
Please note - documentation for previous versions are available on the GitHub repo.
- [1.x Documentation](https://github.com/chartjs/Chart.js/tree/v1.1.1/docs)

View File

@@ -0,0 +1,179 @@
# Chart Prototype Methods
For each chart, there are a set of global prototype methods on the shared chart type which you may find useful. These are available on all charts created with Chart.js, but for the examples, let's use a line chart we've made.
```javascript
// For example:
var myLineChart = new Chart(ctx, config);
```
## .destroy()
Use this to destroy any chart instances that are created. This will clean up any references stored to the chart object within Chart.js, along with any associated event listeners attached by Chart.js.
This must be called before the canvas is reused for a new chart.
```javascript
// Destroys a specific chart instance
myLineChart.destroy();
```
## .update(config)
Triggers an update of the chart. This can be safely called after updating the data object. This will update all scales, legends, and then re-render the chart.
```javascript
// duration is the time for the animation of the redraw in milliseconds
// lazy is a boolean. if true, the animation can be interrupted by other animations
myLineChart.data.datasets[0].data[2] = 50; // Would update the first dataset's value of 'March' to be 50
myLineChart.update(); // Calling update now animates the position of March from 90 to 50.
```
> **Note:** replacing the data reference (e.g. `myLineChart.data = {datasets: [...]}` only works starting **version 2.6**. Prior that, replacing the entire data object could be achieved with the following workaround: `myLineChart.config.data = {datasets: [...]}`.
A `config` object can be provided with additional configuration for the update process. This is useful when `update` is manually called inside an event handler and some different animation is desired.
The following properties are supported:
* **duration** (number): Time for the animation of the redraw in milliseconds
* **lazy** (boolean): If true, the animation can be interrupted by other animations
* **easing** (string): The animation easing function. See [Animation Easing](../configuration/animations.md) for possible values.
Example:
```javascript
myChart.update({
duration: 800,
easing: 'easeOutBounce'
});
```
See [Updating Charts](updates.md) for more details.
## .reset()
Reset the chart to it's state before the initial animation. A new animation can then be triggered using `update`.
```javascript
myLineChart.reset();
```
## .render(config)
Triggers a redraw of all chart elements. Note, this does not update elements for new data. Use `.update()` in that case.
See `.update(config)` for more details on the config object.
```javascript
// duration is the time for the animation of the redraw in milliseconds
// lazy is a boolean. if true, the animation can be interrupted by other animations
myLineChart.render({
duration: 800,
lazy: false,
easing: 'easeOutBounce'
});
```
## .stop()
Use this to stop any current animation loop. This will pause the chart during any current animation frame. Call `.render()` to re-animate.
```javascript
// Stops the charts animation loop at its current frame
myLineChart.stop();
// => returns 'this' for chainability
```
## .resize()
Use this to manually resize the canvas element. This is run each time the canvas container is resized, but you can call this method manually if you change the size of the canvas nodes container element.
```javascript
// Resizes & redraws to fill its container element
myLineChart.resize();
// => returns 'this' for chainability
```
## .clear()
Will clear the chart canvas. Used extensively internally between animation frames, but you might find it useful.
```javascript
// Will clear the canvas that myLineChart is drawn on
myLineChart.clear();
// => returns 'this' for chainability
```
## .toBase64Image()
This returns a base 64 encoded string of the chart in it's current state.
```javascript
myLineChart.toBase64Image();
// => returns png data url of the image on the canvas
```
## .generateLegend()
Returns an HTML string of a legend for that chart. The legend is generated from the `legendCallback` in the options.
```javascript
myLineChart.generateLegend();
// => returns HTML string of a legend for this chart
```
## .getElementAtEvent(e)
Calling `getElementAtEvent(event)` on your Chart instance passing an argument of an event, or jQuery event, will return the single element at the event position. If there are multiple items within range, only the first is returned. The value returned from this method is an array with a single parameter. An array is used to keep a consistent API between the `get*AtEvent` methods.
```javascript
myLineChart.getElementAtEvent(e);
// => returns the first element at the event point.
```
To get an item that was clicked on, `getElementAtEvent` can be used.
```javascript
function clickHandler(evt) {
var firstPoint = myChart.getElementAtEvent(evt)[0];
if (firstPoint) {
var label = myChart.data.labels[firstPoint._index];
var value = myChart.data.datasets[firstPoint._datasetIndex].data[firstPoint._index];
}
}
```
## .getElementsAtEvent(e)
Looks for the element under the event point, then returns all elements at the same data index. This is used internally for 'label' mode highlighting.
Calling `getElementsAtEvent(event)` on your Chart instance passing an argument of an event, or jQuery event, will return the point elements that are at that the same position of that event.
```javascript
canvas.onclick = function(evt) {
var activePoints = myLineChart.getElementsAtEvent(evt);
// => activePoints is an array of points on the canvas that are at the same position as the click event.
};
```
This functionality may be useful for implementing DOM based tooltips, or triggering custom behaviour in your application.
## .getDatasetAtEvent(e)
Looks for the element under the event point, then returns all elements from that dataset. This is used internally for 'dataset' mode highlighting.
```javascript
myLineChart.getDatasetAtEvent(e);
// => returns an array of elements
```
## .getDatasetMeta(index)
Looks for the dataset that matches the current index and returns that metadata. This returned data has all of the metadata that is used to construct the chart.
The `data` property of the metadata will contain information about each point, rectangle, etc. depending on the chart type.
Extensive examples of usage are available in the [Chart.js tests](https://github.com/chartjs/Chart.js/tree/master/test).
```javascript
var meta = myChart.getDatasetMeta(0);
var x = meta.data[0]._model.x;
```

View File

@@ -0,0 +1,134 @@
# New Axes
Axes in Chart.js can be individually extended. Axes should always derive from `Chart.Scale` but this is not a mandatory requirement.
```javascript
let MyScale = Chart.Scale.extend({
/* extensions ... */
});
// MyScale is now derived from Chart.Scale
```
Once you have created your scale class, you need to register it with the global chart object so that it can be used. A default config for the scale may be provided when registering the constructor. The first parameter to the register function is a string key that is used later to identify which scale type to use for a chart.
```javascript
Chart.scaleService.registerScaleType('myScale', MyScale, defaultConfigObject);
```
To use the new scale, simply pass in the string key to the config when creating a chart.
```javascript
var lineChart = new Chart(ctx, {
data: data,
type: 'line',
options: {
scales: {
yAxes: [{
type: 'myScale' // this is the same key that was passed to the registerScaleType function
}]
}
}
});
```
## Scale Properties
Scale instances are given the following properties during the fitting process.
```javascript
{
left: number, // left edge of the scale bounding box
right: number, // right edge of the bounding box
top: number,
bottom: number,
width: number, // the same as right - left
height: number, // the same as bottom - top
// Margin on each side. Like css, this is outside the bounding box.
margins: {
left: number,
right: number,
top: number,
bottom: number
},
// Amount of padding on the inside of the bounding box (like CSS)
paddingLeft: number,
paddingRight: number,
paddingTop: number,
paddingBottom: number
}
```
## Scale Interface
To work with Chart.js, custom scale types must implement the following interface.
```javascript
{
// Determines the data limits. Should set this.min and this.max to be the data max/min
determineDataLimits: function() {},
// Generate tick marks. this.chart is the chart instance. The data object can be accessed as this.chart.data
// buildTicks() should create a ticks array on the axis instance, if you intend to use any of the implementations from the base class
buildTicks: function() {},
// Get the value to show for the data at the given index of the the given dataset, ie this.chart.data.datasets[datasetIndex].data[index]
getLabelForIndex: function(index, datasetIndex) {},
// Get the pixel (x coordinate for horizontal axis, y coordinate for vertical axis) for a given value
// @param index: index into the ticks array
getPixelForTick: function(index) {},
// Get the pixel (x coordinate for horizontal axis, y coordinate for vertical axis) for a given value
// @param value : the value to get the pixel for
// @param index : index into the data array of the value
// @param datasetIndex : index of the dataset the value comes from
getPixelForValue: function(value, index, datasetIndex) {},
// Get the value for a given pixel (x coordinate for horizontal axis, y coordinate for vertical axis)
// @param pixel : pixel value
getValueForPixel: function(pixel) {}
}
```
Optionally, the following methods may also be overwritten, but an implementation is already provided by the `Chart.Scale` base class.
```javascript
{
// Transform the ticks array of the scale instance into strings. The default implementation simply calls this.options.ticks.callback(numericalTick, index, ticks);
convertTicksToLabels: function() {},
// Determine how much the labels will rotate by. The default implementation will only rotate labels if the scale is horizontal.
calculateTickRotation: function() {},
// Fits the scale into the canvas.
// this.maxWidth and this.maxHeight will tell you the maximum dimensions the scale instance can be. Scales should endeavour to be as efficient as possible with canvas space.
// this.margins is the amount of space you have on either side of your scale that you may expand in to. This is used already for calculating the best label rotation
// You must set this.minSize to be the size of your scale. It must be an object containing 2 properties: width and height.
// You must set this.width to be the width and this.height to be the height of the scale
fit: function() {},
// Draws the scale onto the canvas. this.(left|right|top|bottom) will have been populated to tell you the area on the canvas to draw in
// @param chartArea : an object containing four properties: left, right, top, bottom. This is the rectangle that lines, bars, etc will be drawn in. It may be used, for example, to draw grid lines.
draw: function(chartArea) {}
}
```
The Core.Scale base class also has some utility functions that you may find useful.
```javascript
{
// Returns true if the scale instance is horizontal
isHorizontal: function() {},
// Get the correct value from the value from this.chart.data.datasets[x].data[]
// If dataValue is an object, returns .x or .y depending on the return of isHorizontal()
// If the value is undefined, returns NaN
// Otherwise returns the value.
// Note that in all cases, the returned value is not guaranteed to be a number
getRightValue: function(dataValue) {},
// Returns the scale tick objects ({label, major})
getTicks: function() {}
}
```

View File

@@ -0,0 +1,116 @@
# New Charts
Chart.js 2.0 introduces the concept of controllers for each dataset. Like scales, new controllers can be written as needed.
```javascript
Chart.controllers.MyType = Chart.DatasetController.extend({
});
// Now we can create a new instance of our chart, using the Chart.js API
new Chart(ctx, {
// this is the string the constructor was registered at, ie Chart.controllers.MyType
type: 'MyType',
data: data,
options: options
});
```
## Dataset Controller Interface
Dataset controllers must implement the following interface.
```javascript
{
// Create elements for each piece of data in the dataset. Store elements in an array on the dataset as dataset.metaData
addElements: function() {},
// Create a single element for the data at the given index and reset its state
addElementAndReset: function(index) {},
// Draw the representation of the dataset
// @param ease : if specified, this number represents how far to transition elements. See the implementation of draw() in any of the provided controllers to see how this should be used
draw: function(ease) {},
// Remove hover styling from the given element
removeHoverStyle: function(element) {},
// Add hover styling to the given element
setHoverStyle: function(element) {},
// Update the elements in response to new data
// @param reset : if true, put the elements into a reset state so they can animate to their final values
update: function(reset) {}
}
```
The following methods may optionally be overridden by derived dataset controllers.
```javascript
{
// Initializes the controller
initialize: function(chart, datasetIndex) {},
// Ensures that the dataset represented by this controller is linked to a scale. Overridden to helpers.noop in the polar area and doughnut controllers as these
// chart types using a single scale
linkScales: function() {},
// Called by the main chart controller when an update is triggered. The default implementation handles the number of data points changing and creating elements appropriately.
buildOrUpdateElements: function() {}
}
```
## Extending Existing Chart Types
Extending or replacing an existing controller type is easy. Simply replace the constructor for one of the built in types with your own.
The built in controller types are:
* `Chart.controllers.line`
* `Chart.controllers.bar`
* `Chart.controllers.radar`
* `Chart.controllers.doughnut`
* `Chart.controllers.polarArea`
* `Chart.controllers.bubble`
For example, to derive a new chart type that extends from a bubble chart, you would do the following.
```javascript
// Sets the default config for 'derivedBubble' to be the same as the bubble defaults.
// We look for the defaults by doing Chart.defaults[chartType]
// It looks like a bug exists when the defaults don't exist
Chart.defaults.derivedBubble = Chart.defaults.bubble;
// I think the recommend using Chart.controllers.bubble.extend({ extensions here });
var custom = Chart.controllers.bubble.extend({
draw: function(ease) {
// Call super method first
Chart.controllers.bubble.prototype.draw.call(this, ease);
// Now we can do some custom drawing for this dataset. Here we'll draw a red box around the first point in each dataset
var meta = this.getMeta();
var pt0 = meta.data[0];
var radius = pt0._view.radius;
var ctx = this.chart.chart.ctx;
ctx.save();
ctx.strokeStyle = 'red';
ctx.lineWidth = 1;
ctx.strokeRect(pt0._view.x - radius, pt0._view.y - radius, 2 * radius, 2 * radius);
ctx.restore();
}
});
// Stores the controller so that the chart initialization routine can look it up with
// Chart.controllers[type]
Chart.controllers.derivedBubble = custom;
// Now we can create and use our new chart type
new Chart(ctx, {
type: 'derivedBubble',
data: data,
options: options
});
```
### Bar Controller
The bar controller has a special property that you should be aware of. To correctly calculate the width of a bar, the controller must determine the number of datasets that map to bars. To do this, the bar controller attaches a property `bar` to the dataset during initialization. If you are creating a replacement or updated bar controller, you should do the same. This will ensure that charts with regular bars and your new derived bars will work seamlessly.

View File

@@ -0,0 +1,77 @@
# Contributing
New contributions to the library are welcome, but we ask that you please follow these guidelines:
- Before opening a PR for major additions or changes, please discuss the expected API and/or implementation by [filing an issue](https://github.com/chartjs/Chart.js/issues) or asking about it in the [Chart.js Slack](https://chartjs-slack.herokuapp.com/) #dev channel. This will save you development time by getting feedback upfront and make review faster by giving the maintainers more context and details.
- Consider whether your changes are useful for all users, or if creating a Chart.js [plugin](plugins.md) would be more appropriate.
- Check that your code will pass tests and `eslint` code standards. `gulp test` will run both the linter and tests for you.
- Add unit tests and document new functionality (in the `test/` and `docs/` directories respectively).
- Avoid breaking changes unless there is an upcoming major release, which are infrequent. We encourage people to write plugins for most new advanced features, and care a lot about backwards compatibility.
- We strongly prefer new methods to be added as private whenever possible. A method can be made private either by making a top-level `function` outside of a class or by prefixing it with `_` and adding `@private` JSDoc if inside a class. Public APIs take considerable time to review and become locked once implemented as we have limited ability to change them without breaking backwards compatibility. Private APIs allow the flexibility to address unforeseen cases.
## Joining the project
Active committers and contributors are invited to introduce yourself and request commit access to this project. We have a very active Slack community that you can join [here](https://chartjs-slack.herokuapp.com/). If you think you can help, we'd love to have you!
## Building and Testing
Chart.js uses <a href="https://gulpjs.com/" target="_blank">gulp</a> to build the library into a single JavaScript file.
Firstly, we need to ensure development dependencies are installed. With node and npm installed, after cloning the Chart.js repo to a local directory, and navigating to that directory in the command line, we can run the following:
```bash
> npm install
> npm install -g gulp-cli
```
This will install the local development dependencies for Chart.js, along with a CLI for the JavaScript task runner <a href="https://gulpjs.com/" target="_blank">gulp</a>.
The following commands are now available from the repository root:
```bash
> gulp build // build dist files in ./dist
> gulp build --watch // build and watch for changes
> gulp unittest // run tests from ./test/specs
> gulp unittest --watch // run tests and watch for source changes
> gulp unittest --coverage // run tests and generate coverage reports in ./coverage
> gulp lint // perform code linting (ESLint)
> gulp test // perform code linting and run unit tests
> gulp docs // build the documentation in ./dist/docs
> gulp docs --watch // starts the gitbook live reloaded server
```
More information can be found in [gulpfile.js](https://github.com/chartjs/Chart.js/blob/master/gulpfile.js).
### Image-Based Tests
Some display-related functionality is difficult to test via typical Jasmine units. For this reason, we introduced image-based tests ([#3988](https://github.com/chartjs/Chart.js/pull/3988) and [#5777](https://github.com/chartjs/Chart.js/pull/5777)) to assert that a chart is drawn pixel-for-pixel matching an expected image.
Generated charts in image-based tests should be **as minimal as possible** and focus only on the tested feature to prevent failure if another feature breaks (e.g. disable the title and legend when testing scales).
You can create a new image-based test by following the steps below:
- Create a JS file ([example](https://github.com/chartjs/Chart.js/blob/f7b671006a86201808402c3b6fe2054fe834fd4a/test/fixtures/controller.bubble/radius-scriptable.js)) or JSON file ([example](https://github.com/chartjs/Chart.js/blob/4b421a50bfa17f73ac7aa8db7d077e674dbc148d/test/fixtures/plugin.filler/fill-line-dataset.json)) that defines chart config and generation options.
- Add this file in `test/fixtures/{spec.name}/{feature-name}.json`.
- Add a [describe line](https://github.com/chartjs/Chart.js/blob/4b421a50bfa17f73ac7aa8db7d077e674dbc148d/test/specs/plugin.filler.tests.js#L10) to the beginning of `test/specs/{spec.name}.tests.js` if it doesn't exist yet.
- Run `gulp unittest --watch --inputs=test/specs/{spec.name}.tests.js`.
- Click the *"Debug"* button (top/right): a test should fail with the associated canvas visible.
- Right click on the chart and *"Save image as..."* `test/fixtures/{spec.name}/{feature-name}.png` making sure not to activate the tooltip or any hover functionality
- Refresh the browser page (`CTRL+R`): test should now pass
- Verify test relevancy by changing the feature values *slightly* in the JSON file.
Tests should pass in both browsers. In general, we've hidden all text in image tests since it's quite difficult to get them passing between different browsers. As a result, it is recommended to hide all scales in image-based tests. It is also recommended to disable animations. If tests still do not pass, adjust [`tolerance` and/or `threshold`](https://github.com/chartjs/Chart.js/blob/1ca0ffb5d5b6c2072176fd36fa85a58c483aa434/test/jasmine.matchers.js) at the beginning of the JSON file keeping them **as low as possible**.
When a test fails, the expected and actual images are shown. If you'd like to see the images even when the tests pass, set `"debug": true` in the JSON file.
## Bugs and Issues
Please report these on the GitHub page - at <a href="https://github.com/chartjs/Chart.js" target="_blank">github.com/chartjs/Chart.js</a>. Please do not use issues for support requests. For help using Chart.js, please take a look at the [`chartjs`](https://stackoverflow.com/questions/tagged/chartjs) tag on Stack Overflow.
Well structured, detailed bug reports are hugely valuable for the project.
Guidelines for reporting bugs:
- Check the issue search to see if it has already been reported
- Isolate the problem to a simple test case
- Please include a demonstration of the bug on a website such as [JS Bin](https://jsbin.com/), [JS Fiddle](https://jsfiddle.net/), or [Codepen](https://codepen.io/pen/). ([Template](https://codepen.io/pen?template=JXVYzq)). If filing a bug against `master`, you may reference the latest code via https://www.chartjs.org/dist/master/Chart.min.js (changing the filename to point at the file you need as appropriate). Do not rely on these files for production purposes as they may be removed at any time.
Please provide any additional details associated with the bug, if it's browser or screen density specific, or only happens with a certain configuration or data.

View File

@@ -0,0 +1,132 @@
# Plugins
Plugins are the most efficient way to customize or change the default behavior of a chart. They have been introduced at [version 2.1.0](https://github.com/chartjs/Chart.js/releases/tag/2.1.0) (global plugins only) and extended at [version 2.5.0](https://github.com/chartjs/Chart.js/releases/tag/v2.5.0) (per chart plugins and options).
## Using plugins
Plugins can be shared between chart instances:
```javascript
var plugin = { /* plugin implementation */ };
// chart1 and chart2 use "plugin"
var chart1 = new Chart(ctx, {
plugins: [plugin]
});
var chart2 = new Chart(ctx, {
plugins: [plugin]
});
// chart3 doesn't use "plugin"
var chart3 = new Chart(ctx, {});
```
Plugins can also be defined directly in the chart `plugins` config (a.k.a. *inline plugins*):
```javascript
var chart = new Chart(ctx, {
plugins: [{
beforeInit: function(chart, options) {
//..
}
}]
});
```
However, this approach is not ideal when the customization needs to apply to many charts.
## Global plugins
Plugins can be registered globally to be applied on all charts (a.k.a. *global plugins*):
```javascript
Chart.plugins.register({
// plugin implementation
});
```
> Note: *inline* plugins can't be registered globally.
## Configuration
### Plugin ID
Plugins must define a unique id in order to be configurable.
This id should follow the [npm package name convention](https://docs.npmjs.com/files/package.json#name):
- can't start with a dot or an underscore
- can't contain any non-URL-safe characters
- can't contain uppercase letters
- should be something short, but also reasonably descriptive
If a plugin is intended to be released publicly, you may want to check the [registry](https://www.npmjs.com/search?q=chartjs-plugin-) to see if there's something by that name already. Note that in this case, the package name should be prefixed by `chartjs-plugin-` to appear in Chart.js plugin registry.
### Plugin options
Plugin options are located under the `options.plugins` config and are scoped by the plugin ID: `options.plugins.{plugin-id}`.
```javascript
var chart = new Chart(ctx, {
options: {
foo: { ... }, // chart 'foo' option
plugins: {
p1: {
foo: { ... }, // p1 plugin 'foo' option
bar: { ... }
},
p2: {
foo: { ... }, // p2 plugin 'foo' option
bla: { ... }
}
}
}
});
```
#### Disable plugins
To disable a global plugin for a specific chart instance, the plugin options must be set to `false`:
```javascript
Chart.plugins.register({
id: 'p1',
// ...
});
var chart = new Chart(ctx, {
options: {
plugins: {
p1: false // disable plugin 'p1' for this instance
}
}
});
```
## Plugin Core API
Available hooks (as of version 2.7):
* `beforeInit`
* `afterInit`
* `beforeUpdate` *(cancellable)*
* `afterUpdate`
* `beforeLayout` *(cancellable)*
* `afterLayout`
* `beforeDatasetsUpdate` *(cancellable)*
* `afterDatasetsUpdate`
* `beforeDatasetUpdate` *(cancellable)*
* `afterDatasetUpdate`
* `beforeRender` *(cancellable)*
* `afterRender`
* `beforeDraw` *(cancellable)*
* `afterDraw`
* `beforeDatasetsDraw` *(cancellable)*
* `afterDatasetsDraw`
* `beforeDatasetDraw` *(cancellable)*
* `afterDatasetDraw`
* `beforeEvent` *(cancellable)*
* `afterEvent`
* `resize`
* `destroy`

View File

@@ -0,0 +1,101 @@
# Updating Charts
It's pretty common to want to update charts after they've been created. When the chart data or options are changed, Chart.js will animate to the new data values and options.
## Adding or Removing Data
Adding and removing data is supported by changing the data array. To add data, just add data into the data array as seen in this example.
```javascript
function addData(chart, label, data) {
chart.data.labels.push(label);
chart.data.datasets.forEach((dataset) => {
dataset.data.push(data);
});
chart.update();
}
function removeData(chart) {
chart.data.labels.pop();
chart.data.datasets.forEach((dataset) => {
dataset.data.pop();
});
chart.update();
}
```
## Updating Options
To update the options, mutating the options property in place or passing in a new options object are supported.
- If the options are mutated in place, other option properties would be preserved, including those calculated by Chart.js.
- If created as a new object, it would be like creating a new chart with the options - old options would be discarded.
```javascript
function updateConfigByMutating(chart) {
chart.options.title.text = 'new title';
chart.update();
}
function updateConfigAsNewObject(chart) {
chart.options = {
responsive: true,
title: {
display: true,
text: 'Chart.js'
},
scales: {
xAxes: [{
display: true
}],
yAxes: [{
display: true
}]
}
};
chart.update();
}
```
Scales can be updated separately without changing other options.
To update the scales, pass in an object containing all the customization including those unchanged ones.
Variables referencing any one from `chart.scales` would be lost after updating scales with a new `id` or the changed `type`.
```javascript
function updateScales(chart) {
var xScale = chart.scales['x-axis-0'];
var yScale = chart.scales['y-axis-0'];
chart.options.scales = {
xAxes: [{
id: 'newId',
display: true
}],
yAxes: [{
display: true,
type: 'logarithmic'
}]
};
chart.update();
// need to update the reference
xScale = chart.scales['newId'];
yScale = chart.scales['y-axis-0'];
}
```
You can also update a specific scale either by specifying its index or id.
```javascript
function updateScale(chart) {
chart.options.scales.yAxes[0] = {
type: 'logarithmic'
};
chart.update();
}
```
Code sample for updating options can be found in [toggle-scale-type.html](../../samples/scales/toggle-scale-type.html).
## Preventing Animations
Sometimes when a chart updates, you may not want an animation. To achieve this you can call `update` with a duration of `0`. This will render the chart synchronously and without an animation.

View File

@@ -0,0 +1,11 @@
# General Configuration
These sections describe general configuration options that can apply elsewhere in the documentation.
* [Responsive](./responsive.md) defines responsive chart options that apply to all charts.
* [Device Pixel Ratio](./device-pixel-ratio.md) defines the ratio between display pixels and rendered pixels.
* [Interactions](./interactions/README.md) defines options that reflect how hovering chart elements works.
* [Options](./options.md) scriptable and indexable options syntax.
* [Colors](./colors.md) defines acceptable color values.
* [Font](./fonts.md) defines various font options.
* [Performance](./performance.md) gives tips for performance-sensitive applications.

View File

@@ -0,0 +1,39 @@
# Accessible Charts
Chart.js charts are rendered on user provided `canvas` elements. Thus, it is up to the user to create the `canvas` element in a way that is accessible. The `canvas` element has support in all browsers and will render on screen but the `canvas` content will not be accessible to screen readers.
With `canvas`, the accessibility has to be added with ARIA attributes on the `canvas` element or added using internal fallback content placed within the opening and closing canvas tags.
This [website](http://pauljadam.com/demos/canvas.html) has a more detailed explanation of `canvas` accessibility as well as in depth examples.
## Examples
These are some examples of **accessible** `canvas` elements.
By setting the `role` and `aria-label`, this `canvas` now has an accessible name.
```html
<canvas id="goodCanvas1" width="400" height="100" aria-label="Hello ARIA World" role="img"></canvas>
```
This `canvas` element has a text alternative via fallback content.
```html
<canvas id="okCanvas2" width="400" height="100">
<p>Hello Fallback World</p>
</canvas>
```
These are some bad examples of **inaccessible** `canvas` elements.
This `canvas` element does not have an accessible name or role.
```html
<canvas id="badCanvas1" width="400" height="100"></canvas>
```
This `canvas` element has inaccessible fallback content.
```html
<canvas id="badCanvas2" width="400" height="100">Your browser does not support the canvas element.</canvas>
```

View File

@@ -0,0 +1,49 @@
# 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](https://developer.mozilla.org/en-US/docs/Web/API/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](https://developer.mozilla.org/en-US/docs/Web/API/CanvasPattern) or [CanvasGradient](https://developer.mozilla.org/en/docs/Web/API/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.
```javascript
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](http://betweentwobrackets.com/data-graphics-and-colour-vision/).
Using the [Patternomaly](https://github.com/ashiguruma/patternomaly) library you can generate patterns to fill datasets.
```javascript
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']
};
```

View File

@@ -0,0 +1,13 @@
# Device Pixel Ratio
By default the chart's canvas will use a 1:1 pixel ratio, unless the physical display has a higher pixel ratio (e.g. Retina displays).
For applications where a chart will be converted to a bitmap, or printed to a higher DPI medium it can be desirable to render the chart at a higher resolution than the default.
Setting `devicePixelRatio` to a value other than 1 will force the canvas size to be scaled by that amount, relative to the container size. There should be no visible difference on screen; the difference will only be visible when the image is zoomed or printed.
## Configuration Options
| Name | Type | Default | Description
| ---- | ---- | ------- | -----------
| `devicePixelRatio` | `number` | `window.devicePixelRatio` | Override the window's default devicePixelRatio.

View File

@@ -0,0 +1,32 @@
# 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.
```javascript
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.
## Missing 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](https://github.com/chartjs/Chart.js/issues/3318) for more details.

View File

@@ -0,0 +1,10 @@
# 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](./events.md#events).
| Name | Type | Default | Description
| ---- | ---- | ------- | -----------
| `mode` | `string` | `'nearest'` | Sets which elements appear in the tooltip. See [Interaction Modes](./modes.md#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.

View File

@@ -0,0 +1,21 @@
# Events
The following properties define how the chart interacts with events.
| Name | Type | Default | Description
| ---- | ---- | ------- | -----------
| `events` | `string[]` | `['mousemove', 'mouseout', 'click', 'touchstart', 'touchmove']` | The `events` option defines the browser events that the chart should listen to for tooltips and hovering. [more...](#event-option)
| `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:
```javascript
var chart = new Chart(ctx, {
type: 'line',
data: data,
options: {
// This chart will not respond to mousemove, etc
events: ['click']
}
});
```

View File

@@ -0,0 +1,119 @@
# 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.
```javascript
var chart = new Chart(ctx, {
type: 'line',
data: data,
options: {
tooltips: {
mode: 'point'
}
}
});
```
## nearest
Gets the items that are at the nearest distance to the point. The nearest item is determined based on the distance to the center of the chart item (point, bar). You can use the `axis` setting to define which directions are used in distance calculation. 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.
```javascript
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.
```javascript
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.
```javascript
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.
```javascript
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.
```javascript
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.
```javascript
var chart = new Chart(ctx, {
type: 'line',
data: data,
options: {
tooltips: {
mode: 'y'
}
}
});
```

View File

@@ -0,0 +1,48 @@
# Options
## Scriptable Options
Scriptable options also accept a function which is called for each of the underlying data values and that takes the unique argument `context` representing contextual information (see [option context](options.md#option-context)).
Example:
```javascript
color: function(context) {
var index = context.dataIndex;
var value = context.dataset.data[index];
return value < 0 ? 'red' : // draw negative values in red
index % 2 ? 'blue' : // else, alternate values in blue and green
'green';
}
```
## 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](#scriptable-options) is more appropriated if supported.
Example:
```javascript
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](#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
- `hover`: true if hovered
**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.

View File

@@ -0,0 +1,84 @@
# Performance
Chart.js charts are rendered on `canvas` elements, which makes rendering quite fast. For large datasets or performance sensitive applications, you may wish to consider the tips below.
## Tick Calculation
### Rotation
[Specify a rotation value](https://www.chartjs.org/docs/latest/axes/cartesian/#tick-configuration) by setting `minRotation` and `maxRotation` to the same value, which avoids the chart from having to automatically determine a value to use.
### Sampling
Set the [`ticks.sampleSize`](../axes/cartesian/README.md#tick-configuration) option. This will determine how large your labels are by looking at only a subset of them in order to render axes more quickly. This works best if there is not a large variance in the size of your labels.
## Disable Animations
If your charts have long render times, it is a good idea to disable animations. Doing so will mean that the chart needs to only be rendered once during an update instead of multiple times. This will have the effect of reducing CPU usage and improving general page performance.
To disable animations
```javascript
new Chart(ctx, {
type: 'line',
data: data,
options: {
animation: {
duration: 0 // general animation time
},
hover: {
animationDuration: 0 // duration of animations when hovering an item
},
responsiveAnimationDuration: 0 // animation duration after a resize
}
});
```
## 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](https://digital.ni.com/public.nsf/allkb/F694FFEEA0ACF282862576020075F784) 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.
## Line Charts
### 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:
```javascript
new Chart(ctx, {
type: 'line',
data: data,
options: {
elements: {
line: {
tension: 0 // disables bezier curves
}
}
}
});
```
### Disable Line Drawing
If you have a lot of data points, it can be more performant to disable rendering of the line for a dataset and only draw points. Doing this means that there is less to draw on the canvas which will improve render performance.
To disable lines:
```javascript
new Chart(ctx, {
type: 'line',
data: {
datasets: [{
showLine: false // disable for a single dataset
}]
},
options: {
showLines: false // disable for all datasets
}
});
```

View File

@@ -0,0 +1,51 @@
# Responsive Charts
When it comes to changing 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**:
- `<canvas height="40vh" width="80vw">`: **invalid** values, the canvas doesn't resize ([example](https://codepen.io/chartjs/pen/oWLZaR))
- `<canvas style="height:40vh; width:80vw">`: **invalid** behavior, the canvas is resized but becomes blurry ([example](https://codepen.io/chartjs/pen/WjxpmO))
Chart.js provides a [few options](#configuration-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...](#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.
| `aspectRatio` | `number` | `2` | Canvas aspect ratio (i.e. `width / height`, a value of 1 representing a square canvas). Note that this option is ignored if the height is explicitly defined either as attribute or via the style.
| `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](https://codepen.io/chartjs/pen/YVWZbz)):
```html
<div class="chart-container" style="position: relative; height:40vh; width:80vw">
<canvas id="chart"></canvas>
</div>
```
The chart can also be programmatically resized by modifying the container size:
```javascript
chart.canvas.parentNode.style.height = '128px';
chart.canvas.parentNode.style.width = '128px';
```
Note that in order for the above code to correctly resize the chart height, the [`maintainAspectRatio`](#configuration-options) option must also be set to `false`.
## Printing Resizeable Charts
CSS media queries allow changing styles when printing a page. The CSS applied from these media queries may cause charts to need to resize. However, the resize won't happen automatically. To support resizing charts when printing, one needs to hook the [onbeforeprint](https://developer.mozilla.org/en-US/docs/Web/API/WindowEventHandlers/onbeforeprint) event and manually trigger resizing of each chart.
```javascript
function beforePrintHandler () {
for (var id in Chart.instances) {
Chart.instances[id].resize();
}
}
```

View File

@@ -0,0 +1,43 @@
# Getting Started
Let's get started using Chart.js!
First, we need to have a canvas in our page.
```html
<canvas id="myChart"></canvas>
```
Now that we have a canvas we can use, we need to include Chart.js in our page.
```html
<script src="https://cdn.jsdelivr.net/npm/chart.js@2.8.0"></script>
```
Now, we can create a chart. We add a script to our page:
```javascript
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.
All our examples are [available online](https://www.chartjs.org/samples/latest/) but you can also download the `Chart.js.zip` archive attached to every [release](https://github.com/chartjs/Chart.js/releases) to experiment with our samples locally from the `/samples` folder.

View File

@@ -0,0 +1,58 @@
# Installation
Chart.js can be installed via npm or bower. It is recommended to get Chart.js this way.
## npm
[![npm](https://img.shields.io/npm/v/chart.js.svg?style=flat-square&maxAge=600)](https://npmjs.com/package/chart.js)
[![npm](https://img.shields.io/npm/dm/chart.js.svg?style=flat-square&maxAge=600)](https://npmjs.com/package/chart.js)
```bash
npm install chart.js --save
```
## Bower
[![bower](https://img.shields.io/bower/v/chartjs.svg?style=flat-square&maxAge=600)](https://libraries.io/bower/chartjs)
```bash
bower install chart.js --save
```
## CDN
### CDNJS
[![cdnjs](https://img.shields.io/cdnjs/v/Chart.js.svg?style=flat-square&maxAge=600)](https://cdnjs.com/libraries/Chart.js)
Chart.js built files are available on [CDNJS](https://cdnjs.com/):
https://cdnjs.com/libraries/Chart.js
### jsDelivr
[![jsdelivr](https://img.shields.io/npm/v/chart.js.svg?label=jsdelivr&style=flat-square&maxAge=600)](https://cdn.jsdelivr.net/npm/chart.js@latest/dist/) [![jsdelivr hits](https://data.jsdelivr.com/v1/package/npm/chart.js/badge)](https://www.jsdelivr.com/package/npm/chart.js)
Chart.js built files are also available through [jsDelivr](https://www.jsdelivr.com/):
https://www.jsdelivr.com/package/npm/chart.js?path=dist
## Github
[![github](https://img.shields.io/github/release/chartjs/Chart.js.svg?style=flat-square&maxAge=600)](https://github.com/chartjs/Chart.js/releases/latest)
You can download the latest version of [Chart.js on GitHub](https://github.com/chartjs/Chart.js/releases/latest).
If you download or clone the repository, you must [build](../developers/contributing.md#building-and-testing) Chart.js to generate the dist files. Chart.js no longer comes with prebuilt release versions, so an alternative option to downloading the repo is **strongly** advised.
## Selecting the Correct Build
Chart.js provides two different builds for you to choose: **Stand-Alone Build**, **Bundled Build**.
### Stand-Alone Build
Files:
* `dist/Chart.js`
* `dist/Chart.min.js`
The stand-alone build includes Chart.js as well as the color parsing library. If this version is used, you are required to include [Moment.js](https://momentjs.com/) before Chart.js for the functionality of the time axis.
### Bundled Build
Files:
* `dist/Chart.bundle.js`
* `dist/Chart.bundle.min.js`
The bundled build includes Moment.js in a single file. You should use this version if you require time axes and want to include a single file. You should not use this build if your application already included Moment.js. Otherwise, Moment.js will be included twice which results in increasing page load time and possible version compatibility issues. The Moment.js version in the bundled build is private to Chart.js so if you want to use Moment.js yourself, it's better to use Chart.js (non bundled) and import Moment.js manually.

View File

@@ -0,0 +1,101 @@
# 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.
## Script Tag
```html
<script src="path/to/chartjs/dist/Chart.js"></script>
<script>
var myChart = new Chart(ctx, {...});
</script>
```
## Common JS
```javascript
var Chart = require('chart.js');
var myChart = new Chart(ctx, {...});
```
## Bundlers (Webpack, Rollup, etc.)
```javascript
import Chart from 'chart.js';
var myChart = new Chart(ctx, {...});
```
**Note:** Moment.js is installed along Chart.js as dependency. If you don't want to use Moment.js (either because you use a different date adapter or simply because don't need time functionalities), you will have to configure your bundler to exclude this dependency (e.g. using [`externals` for Webpack](https://webpack.js.org/configuration/externals/) or [`external` for Rollup](https://rollupjs.org/guide/en#peer-dependencies)).
```javascript
// Webpack
{
externals: {
moment: 'moment'
}
}
```
```javascript
// Rollup
{
external: {
['moment']
}
}
```
## Require JS
**Important:** RequireJS [can **not** load CommonJS module as is](https://requirejs.org/docs/commonjs.html#intro), so be sure to require one of the UMD builds instead (i.e. `dist/Chart.js`, `dist/Chart.min.js`, etc.).
```javascript
require(['path/to/chartjs/dist/Chart.min.js'], function(Chart){
var myChart = new Chart(ctx, {...});
});
```
**Note:** starting v2.8, Moment.js is an optional dependency for `Chart.js` and `Chart.min.js`. In order to use the time scale with Moment.js, you need to make sure Moment.js is fully loaded **before** requiring Chart.js. You can either use a shim:
```javascript
require.config({
shim: {
'chartjs': {
deps: ['moment'] // enforce moment to be loaded before chartjs
}
},
paths: {
'chartjs': 'path/to/chartjs/dist/Chart.min.js',
'moment': 'path/to/moment'
}
});
require(['chartjs'], function(Chart) {
new Chart(ctx, {...});
});
```
or simply use two nested `require()`:
```javascript
require(['moment'], function() {
require(['chartjs'], function(Chart) {
new Chart(ctx, {...});
});
});
```
## Content Security Policy
By default, Chart.js injects CSS directly into the DOM. For webpages secured using [Content Security Policy (CSP)](https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP), this requires to allow `style-src 'unsafe-inline'`. For stricter CSP environments, where only `style-src 'self'` is allowed, the following CSS file needs to be manually added to your webpage:
```html
<link rel="stylesheet" type="text/css" href="path/to/chartjs/dist/Chart.min.css">
```
And the style injection must be turned off **before creating the first chart**:
```javascript
// Disable automatic style injection
Chart.platform.disableCSSInjection = true;
```

View File

@@ -0,0 +1,65 @@
# 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.
```html
<canvas id="myChart" width="400" height="400"></canvas>
```
```javascript
// 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.
```html
<canvas id="myChart" width="400" height="400"></canvas>
<script>
var ctx = document.getElementById('myChart');
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: ['Red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange'],
datasets: [{
label: '# of Votes',
data: [12, 19, 3, 5, 2, 3],
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
}
}]
}
}
});
</script>
```

View File

@@ -0,0 +1 @@
# Additional Notes

View File

@@ -0,0 +1,31 @@
# Comparison with Other Charting Libraries
Library Features
| Feature | Chart.js | D3 | HighCharts | Chartist |
| ------- | -------- | --- | ---------- | -------- |
| Completely Free | &check; | &check; | | &check; |
| Canvas | &check; | | | |
| SVG | | &check; | &check; | &check; |
| Built-in Charts | &check; | | &check; | &check; |
| 8+ Chart Types | &check; | &check; | &check; | |
| Extendable to Custom Charts | &check; | &check; | | |
| Supports Modern Browsers | &check; | &check; | &check; | &check; |
| Extensive Documentation | &check; | &check; | &check; | &check; |
| Open Source | &check; | &check; | | &check; |
Built in Chart Types
| Type | Chart.js | HighCharts | Chartist |
| ---- | -------- | ---------- | -------- |
| Combined Types | &check; | &check; | |
| Line | &check; | &check; | &check; |
| Bar | &check; | &check; | &check; |
| Horizontal Bar | &check; | &check; | &check; |
| Pie/Doughnut | &check; | &check; | &check; |
| Polar Area | &check; | &check; | |
| Radar | &check; | | |
| Scatter | &check; | &check; | &check; |
| Bubble | &check; | | |
| Gauges | | &check; | |
| Maps (Heat/Tree/etc.) | | &check; | |

View File

@@ -0,0 +1 @@
!REDIRECT "https://github.com/chartjs/awesome"

View File

@@ -0,0 +1,3 @@
# License
Chart.js is <a href="https://github.com/chartjs/Chart.js" target="_blank">open source</a> and available under the <a href="https://opensource.org/licenses/MIT" target="_blank">MIT license</a>.

View File

@@ -0,0 +1,15 @@
a.anchorjs-link {
color: rgba(65, 131, 196, 0.1);
font-weight: 400;
text-decoration: none;
transition: color 100ms ease-out;
z-index: 999;
}
a.anchorjs-link:hover {
color: rgba(65, 131, 196, 1);
}
sup {
font-size: 0.75em !important;
}