# 配置
配置用于更改图表的行为。其中包含控制样式、字体、图例等的属性。
# 配置对象结构
Chart.js 配置的顶层结构
const config = {
type: 'line',
data: {},
options: {},
plugins: []
}
# type
图表类型确定图表的类型。
注意 数据集可以覆盖type
,这是构建混合图表的方式。
# data
有关详细信息,请参见 数据结构。
# options
大多数文档都讨论这些选项。
# plugins
内联插件可以包含在此数组中。这是一种为单个图表添加插件的替代方法(与全局注册插件相比)。有关插件的更多信息,请参见 开发者部分。
# 全局配置
此概念是在 Chart.js 1.0 中引入的,以使配置 DRY (在新窗口中打开),并允许在图表类型之间全局更改选项,避免为每个实例指定选项或为特定图表类型指定默认值。
Chart.js 将传递给图表的options
对象与全局配置合并,使用图表类型默认值和刻度默认值进行适当的缩放。这样,您可以在单个图表配置中尽可能地具体,同时仍然更改所有适用的图表类型的默认值。全局通用选项在Chart.defaults
中定义。每个图表类型的默认值在该图表类型的文档中进行了讨论。
以下示例将为所有图表将交互模式设置为“nearest”,除非图表类型默认值或在创建时传递给构造函数的选项对此进行了覆盖。
Chart.defaults.interaction.mode = 'nearest';
// Interaction mode is set to nearest because it was not overridden here
const chartInteractionModeNearest = new Chart(ctx, {
type: 'line',
data: data
});
// This chart would have the interaction mode that was passed in
const chartDifferentInteractionMode = new Chart(ctx, {
type: 'line',
data: data,
options: {
interaction: {
// Overrides the global setting
mode: 'index'
}
}
});
# 数据集配置
可以在数据集上直接配置选项。可以在多个不同的级别更改数据集选项。有关如何解析选项的详细信息,请参见 选项。
以下示例将为所有折线数据集将showLine
选项设置为“false”,除非在创建时传递给数据集的选项对此进行了覆盖。
// Do not show lines for all datasets by default
Chart.defaults.datasets.line.showLine = false;
// This chart would show a line only for the third dataset
const 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]
}]
}
});