# 配置
配置用于更改图表的行为方式。 有一些属性可以控制样式、字体、图例等。
# 配置对象结构
Chart.js 配置的顶层结构:
const config = {
type: 'line',
data: {},
options: {},
plugins: []
}
# type
图表类型决定了图表的主要类型。
note 数据集可以覆盖 type
,这就是混合图表的构造方式。
# data
详见 数据结构。
# options
大多数文档都在讨论这些选项。
# plugins
内联插件可以包含在此数组中。 这是为单个图表添加插件的另一种方法(与全局注册插件相比)。 更多关于 开发者部分 中的插件。
# 全局配置
这个概念是在 Chart.js 1.0 中引入的,以保留配置 DRY (opens new window),并允许跨图表类型全局更改选项,避免需要为每个实例指定选项,或为特定图表类型指定默认选项。
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'
}
}
});
# 数据集配置
选项可以直接在数据集上配置。 可以在多个不同级别更改数据集选项。 有关选项如何解析的详细信息,请参见 options。
以下示例会将所有线数据集的 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]
}]
}
});