# 标记轴
¥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
命名空间:options.scales[scaleId].title
,它定义了量表标题的选项。请注意,这仅适用于笛卡尔轴。
¥Namespace: options.scales[scaleId].title
, it defines options for the scale title. Note that this only applies to cartesian axes.
名称 | 类型 | 默认 | 描述 |
---|---|---|---|
display | boolean | false | 如果为真,则显示轴标题。 |
align | string | 'center' | 轴标题的对齐方式。可能的选项是 'start' 、'center' 和 'end' |
text | string |string[] | '' | 标题的文本。(即 "# 人数 " 或 "回应选择")。 |
color | Color | Chart.defaults.color | 标签的颜色。 |
font | Font | Chart.defaults.font | 见 字体 |
padding | Padding | 4 | 填充以应用在刻度标签周围。仅实现了 top 、bottom 和 y 。 |
# 创建自定义刻度格式
¥Creating Custom Tick Formats
想要更改刻度线以包含有关数据类型的信息也很常见。例如,添加美元符号 ('$')。为此,你需要覆盖轴配置中的 ticks.callback
方法。
¥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.
该方法接收 3 个参数:
¥The method receives 3 arguments:
value
- 关联刻度的内部数据格式中的刻度值。对于时间尺度,它是一个时间戳。¥
value
- the tick value in the internal data format of the associated scale. For time scale, it is a timestamp.index
- ticks 数组中的 tick 索引。¥
index
- the tick index in the ticks array.ticks
- 包含所有 刻度对象 的数组。¥
ticks
- the array containing all of the tick objects.
对该方法的调用仅限于比例尺。方法中的 this
是比例对象。
¥The call to the method is scoped to the scale. this
inside the method is the scale object.
如果回调返回 null
或 undefined
,则关联的网格线将被隐藏。
¥If the callback returns null
or undefined
the associated grid line will be hidden.
提示
分类轴 是折线图和柱状图的默认 x 轴,使用 index
作为内部数据格式。要访问标签,请使用 this.getLabelForValue(value)
。API:getLabelForValue
¥The category axis, which is the default x-axis for line and bar charts, uses the index
as internal data format. For accessing the label, use this.getLabelForValue(value)
. API: getLabelForValue
在以下示例中,Y 轴的每个标签都将在前面显示一个美元符号。
¥In the following example, every label of the Y-axis would be displayed with a dollar sign at the front.
const chart = new Chart(ctx, {
type: 'line',
data: data,
options: {
scales: {
y: {
ticks: {
// Include a dollar sign in the ticks
callback: function(value, index, ticks) {
return '$' + value;
}
}
}
}
}
});
请记住,覆盖 ticks.callback
意味着你负责标签的所有格式。根据你的用例,你可能想要调用默认格式化程序,然后修改其输出。在上面的示例中,它看起来像:
¥Keep in mind that overriding ticks.callback
means that you are responsible for all formatting of the label. Depending on your use case, you may want to call the default formatter and then modify its output. In the example above, that would look like:
// call the default formatter, forwarding `this`
return '$' + Chart.Ticks.formatters.numeric.apply(this, [value, index, ticks]);
相关样本:
¥Related samples: