I am using chartJS to draw a bubble chart with an x axis running from -5 to +5 and a y axis running from -5 to +5. I was able to change the grid line styling using
JavaScript
x
7
1
x: {
2
grid: {
3
borderDash: [2, 10],
4
lineWidth: 1,
5
color: `#000`,
6
},
7
to get this result.
I need to have the X and Y axis at 0 on both to be solid bold. Is there a way to style gridline at specific tick points?
desired result is this…
Advertisement
Answer
The borderDash
option is non scriptable so to achieve this behaviour you will need to use a custom plugin to draw over the default grid lines:
JavaScript
1
89
89
1
const zeroZeroLines = {
2
id: 'zeroZeroLines',
3
beforeDatasetsDraw: (chart, args, opts) => {
4
const {
5
ctx,
6
chartArea: {
7
top,
8
bottom,
9
left,
10
right
11
},
12
scales: {
13
x,
14
y
15
}
16
} = chart;
17
18
const color = opts.color || 'black';
19
const width = opts.width || 1;
20
21
ctx.beginPath();
22
23
ctx.lineWidth = width;
24
ctx.strokeStyle = color;
25
26
ctx.moveTo(x.getPixelForValue(0), bottom);
27
ctx.lineTo(x.getPixelForValue(0), top);
28
29
ctx.moveTo(left, y.getPixelForValue(0));
30
ctx.lineTo(right, y.getPixelForValue(0));
31
32
ctx.stroke();
33
}
34
}
35
36
const options = {
37
type: 'bubble',
38
data: {
39
datasets: [{
40
label: '# of Votes',
41
data: [{
42
x: -4,
43
y: 0,
44
r: 4
45
}, {
46
x: 1,
47
y: -3,
48
r: 10
49
}, {
50
x: 3,
51
y: 3,
52
r: 20
53
}, {
54
x: 0,
55
y: 0,
56
r: 20
57
}],
58
backgroundColor: 'pink'
59
}]
60
},
61
options: {
62
scales: {
63
x: {
64
min: -5,
65
max: 5,
66
grid: {
67
borderDash: [2, 2]
68
}
69
},
70
y: {
71
min: -5,
72
max: 5,
73
grid: {
74
borderDash: [2, 2]
75
}
76
}
77
},
78
plugins: {
79
zeroZeroLines: {
80
color: 'black',
81
width: 1
82
}
83
}
84
},
85
plugins: [zeroZeroLines]
86
}
87
88
const ctx = document.getElementById('chartJSContainer').getContext('2d');
89
new Chart(ctx, options);
JavaScript
1
4
1
<body>
2
<canvas id="chartJSContainer" width="600" height="400"></canvas>
3
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.5.0/chart.js"></script>
4
</body>