chartjs - display nth string X-axis label? - javascript

I am trying to display every nth label on the x-axis in Chartjs based on the length of the labels. I saw a similar question: Link but the answer doesn't work for me. I went through the documentation for tick-configuration-options and wasn't able to make it work.
Example code:
const labels = ['11-02-2022', '11-01-2022', '30-01-2022', '11-20-2022']
const options = {
responsive: true,
maintainAspectRatio: false,
scales: {
xAxes: [{
ticks: {
maxTicksLimit: 3 # Once this works I want to make it conditional i.e. if length == 10 display 10/2
}
}]
},
interaction: {
intersect: false
},
animations:animation,
plugins: {
legend: {
position: 'top',
},
},
};
Would be great if someone can give a little explanation on what exactly I should have checked to fix the problem myself.

See https://www.chartjs.org/docs/latest/axes/labelling.html
basically, you set the ticks value. You use a ternary to decide when to show, e.g.
options: {
scales: {
y: {
ticks: {
// Only show if n'th
callback: function(value, index, ticks) {
return index%3 ? value : '';
}
}
}
}
}

Related

Chart.js is removing the final x-axis label when toggling between views

I am using JS/JQuery/Kendo and have and am attempting to toggle between two different view types in the same graph. The first view is of a Cadence (Week) within a period (Months), on initial render the x-axis labels are correct in showing the start and end of a cadence, for sake of this example lets say the cadence starts on 2/2/23 and ends on 2/9/23, the graph points and labels are correct, but when clicking on the button to toggle the views, the cadence week is also correct on the graphs but instead of showing the end date of 2/9, the graph in this view stops at the current date, but also does not render, all that shows is the most recent update, this is less of a concern at the moment because if I toggle back to the original view of the cadence, suddenly the final date is cut off, so instead of seeing 2/2-2/9, we now see 2/2-2/8 and I have no clue why, I've tried using the offset as well as autoSkip properties but I'm still seeing the behavior, in my call to render the graph I am also using chart.update() but still seeing the incorrect data points. Here is my code, note that the definitions are in a call to render the graph, hence the chart.update() at the bottom of the definitions:
var customLineScales: {
xAxes: any[],
yAxes: {
ticks: {
suggestedMin: number,
suggestedMax: number,
userCallback: (value: any, index: number, values: any[]) => string
}
} []
} = {
xAxes: [{
type: 'time',
time: {
tooltipFormat: 'll',
unit: 'day',
min: chartStart,
max: chartEnd
},
ticks: {
suggestedMin: chartStart,
suggestedMax: chartEnd,
},
gridLines: {
display: false,
drawBorder: false,
}
}],
yAxes: []
};
var chart = new Chart(lineChart, {
type: 'line',
data: {
labels: cleanedUpdateLabels,
datasets: [{
label: historicalData.Name,
data: cleanedUpdateDataPoints,
}]
},
options: {
responsive: true,
elements: {
point: {
hitRadius: hitRadius,
hoverRadius: 5,
radius: UpdateValueRadius
},
scales: customLineScales,
});
chart.update();
Code for toggle switch:
if (Cadence === "Weekly") {
var weekSoFar = historicalData.HistoricalUpdates.map(function (update: any) {
if (vm.get('showPeriod')) {
return update.Date;
} else {
if (update.Date >= cadence.startDate && update.Date <= cadence.endDate) {
return update.Date;
}
}
});
if (vm.get('showPeriod')) {
chart.data.labels = cleanedUpdateLabels;
} else {
newChart.data.labels = cleanedUpdateLabels;
}
}

zeroLineColor and zeroLineWidth not working for the x-axis in Chartjs

How to change the width and the color of the x-axis (horizontal axis) in Chartjs? It seems to work using zeroLineColor and zeroLineWidth for the y-axis (vertical one), but it does not work for the x-axis.
If we add:
ticks: {
beginAtZero: true
}
It works as expected, but I don't want the vertical ticks to start from 0.
Is there a way to make this happen?
scales: {
xAxes: [{
gridLines: {
zeroLineColor: 'black', // WORKS
zeroLineWidth: 2 // WORKS
},
display: true
}],
yAxes: [{
gridLines: {
zeroLineColor: 'black', // DOES NOT WORK
zeroLineWidth: 2, // DOES NOT WORK
},
id: 'y-axis-0',
display: true,
ticks: {
// beginAtZero: true // This is what I dont't want to use
}
}]
}
This is the result I get with the previous code:
As you can see, the x-axis is displayed without changes in color or width.
I'm using version 2.9.4 of the Chartjs library.
Go to the .js of the library (in my case: 'node_modules/chart.js/dist/Chart.bundle.js') and, in the line 12202, you will find this conditional:
if (i === me.zeroLineIndex && options.offset === offsetGridLines) {
Transform it into this:
if ((i === me.zeroLineIndex || (!isHorizontal && i === ticksLength - 1)) && options.offset === offsetGridLines) {
Then, do whatever compression or manipulation of the file you need to do to add it to your project.
It's not the best solution, but it's the one I came up with.

Chart.js Y axis label, reverse tooltip order, shorten X axis labels

I am creating a stacked bar chart using Chart.js. However, I cannot find in the documentation how to change some things.
How to add a label on the Y axis.
How to shorten the label on the X axis so it displays only
the first 10 letters.
How to reverse the order in which the values are shown in
the tooltip.
Are these thigs are possible to implement?
I have marked what I want to change here.
Here are what my chart options look like now:
var ctx = $("#newchart");
var barGraph = new Chart(ctx, {
type: 'bar',
data: chartdata,
options: {
barValueSpacing: 20,
tooltips: {
enable: true,
mode: 'label',
callbacks: {
label: function(tooltipItem, data){
var datasetLabel = data.datasets[tooltipItem.datasetIndex].label || '';
return datasetLabel + ': ' + Number(tooltipItem.yLabel) + ' Users';
}
}
},
responsive: true,
segmentShowStroke: true,
scales: {
xAxes: [{
display: false,
stacked: true,
ticks:{
stepSize : 10,
},
gridLines: {
lineWidth: 0,
color: "#9E9E9E"
}
}],
yAxes: [{
stacked: true,
ticks: {
min: 0,
stepSize: 10,
},
gridLines: {
lineWidth: 0,
color: "#9E9E9E"
}
}]
}
}
});
1. Adding a Y-axis label
in the yAxes object give it a scaleLabel object that takes in labelString (example fiddle)
yAxes: [{
scaleLabel: {
labelString: 'Value'
}
}]
2. Shortening xAxis category labels
For this, you can pass a userCallback function to the xAxis ticks object that can return your desired output. The function will take in the original label in its first parameter so you can just return a substring at your desired length, example fiddle
xAxes: [{
ticks: {
userCallback: function(label, index, labels) {
if(typeof label === "string")
{
return label.substring(0,1)
}
return label;
},
}
}],
3. reverse tooltip order
The tooltips object accepts a function called itemSort that can be passed to Array.prototype.sort.
So you could so something like below, but you may also need to compare the objects index as well as the datasetIndex to get your desired result. (example fiddle)
tooltips: {
mode: 'label',
itemSort: function(a, b) {
return b.datasetIndex - a.datasetIndex
},
},

Chart.JS custom y axis labels with text that has value

I want to make a bar graph like this.. is it possible in chart.js?
assuming that OK, Difficult, and Problematic has its own value..
Example:
Problematic = 11 or more
Difficult = 6 - 10
OK = 0 - 5
Yes, like this:
options: {
scales: {
yAxes: [{
ticks: {
userCallback: function(value) {
return value;
},
stepSize: 1
}
}]
},
},
You can also set the step size.

jQuery Flot xaxis elements number

Im trying to generate graph with jquery Flot.
This is the script Im using:
var plot = $.plot("#placeholder", [
{ data: data2, label: observation_obj.concept_name}
], {
series: {
lines: {
show: true
},
points: {
show: true
}
},
grid: {
hoverable: true,
clickable: true
},
yaxis: {
},
xaxis: {
mode: "time",
timeformat: "%d.%m"
}
});
The result I'm getting is this:
http://i62.tinypic.com/25uk51z.png
My data is contains of two points, I dont know why in the x axis I see 4 points,
Can anyone help?
Thanks
The ticks on the x-axis are automatically generated so that they are evenly spaced on the axis. If you want to change that you can give flot an array of (in your case) timestamps which match the timestamps from your data (only examples here):
xaxis: {
mode: "time",
timeformat: "%d.%m",
ticks: [1383582043000, 1383682043000]
}
See the documentation for more infos / examples.

Categories