React-Chartjs-2 How to create dashed gridlines - chart.js

Im using react-chartjs-2 and trying to create dashed gridlines on the y-axis
I tried to look on Chart Config Web: https://www.chartjs.org/docs/latest/axes/styling.html#grid-line-configuration
But cant find the trick
Here is my code:
import { Chart } from 'react-chartjs-2';
import {Chart as ChartJS, registerables} from 'chart.js';
ChartJS.register(...registerables);
const data = {
labels: ["Label1", "Label2", "Label3"],
datasets: [{
label: 'legend1',
data: [12, 19, 3],
},{
label: 'legend2',
data: [22, 9, 13],
}]
};
const options = {
scales: {
y: {
grid: {
tickBorderDash: [4, 4],
tickColor: '#000',
tickWidth: 2,
offset: true,
drawTicks: true,
drawOnChartArea: true
},
beginAtZero: true,
},
x: {
display: false
}
},
};
const BarChart = (props : Props) => {
return (
<Chart type='bar' data={data} options={options} />
);
};
Thank you!

By looking at the source code, I gathered that for some reason y.grid.tickBorderDash option only applies to the tick marks, not for the grid lines. Actually, the option is applied only for lines that are not affected by drawOnChartArea: true.
To make y axis gridlines dashed, one has to set y.border.dash option. This doesn't seem very consistent to me, but that's the way the code currently functions.
So this should work:
const options = {
scales: {
y: {
border:{dash: [4, 4]}, // for the grid lines
grid: {
color: '#aaa', // for the grid lines
tickColor: '#000', // for the tick mark
tickBorderDash: [2, 3], // also for the tick, if long enough
tickLength: 10, // just to see the dotted line
tickWidth: 2,
offset: true,
drawTicks: true, // true is default
drawOnChartArea: true // true is default
},
beginAtZero: true,
},
x: {
display: false
}
},
};
Note: I tested with charts.js 4.2.0 (latest at the time of posting).

Related

why the main and axis title does not show in chart.js

I have the following code to make a chart with chart.js but the main and axis title just does not work. Also I have put the legend to the bottom but does not work. Can anybody tell why it is not working?
let dataSize = 30;
let readings = new Array(dataSize);
const data = {
// X axis labels
labels: new Array(dataSize),
datasets: [{
//label: 'My Input', // chart label
data: readings, // the data to chart
//borderColor: '#272323', // line color (lavender)
backgroundColor: 'rgba(123, 83, 252, 80)',
borderColor: "rgba(255, 0, 0,1)",
borderWidth: 1.2,
pointBorderColor: "rgba(255, 0, 0, 1)",
pointRadius: 0.2 // point size
}]
};
const config = {
type: 'line', // type of chart
data: data, // the data
options: {
animation: false, // remove animation to speed drawing up
responsive: true,
maintainAspectRatio: false,
title: {
display: true,
text: 'Tarrif'
},
legend:{
position: 'bottom'
},
scales: { // axis ranges:
y: {
//type: 'linear',
scaleLabel: {
display: true,
labelString: 'X axis Title'
},
min: 0,
max: 260,
gridLines: {
display: true,
drawBorder: false //hide the chart edge line
}
},
x:[{
gridLines: {
display: false
},
scaleLabel: {
display: true,
labelString: 'X axis Title'
},
min:0
}]
}
}
};
Below is screenshot of my graph:
I followed the advice here:
In Chart.js set chart title, name of x axis and y axis?
thanks
First of all don't use an array for your X scales, all the scales need to be defined as objects. Second you are placing the options in the wrong part, it has to be configured in the title namespace like so:
scales: {
y: {
title: {
display: true,
text: 'yTitle'
}
},
x: {
title: {
display: true,
text: 'xTitle'
}
}
}

chartjs show nearest point on hover

