I'm using react-chart-js 2 to display continuous data in scatter chart form. I wanted to put options on the charts but some of them do not work properly or at all.So i would like the x-axis not to move and the y-axis to readjust with the data except that my problem is that the x-axis stays fixed but the y-axis keeps moving and as in the picture the 0 is above the x-axis.
The version of react-chart-js 2 installed is : 5.2.0 and the version of chartJS is: 4.1.2.
Question : How can I link the 2 axes?
What i have tried : I have tried to insert min,max in the y axis but the x-axis remained at the bottom.
I have inserted the following code for the plugin part but it didn't display the line axis at the middle.
const plugin = {
id: 'middleAxis',
beforeDraw(chart) {
const {ctx, scales} = chart;
const yAxis = scales.y;
const xAxis = scales.x;
const zeroPosition = yAxis.getPixelForValue(0);
const labelItems = xAxis.getLabelItems();
ctx.save();
ctx.beginPath();
ctx.lineWidth = 1;
ctx.moveTo(xAxis.left, zeroPosition);
ctx.lineTo(xAxis.right, zeroPosition)
ctx.stroke();
for (const item of labelItems) {
const {font, label, options} = item;
const {strokeWidth, strokeColor, textAlign, textBaseline, translation} = options;
const x = translation[0];
const y = zeroPosition + font.lineHeight;
ctx.beginPath();
ctx.font = font.string;
ctx.textAlign = textAlign;
ctx.textBaseline = textBaseline;
ctx.lineWidth = strokeWidth;
ctx.strokeStyle = strokeColor;
ctx.fillText(label, x, y);
ctx.fill();
}
ctx.restore();
}
};
export const options5 = {
elements: {
line: {
tension: 0.3,
},
},
// Modify the axis by adding scales
scales: {
// to remove the labels
x: {
display: false,
ticks: {
display: true,
},
// to remove the x-axis grid
grid: {
drawBorder: false,
display: false,
},
},
// to remove the y-axis label
},
responsive: true,
maintainAspectRatio: false,
plugins: [plugin],
};
I had the following result :
Here is the old code :
Option of my scatter chart :
export const options5 = {
elements: {
line: {
tension: 0.3,
}
},
// Modify the axis by adding scales
scales: {
// to remove the labels
x: {
ticks: {
display: true,
},
// to remove the x-axis grid
grid: {
drawBorder: false,
display: false,
},
},
// to remove the y-axis labels
y: {
display:true,
beginAtZero: true,
ticks: {
display: true,
},
// to remove the y-axis grid
grid: {
drawBorder: false,
display: false,
},
},
},
responsive: true,
maintainAspectRatio: false,
plugins: {
showLine: true,
legend: false,
},
};
Regards,