#chart.js
Вопрос:
У меня есть график с использованием ChartJS последней версии 3.3.2. Мой код выглядит следующим образом:
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="">
<meta name="author" content="">
<title>OCA-Test</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.3.2/chart.min.js"></script>
</head>
<body>
<canvas id="chartJSContainer"></canvas>
<script>
const labels = ["A","B","C","D","E","F","G","H","I","J"];
const data = {
labels: labels,
datasets: [
{
label: 'Dataset 1',
data: [-92, -100, -99, -86, 8, 56, -94, -89, -92, -24],
borderColor: 'transparent',
backgroundColor: 'transparent',
order: 1
},
{
label: 'Dataset 2',
data: [-92, -100, -99, -86, 8, 56, -94, -89, -92, -24],
borderColor: 'black',
backgroundColor: 'blue',
type: 'line',
order: 0
}
]
};
const config = {
type: 'bar',
data: data,
options: {
responsive: true,
plugins: {
legend: {
display: false
},
title: {
display: false
}
},
scales: {
y: {
min: -100,
max: 100
}
}
}
};
var chart = new Chart(document.getElementById('chartJSContainer'), config);
</script>
</body>
</html>
Как я могу добавить те же метки по оси x также в верхней части графика и добавить новые метки также слева от графика. См. Прилагаемый снимок. Спасибо.
Ответ №1:
Для оси X сверху вы можете просто добавить другую ось X и установить положение сверху, для меток между осями Y лучше всего написать для этого пользовательский плагин.
Пример:
var options = {
type: 'line',
data: {
labels: ["A", "B", "C", "D", "E", "F"],
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: {
scales: {
x: {
position: 'bottom',
grid: {
offset: true // offset true to get labels in between the lines instead of on the lines
}
},
x2: {
position: 'top',
grid: {
offset: true // offset true to get labels in between the lines instead of on the lines
}
},
y: {
ticks: {
count: (context) => (context.scale.chart.data.labels.length 1)
}
}
},
plugins: {
labelsY: {
font: 'Arial',
size: '14px',
color: '#666',
align: 'right',
reverseLabels: false // true to make A start at top and F at bottom
}
}
},
plugins: [{
id: 'labelsY',
afterDraw: (chart, args, options) => {
const {
ctx,
scales: {
y,
x
},
data: {
labels
}
} = chart;
let dupLabels = JSON.parse(JSON.stringify(labels)); // remove pointer to internal labels array so you dont get glitchy behaviour
if (options.reverseLabels) {
dupLabels = dupLabels.reverse();
}
dupLabels.forEach((label, i) => {
ctx.save();
ctx.textAlign = options.align || 'right';
ctx.font = `${options.size || '20px'} ${options.font || 'Arial'}`;
ctx.fillStyle = options.color || 'black'
let xPos = x.getPixelForValue(labels[0]) - ctx.measureText(label).width;
let yPos = (y.getPixelForValue(y.ticks[i].value) y.getPixelForValue(y.ticks[i 1].value)) / 2;
ctx.fillText(label, xPos, yPos)
ctx.restore();
});
}
}]
}
var 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.3.0/chart.js"></script>
</body>
Комментарии:
1. Большое спасибо!