I'm currently trying to reproduce the chart you can see on https://discordstatus.com/ for the API Response Time.
However I'm unable to always show the nearest label depending on the mouse position on the X axis. I've tried different configurations for interactions (Chart.js Interactions) but fail to get the desired outcome.
Also it would be nice to show a vertical line dependent on the current active point. As well as always show the tooltip at the top left.
Is this possible with the default chart.js library or do i have to add a plugin or some own modifications?
Here is my current configuration:
const data = {
datasets: [{
label: 'RTT',
backgroundColor: '#C00122',
borderColor: '#C00122',
borderWidth: 2,
}]
};
const config = {
type: 'line',
data: data,
options: {
animation: false,
maintainAspectRatio: false,
pasing: false,
plugins: {
legend: false
},
elements: {
point: {
radius: 1
}
},
scales: {
x: {
type: 'time',
time: {
unit: 'second',
displayFormats: {
'second': 'H:mm:ss',
}
},
ticks: {
minRotation: 0,
maxRotation: 0,
maxTicksLimit: 5
}
},
y: {
min: 0,
ticks: {
stepSize: 10
}
}
},
hover: {
mode: 'index'
}
}
};
EDIT: My datasets are filled dynamically as described here: Updating Charts

Chartjs Datasets overlapping and z-index

