Show only nth tick LINE on x-axis for Chart.js diagram - chart.js

I've been searching for a solution to this for a while but am getting no nearer to a solution due to the mass of deleted documentation and hacky answers for previous versions of the library.
I'm working on a chart with ChartJS v2 with quarterly-month names along the x-axis, and I've set my labels so that only every 4th label is shown (i.e. one per year). The result is this:
However, I would like to have it such that the tick lines also only appear on every 4th x-axis entry at the same point as the labels. Is this possible?
My current script tag is as follows:
<script>
var ctx = document.getElementById("myChart").getContext('2d');
ctx.canvas.width = 600;
ctx.canvas.height = 420;
var myChart = new Chart(ctx, {
type: 'line',
data: {
< snipped for brevity >
},
options: {
tooltips: {
mode: 'index',
intersect: false
},
scales: {
xAxes: [{
ticks: {
userCallback: function(item, index) {
if (index%4) return "";
return item;
},
autoSkip: false
},
display: true
}],
yAxes: [{
ticks: {
beginAtZero:true
}
}]
}
}
});
</script>
Is this possible to achieve? Thanks in advance.

Replace your tick­'s userCallback function with the following ...
userCallback: function(item, index) {
if (!(index % 4)) return item;
}
Basically, you don't need to return any empty string for the label that you wish to hide. If you do not return anything (for the label you don't want), it won't draw any tick (as well as gridline) for that label.
ᴅᴇᴍᴏ
var ctx = document.getElementById("myChart").getContext('2d');
var myChart = new Chart(ctx, {
type: 'line',
data: {
labels: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sept'],
datasets: [{
label: 'Standard Rating',
data: [1, 2, 3, 4, 5, 6, 7, 8, 9],
backgroundColor: 'rgba(209, 230, 245, 0.5)',
borderColor: 'rgba(56, 163, 236, 1)',
borderWidth: 1
}]
},
options: {
responsive: false,
tooltips: {
mode: 'label',
intersect: false
},
scales: {
xAxes: [{
ticks: {
userCallback: function(item, index) {
if (!(index % 4)) return item;
},
autoSkip: false
}
}],
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.5.0/Chart.min.js"></script>
<canvas id="myChart" width="350" height="200"></canvas>

Related

How to skip tick interval on chart.js x-axis?

I am working with Chart.js. I want to display every third tick and label on the chart.
With the code below, I am able to skip every third label not the interval/tick also.
I want to skip/remove the interval. Is it possible to skip the tick and interval without modifying the input data ?
I'll for thank full for any kind of inputs/help?
options: {
scales: {
xAxes: [{
autoSkip: false,
ticks: {
callback: function(tick, index, array) {
return (index % 3) ? "" : tick;
}
}
}],
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
You can define the scriptable option options.scales.x.grid.tickColor as follows. This generates an array that specifies a color for every 3rd tick line only.
grid: {
tickColor: labels.map((l, i) => i % 3 ? null : 'lightgray')
}
For further information, consult Grid Line Configuration from the Chart.js documentation.
Please take a look at the runnable code below and see how it works.
const labels = ['January', 'February', 'March', 'April', 'May', 'June', 'July'];
const data = [65, 59, 80, 81, 56, 55, 40];
new Chart('myChart', {
type: 'line',
data: {
labels: labels,
datasets: [{
label: 'My Dataset',
data: data,
fill: false,
borderColor: 'rgb(75, 192, 192)',
tension: 0.1
}]
},
options: {
scales: {
x: {
autoSkip: false,
grid: {
tickColor: labels.map((l, i) => i % 3 ? null : 'lightgray')
},
ticks: {
callback: (t, i) => i % 3 ? '' : labels[i]
},
},
y: {
beginAtZero: true
}
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.9.1/chart.min.js"></script>
<canvas id="myChart" height="80"></canvas>

Can I make Y axis begin at specific value in ChartJS?

I have this chart, starting at 0 and I want the Y axis to begin at 20. It surprises me how there is nothing related to this in the official ChartJS docs. Is this possible in any way?
I have tried several ways to do it, eg. with ticks or min value and so on but nothing worked.
The application is written in Nuxt3 and the ChartJS library used is vue-chart-3.
const options = computed(() => ({
responsive: true,
plugins: {
legend: {
display: false,
},
title: {
display: false,
}
},
scales: {
x: {
stacked: true,
},
y: {
stacked: true,
}
}
}));
const chartData = computed(() => ({
labels: ['Provider'],
datasets: [
{
data: [selectedDataset.value?.score.uncustomized],
backgroundColor: ['#00b7c4'],
},
{
data: [selectedDataset.value?.score.difference],
backgroundColor: ['#204992'],
},
],
}));
const { barChartProps, barChartRef } = useBarChart({
chartData,
options,
});
Any help would be appreciated.
If you want the axis to start at a given number you need to use the min property:
const options = {
type: 'line',
data: {
labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
datasets: [{
label: '# of Votes',
data: [12, 19, 3, 5, 2, 3],
borderColor: 'pink'
},
{
label: '# of Points',
data: [7, 11, 5, 8, 3, 7],
borderColor: 'orange'
}
]
},
options: {
scales: {
y: {
min: 6
}
}
}
}
const ctx = document.getElementById('chartJSContainer').getContext('2d');
new Chart(ctx, options);
<body>
<canvas id="chartJSContainer" width="600" height="400"></canvas>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.7.1/chart.js"></script>
</body>

Chart.js label and point getting cutoff on the right

It seems as though the last date label is getting cutoff on my chart here in chart.js. There should be a data point for 2018.
When researching it I've seen it suggested to add layout padding.
I tried that but it disables the chart entirely. Anyone have an alternative solution or an idea on why my layout padding does not work?
var myChart = new Chart(ctx, {
type: 'line',
data: {
labels: dollar.years,
datasets: [
{label: 'Cdn dollar in cents',
data: dollar.vals,
borderColor: 'rgb(153,222,101)',
backgroundColor: 'rgb(153,222,101, 0.2)',
pointRadius: 0,
borderWidth: 6,
}]
},
options: {
responsive: true,
title: {
display: false
},
legend: {
display: false
},
labels: {
padding:1
},
scales: {
yAxes: [{
ticks: {
min: 0,
max: 5,
stepSize: 1
}
}],
xAxes: [{
type: "time",
time: {
unit: "year",
tooltipFormat: "YYYY"
},
ticks: {
display: true,
labelOffset: -1,
maxTicksLimit: 5,
drawOnChartArea: false,
autoSkip: false,
maxRotation: 0,
minRotation: 0,
padding: 5
},
}],
}
}
});
}
The option layout.padding work as below code snippet illustrates. You however need to carefully choose the values (number of pixels) in order to not completely hide the chart area.
I would however rather define xAxes.ticks.max to make sure the tick for 2018 is shown even if data would be available up to 2017 only.
const years = [];
const vals = [];
for (let year = 1968; year <= 2018; year++) {
years.push(year.toString());
vals.push(Math.floor(Math.random() * 3) + 1);
}
var myChart = new Chart(document.getElementById("myChart"), {
type: 'line',
data: {
labels: years,
datasets: [{
label: 'Cdn dollar in cents',
data: vals,
borderColor: 'rgb(153,222,101)',
backgroundColor: 'rgb(153,222,101, 0.2)',
pointRadius: 0,
borderWidth: 6
}]
},
options: {
responsive: true,
layout: {
padding: {
left: 0,
right: 100,
top: 0,
bottom: 0
}
},
legend: {
display: false
},
scales: {
yAxes: [{
ticks: {
min: 0,
max: 4,
stepSize: 1
}
}],
xAxes: [{
type: "time",
time: {
parser: 'YYYY',
unit: "year",
tooltipFormat: "YYYY"
},
ticks: {
max: "2018",
maxTicksLimit: 5,
maxRotation: 0
}
}]
}
}
});
canvas {
max-width: 400px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.bundle.js"></script>
<canvas id="myChart" width="600" height="400"></canvas>

Chart.js - Hover labels to display data for all data points on x-axis

I have a graph with multiple data points / lines. Currently, if you hover near a data point, it will display the label/value for that point.
What I'd like is the following: when you hover anywhere on the chart, it will display the labels + values for all data points at that x-value simultaneously in a single label.
For example, let's take the given datasets:
Date (x-labels): ['Jan 01','Jan 02','Jan 03']
Apples Sold: [3,5,1]
Oranges Sold: [0,10,2]
Gallons of Milk Sold: [5,7,4]
When you hover over the middle of the graph, above the 'Jan 02' vertical space, the label should display:
Jan 02
-----------------------
Apples Sold: 5
Oranges Sold: 10
Gallons of Milk Sold: 7
Is there a simple way to accomplish this?
Thanks.
Is there a simple way to accomplish this?
YES !! There is a quite straightforward way to accomplish this. If you would have read the documentation, you could have found that pretty easily.
Anyway, basically you need to set the tooltips mode to index in your chart options, in order to accomplish the behavior you want.
...
options: {
tooltips: {
mode: 'index'
}
}
...
Additionally, you probably want to set the following:
...
options: {
tooltips: {
mode: 'index',
intersect: false
},
hover: {
mode: 'index',
intersect: false
}
}
...
This will make it so all of the expected hover/label interactions will occur when hovering anywhere on the graph at the nearest x-value.
From the Documentation :
# index
Finds item at the same index. If the intersect setting is true, the
first intersecting item is used to determine the index in the data. If
intersect false the nearest item, in the x direction, is used to
determine the index.
Here is a working example :
var ctx = document.getElementById('canvas').getContext('2d');
var chart = new Chart(ctx, {
type: 'line',
data: {
labels: ['Jan 01', 'Jan 02', 'Jan 03'],
datasets: [{
label: 'Apples Sold',
data: [3, 5, 1],
borderColor: 'rgba(255, 99, 132, 0.8)',
fill: false
}, {
label: 'Oranges Sold',
data: [0, 10, 2],
borderColor: 'rgba(255, 206, 86, 0.8)',
fill: false
}, {
label: 'Gallons of Milk Sold',
data: [5, 7, 4],
borderColor: 'rgba(54, 162, 235, 0.8)',
fill: false
}]
},
options: {
tooltips: {
mode: 'index',
intersect: false
},
hover: {
mode: 'index',
intersect: false
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.2/Chart.min.js"></script>
<canvas id="canvas"></canvas>
For Chart.js 3.3.2, you can use #baburao's approach with a few changes. You can check the documentation. Put tooltip in plugins. Example:
...
options: {
plugins: {
tooltip: {
mode: 'nearest',
intersect: false
}
}
}
...
I know this is an old post, but in a time I needed to divide a bar on multiple datasets, but the labels to be keeped as original values:
eg:
dataset 1: Totals: 10 15 10
dataset 2: Red: 4 5 9
dataset 3: Blue: 4 2 1
In my chart I want to show the "Totals" bar and to collor a part of it in red/blue or "the rest" (which is Totals color). I'll don't write the code to modify the datasets, but I'll complete #busterroni answer for chartjs v3+
plugins: {
tooltip: {
mode: 'index',
intersect: false,
callbacks: {
label: (item) => item.dataset.label + ': ' +
this.originalValues[item.datasetIndex].data[item.dataIndex]
}
}
}
You can achieve this after plotting the data like this:
Html
<div class="container">
<h2>Chart.js — Line Chart Demo</h2>
<div>
<canvas id="myChart"></canvas>
</div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.1.4/Chart.min.js">
</script>
CSS
.container {
width: 80%;
margin: 15px auto;
}
Javascript
var ctx = document.getElementById('myChart').getContext('2d');
function convert(str) {
var date = new Date(str),
mnth = ("0" + (date.getMonth() + 1)).slice(-2),
day = ("0" + date.getDate()).slice(-2);
return [date.getFullYear(), mnth, day].join("-");
}
var date = ["Tue Jun 25 2019 00:00:00 GMT+0530 (India Standard Time)"];
var y1 = [12];
var y2 = [32];
var y3 = [7];
var dataPoints1 = [], dataPoints2 = [], dataPoints3 = [], datep=[];
console.log(date.length)
if(date.length=="1"){
var myChart = new Chart(ctx, {
type: 'line',
data: {
labels: ["",convert(date[0]),""],
datasets: [{
label:"Tweets",
backgroundColor: "rgba(153,255,51,0.4)",
fill:false,
borderColor:"rgba(153,255,51,0.4)",
data: [null,y1[0],null]
}, {
label:"Retweets",
backgroundColor: "rgba(255,153,0,0.4)",
fill:false,
borderColor:"rgba(255,153,0,0.4)",
data: [null,y2[0],null]
},{
label:"Favourites",
backgroundColor: "rgba(197, 239, 247, 1)",
fill:false,
borderColor:"rgba(197, 239, 247, 1)",
data:[null,y3[0],null]
}
]
},
options: {
scales: {
xAxes: [{
gridLines: {
display: false
}
}],
yAxes: [{
ticks: {
display: true
},
gridLines: {
display: false,
// drawBorder: false //maybe set this as well
}
}]
},
}
});}
else{
for (var i = 0; i < date.length; i++) {
datep.push(convert(date[i]))
dataPoints1.push(y1[i]);
dataPoints2.push(y2[i]);
dataPoints3.push(y3[i]);
}
console.log(datep)
var myChart = new Chart(ctx, {
type: 'line',
data: {
labels: datep,
datasets: [{
label:"Tweets",
backgroundColor: "rgba(153,255,51,0.4)",
fill:false,
borderColor:"rgba(153,255,51,0.4)",
data: dataPoints1
}, {
label:"Retweets",
backgroundColor: "rgba(255,153,0,0.4)",
fill:false,
borderColor:"rgba(255,153,0,0.4)",
data: dataPoints2
},{
label:"Favourites",
backgroundColor: "rgba(197, 239, 247, 1)",
fill:false,
borderColor:"rgba(197, 239, 247, 1)",
data:dataPoints3
}
]
},
options: {
scales: {
xAxes: [{
gridLines: {
display: false
}
}],
yAxes: [{
ticks: {
display: true
},
gridLines: {
display: false,
// drawBorder: false //maybe set this as well
}
}]
},
}
});
}
or chk this fiddle https://jsfiddle.net/gqozfb4L/
You could try using JavaScript to track the users mouse and based on the position, return the data at that vertice.
document.querySelector('.button').onmousemove = (e) => {
const x = e.pageX - e.target.offsetLeft
const y = e.pageY - e.target.offsetTop
e.target.style.setProperty('--x', `${ x }px`)
e.target.style.setProperty('--y', `${ y }px`)
}

Remove excess lines on y axis using chartjs

I wonder how to remove the excess lines on the line chart. I tried to set drawborder to false but of course it just remove the all lines to the axis. I just wanted get rid of the unwanted vertical lines that points to the y axis labels like the image below with red mark.
Template:
<d-chartrecord
:chart-data="datacollection"
v-bind:options="options"
:height="200"
></d-chartrecord>
Script:
export default {
data () {
return {
datacollection: {},
options: {
responsive: true,
legend: {
display: false,
},
scales: {
xAxes: [{
gridLines: {
display: true,
color: '#D7D7D7'
},
ticks: {
fontSize: 8,
beginAtZero: true
},
gridLines: {
display: true,
}
}],
yAxes: [{
display: true,
ticks: {
fontSize: 8,
beginAtZero: true,
stepSize: 50,
maxTicksLimit: 3
}
}],
}
},
}
},
mounted () {
this.putData()
},
methods: {
putData () {
this.datacollection = {
labels: ['JAN', 'FEB', 'MAR', 'APR', 'MAY', 'JUN', 'JUL', 'AUG', 'SEP', 'OCT', 'NOV', 'DEC'],
datasets: [{
lineTension: 0,
radius: 4,
borderWidth: 1,
borderColor: '#F2A727',
pointBackgroundColor:[ '#fff', '#fff', '#fff', '#fff', '#fff', '#F2A727'],
backgroundColor: 'transparent',
data: [this.getRandomInt(), this.getRandomInt(), this.getRandomInt(), this.getRandomInt(), this.getRandomInt(), this.getRandomInt()]
}]
}
},
getRandomInt () {
return Math.floor(Math.random() * (95)) + 5
}
}
}
In chart.js, gridLines provides an option tickMarkLength to disable the length beyond the axes, Eg:
yAxes: [{
gridLines: {
tickMarkLength: 0,
},
}]
xAxes: [{
gridLines: {
tickMarkLength: 0,
},
}]
Unfortunately, there isn't any native functionality for this in ChartJS at the moment. You would rather need to create a chart plugin to achieve that.
ᴘʟᴜɢɪɴ (ᴅʀᴀᴡ x-ᴀxɪꜱ ɢʀɪᴅ-ʟɪɴᴇꜱ)
­
Chart.plugins.register({
beforeDraw: function(chart) {
var ctx = chart.chart.ctx,
x_axis = chart.scales['x-axis-0'],
topY = chart.scales['y-axis-0'].top,
bottomY = chart.scales['y-axis-0'].bottom;
x_axis.options.gridLines.display = false;
x_axis.ticks.forEach(function(label, index) {
if (index === 0) return;
var x = x_axis.getPixelForValue(label);
ctx.save();
ctx.beginPath();
ctx.strokeStyle = x_axis.options.gridLines.color;
ctx.moveTo(x, topY);
ctx.lineTo(x, bottomY);
ctx.stroke();
ctx.restore();
});
}
});
* place this at the top of your script
ᴡᴏʀᴋɪɴɢ ᴇxᴀᴍᴘʟᴇ ⧩
Chart.plugins.register({
beforeDraw: function(chart) {
var ctx = chart.chart.ctx,
x_axis = chart.scales['x-axis-0'],
topY = chart.scales['y-axis-0'].top,
bottomY = chart.scales['y-axis-0'].bottom;
x_axis.options.gridLines.display = false; // hide original grid-lines
// loop through x-axis ticks
x_axis.ticks.forEach(function(label, index) {
if (index === 0) return;
var x = x_axis.getPixelForValue(label);
ctx.save();
ctx.beginPath();
ctx.strokeStyle = x_axis.options.gridLines.color;
ctx.moveTo(x, topY);
ctx.lineTo(x, bottomY);
ctx.stroke();
ctx.restore();
});
}
});
var chart = new Chart(ctx, {
type: 'line',
data: {
labels: ['Jan', 'Feb', 'Mar', 'Apr', 'May'],
datasets: [{
label: 'LINE',
data: [3, 1, 4, 2, 5],
backgroundColor: 'rgba(0, 119, 290, 0.2)',
borderColor: 'rgba(0, 119, 290, 0.6)',
fill: false,
tension: 0
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: true,
stepSize: 1
},
gridLines: {
display: false
}
}]
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.min.js"></script>
<canvas id="ctx"></canvas>
in Chart.js (I'm using version 2.9), gridLines also provides an option to disable the tick mark : drawTicks.
scales: {
xAxes: [{
gridLines:{
drawTicks: false
}
}]
}