如何在chart.js中更改缩放标题位置



是否可以将标题位置(月份和数字)更改为图表中x和y刻度的末尾(如预期的图片)

期望:https://i.stack.imgur.com/Dlr6R.png

实际:https://i.stack.imgur.com/AcD7c.png

这里是选项设置:

options: {
layout: {
padding: 0,
},
scales: {
y: {
title: {
display: true,
align: "center",
text: "number",
color: "#242424",
},
},
x: {
title: {
display: true,
align: "center",
text: "month",
color: "#242424",
},
},
},
plugins: {
legend: {
display: true,
position: "bottom",
},
},
},

你不能在默认情况下做到这一点,你需要使用一个自定义插件:

const customTitle = {
id: 'customTitle',
beforeLayout: (chart, args, opts) => {
if (!opts.x.display) {
return;
}
const {
ctx
} = chart;
ctx.font = opts.x.font || '12px "Helvetica Neue", Helvetica, Arial, sans-serif'
const {
width
} = ctx.measureText(opts.x.text);
chart.options.layout.padding.right = width * 1.3;
},
afterDraw: (chart, args, opts) => {
const {
ctx,
scales: {
x,
y
},
chartArea: {
top,
bottom,
left,
right
}
} = chart;
if (opts.x.display) {
ctx.fillStyle = opts.x.color || Chart.defaults.color
ctx.font = opts.x.font || '12px "Helvetica Neue", Helvetica, Arial, sans-serif'
ctx.fillText(opts.x.text, (right + (opts.x.offsetX || 0)), (bottom + ((opts.x.offsetY * -1) || 0)))
}
if (opts.y.display) {
ctx.fillStyle = opts.y.color || Chart.defaults.color
ctx.font = opts.y.font || '12px "Helvetica Neue", Helvetica, Arial, sans-serif'
ctx.fillText(opts.y.text, opts.y.offsetX || 3, (top + ((opts.y.offsetY * -1) || -15)))
}
}
}
const options = {
type: 'line',
data: {
labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
datasets: [{
label: '# of Votes',
data: [12, 19, 3, 5, 2, 3],
borderWidth: 1
},
{
label: '# of Points',
data: [7, 11, 5, 8, 3, 7],
borderWidth: 1
}
]
},
options: {
layout: {
padding: {
right: 0 // Seems neccesarry to put to 0, otherwise seems to not update padding
}
},
plugins: {
customTitle: {
y: {
display: true,
text: 'Numbers'
},
x: {
display: true,
text: 'Month',
offsetX: 5,
offsetY: 5,
font: '12px Comic Sans MS'
}
}
}
},
plugins: [customTitle]
}
const ctx = document.getElementById('chartJSContainer').getContext('2d');
new Chart(ctx, options);
<body>
<canvas id="chartJSContainer" width="600" height="400"></canvas>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.5.1/chart.js"></script>
</body>

最新更新