I have the below Chart implemented using chart.js version 3.x.
https://jsfiddle.net/Lxya0u98/12/
I have multiple datasets in my charts to achieve the behavior I want.
I am facing an issue with the datasets overlapping. In the chart, I have end of the blue color line overlapping with the green color dot dataset. Is there a way to avoid this issue?
I have the below two datasets:
// Data set for the Big Dot
{
showLine: false,
borderWidth: 0,
lineTension: 0,
borderColor: colorVal,
backgroundColor: colorVal,
pointBackgroundColor: colorVal,
pointBorderColor: colorVal,
pointBorderWidth: 2,
pointRadius: 15,
};
// Data set for the Connecting Lines
{
showLine: true,
lineTension: 0,
borderWidth: 5,
borderColor: colorVal,
pointRadius: 0,
pointBorderWidth: 0,
spanGaps: true,
};
Is there a Z-Index for the Datasets so that they appear on top of the previous one in the stack?
The option dataset.order has similar effect as the z-index.
Datasets with higher order are drawn first
Datasets with no or lower order are drawn last, hence appear on top
Therefore, adding order: 1 to your line datasets should solve the problem.
var newDataLine = {
...
order: 1
};
Instead of defining multiple datasets, you could proceed as follows:
First convert your line chart into a scatter chart.
Then draw the lines directly on the canvas using the Plugin Core API. The API offers a range of hooks that may be used for performing custom code. You can use the beforeDraw hook to draw connection lines of different colors between data points and to the open end of the chart.
Note that you have to define xAxes.ticks.max in order to obtain the open end line at the right of the chart.
Please take a look at below runnable code snippet and see how it works.
new Chart('line-chart', {
type: "scatter",
plugins: [{
beforeDraw: chart => {
var ctx = chart.chart.ctx;
ctx.save();
var xAxis = chart.scales['x-axis-1'];
var yAxis = chart.scales['y-axis-1'];
var dataset = chart.data.datasets[0];
var y = yAxis.getPixelForValue(0);
dataset.data.forEach((value, index) => {
var xFrom = xAxis.getPixelForValue(value.x);
var xTo;
if (index + 1 < dataset.data.size) {
xTo = xAxis.getPixelForValue(dataset.data[index + 1].x);
} else {
xTo = xAxis.right;
}
ctx.strokeStyle = dataset.backgroundColor[index];
ctx.lineWidth = 4;
ctx.beginPath();
ctx.moveTo(xFrom, y);
ctx.lineTo(xTo, y);
ctx.stroke();
});
ctx.restore();
}
}],
data: {
datasets: [{
data: [
{ x: 0, y: 0 },
{ x: 1, y: 0 },
{ x: 2, y: 0 }
],
backgroundColor: ['red', 'blue', 'green'],
borderColor: ['red', 'blue', 'green'],
pointRadius: 8,
pointHoverRadius: 8,
}],
},
options: {
layout: {
padding: {
left: 10,
right: 10
}
},
legend: {
display: false
},
tooltips: {
enabled: false
},
scales: {
yAxes: [{
ticks: {
display: false
},
gridLines: {
display: false,
}
}],
xAxes: [{
ticks: {
display: false,
max: 3
},
gridLines: {
display: false
}
}]
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.min.js"></script>
<canvas id="line-chart" height="30"></canvas>

Is there a way to create a chart with only a single axis?

I'm trying to create a "chart" where I only want to show the x-axis. Basically I'm trying to create visualization of a range (min-max) and a point that sits in between like:
I'm unable to find any resources online on how to make this, or what this type of plot is even called. If anyone could help out, that would be awesome!
This is straightforward to achieve through styling a line chart appropriately and using linear x- & y-axes with points defined via x and y coordinates.
By keeping y at 0 you can assure the points all appear in the same horizontal position.
The example below gets the visual result you want, but you'll probably want to disable tooltips for the 'fake' x-axis line via a callback:
let range = {
min: 0,
max: 100
},
pointVal = 65;
new Chart(document.getElementById("chart"), {
type: "line",
data: {
labels: ["", "", ""],
datasets: [{
pointBackgroundColor: "green",
pointRadius: 10,
pointHoverRadius: 10,
pointStyle: "rectRot",
data: [{
x: pointVal,
y: 0
}]
}, {
// this dataset becomes the 'fake' x-axis line.
pointBackgroundColor: "black",
borderColor: "black",
data: [{
x: range.min,
y: 0
},
{
x: range.max / 2,
y: 0
},
{
x: range.max,
y: 0
}
]
}]
},
options: {
legend: {
display: false
},
hover: {
mode: "point"
},
layout: {
padding: {
left: 10,
right: 10,
top: 0,
bottom: 0
}
},
scales: {
xAxes: [{
type: "linear",
display: false
}],
yAxes: [{
display: false
}]
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.8.0/Chart.min.js"></script>
<div style="width:200px">
<canvas id="chart"></canvas>
</div>

How do I invert an y-axis using chart.js (v2.0-dev)

I am creating line charts with 2 y-axes. one of those axes has two datasets but both run from the range of 0-100. The higher number being the better one. The second y-axis is usually lower in range (often in the single digits) and the best result is 1.
How can I invert the second y-axis so that 1 is at the top of the chart?
(I will try to find a solution myself, but at 5k+ lines in chart.js, it might take a while )
Thanks ^_^
Dev 2.0 of chart js supports an option to reverse the ticks when setting up the axis so your declaration of the second axis would become
{
type: "invertedLinear", // only linear but allow scale type registration. This allows extensions to exist solely for log scale for instance
display: true,
position: "right",
id: "y-axis-2",
ticks: {
reverse: true
},
// grid line settings
gridLines: {
drawOnChartArea: false, // only want the grid lines for one axis to show up
}
}
Here it is in action https://jsfiddle.net/nwc8ys34/15/
Using v 2.7.0, and the following seems to work:
options: {
scales: {
yAxes: [{
ticks: {
reverse: true,
}
}]
}
}
In v3 the scale configs have been changed so the desired behaviour can be accomplished like so:
const options = {
type: 'line',
data: {
labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
datasets: [{
label: '# of Votes',
data: [40, 80, 100, 70, 60, 80],
borderColor: 'pink'
},
{
label: '# of Points',
data: [7, 11, 5, 8, 3, 7],
borderColor: 'orange',
yAxisID: 'y2'
}
]
},
options: {
scales: {
y: {},
y2: {
position: 'right',
reverse: true
}
}
}
}
const ctx = document.getElementById('chartJSContainer').getContext('2d');
const chart = new Chart(ctx, options);
<body>
<canvas id="chartJSContainer" width="600" height="400"></canvas>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.6.0/chart.js"></script>
</body>
Chart.js 4:
datasets: [{
label: "Strength",
yAxisID: "y1",
data: mappedData.sigStrength
}, {
label: "Bars",
yAxisID: "y2",
data: mappedData.sigBars
}]
scales: {
y1: {
type: "linear",
display: true,
position: "left",
reverse: true
},
y2: {
type: "linear",
display: true,
position: "right",
ticks: {
stepSize: 1
}
}
},