0👍
✅
you can use color
property of gridline
. If color
is specified as an array, the first color applies to the first grid line, the second to the second grid line and so on. so define a color for first line and for the rest just define color as transparent so they wont be visible.
var ctx = document.getElementById('myChart').getContext('2d');
// you need to calculate the step items on axes to make all those color invisible
var restArr = ['rgba(0, 0, 0, 0)', 'rgba(0, 0, 0, 0)', 'rgba(0, 0, 0, 0)', 'rgba(0, 0, 0, 0)', 'rgba(0, 0, 0, 0)', 'rgba(0, 0, 0, 0)', 'rgba(0, 0, 0, 0)', 'rgba(0, 0, 0, 0)']
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: ['Red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange'],
datasets: [{
label: '# of Votes',
data: [-12, 19, 3, -5, 2, 3],
backgroundColor: [
'rgba(255, 99, 132, 0.2)',
'rgba(54, 162, 235, 0.2)',
'rgba(255, 206, 86, 0.2)',
'rgba(75, 192, 192, 0.2)',
'rgba(153, 102, 255, 0.2)',
'rgba(255, 159, 64, 0.2)'
],
borderColor: [
'rgba(255, 99, 132, 1)',
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)',
'rgba(75, 192, 192, 1)',
'rgba(153, 102, 255, 1)',
'rgba(255, 159, 64, 1)'
],
borderWidth: 1
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: true,
suggestedMin: -20,
suggestedMax: 20,
fontSize: 15,
padding: 20,
callback: value => {
if (value === 0) {
return value
} else if (Number(value).toFixed(1) === 10) {
return value
} else if (Number(value).toFixed(1) === Number(0 - 10).toFixed(1)) {
return value
} else {
return ''
}
}
},
gridLines: {
display: true,
drawBorder: true,
zeroLineWidth: 2,
lineWidth: 0,
drawTicks: false,
drawOnChartArea: true,
color: ['rgba(0, 0, 0, 0)', ...restArr],
zeroLineColor: 'rgba(0, 0, 0, 0.5)',
borderWidth: 0
}
}],
xAxes: [{
ticks: {
padding: 20
},
gridLines: {
display: true,
drawBorder: true,
drawTicks: false,
drawOnChartArea: true,
lineWidth: 1,
color: ['rgba(0, 0, 0, 1)', ...restArr],
zeroLineColor: 'rgba(0, 0, 0, 1)',
}
}]
},
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script>
<canvas id="myChart" width="400" height="400"></canvas>
Source:stackexchange.com