new Chart(stats, {
type: 'line',
data: {
labels: ['', '', '2021', '2022', '2023', '2024', '', ''],
datasets: [{
data: [, , 100, 300, 200, 450],
borderWidth: 4,
borderColor: '#7168BD',
backgroundColor: 'rgba(241, 163, 60, 0.1)',
pointRadius: 5,
pointHoverRadius: 8,
pointBackgroundColor: "#7168BD"
},
{
data: [, , 250, 200, 250, 400],
borderWidth: 4,
borderColor: '#B6A76E',
backgroundColor: 'rgba(230, 57, 70, 0.1)',
pointRadius: 5,
pointHoverRadius: 8,
pointBackgroundColor: "#B6A76E"
}]
},
options: {
scales: {
y: {
grid: {
color: '#B0B0B0',
borderColor: 'transparent'
}
},
x: {
grid: {
color: '#B0B0B0',
borderColor: 'transparent',
}
}
},
plugins: {
legend: {
display: false,
}
},
responsive: true
}
});
<canvas id="stats"></canvas>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.9.1/chart.min.js"></script>
转到有关如何使用Chartjs上删除X轴上多余的线的答案?grid Configuration
labels
数组中的第一个和最后一个其他空字符串。
new Chart(stats, {
type: 'line',
data: {
labels: ['', '2021', '2022', '2023', '2024', ''],
datasets: [
{
data: [null, 100, 300, 200, 450, null],
borderWidth: 4,
borderColor: '#7168BD',
backgroundColor: 'rgba(241, 163, 60, 0.1)',
pointRadius: 5,
pointHoverRadius: 8,
pointBackgroundColor: '#7168BD',
},
{
data: [null, 250, 200, 250, 400, null],
borderWidth: 4,
borderColor: '#B6A76E',
backgroundColor: 'rgba(230, 57, 70, 0.1)',
pointRadius: 5,
pointHoverRadius: 8,
pointBackgroundColor: '#B6A76E',
},
],
},
options: {
scales: {
y: {
grid: {
color: '#B0B0B0',
borderColor: 'transparent',
drawBorder: true,
drawOnChartArea: true,
drawTicks: false,
},
},
x: {
grid: {
color: function (context) {
if (
context.index === 0 ||
context.index === context.chart.scales.x.ticks.length - 1
) {
return 'transparent';
}
return '#B0B0B0';
},
borderColor: 'transparent',
},
},
},
plugins: {
legend: {
display: false,
},
},
responsive: true,
},
});
demo @stackblitz