Format chart.js x labels - javascript

I use chart.js with React. My question is how to show the month label (MMM) only once per month?
The chart currently has labels: [May 15, May 18, May 21, May 24, ...]
As result I want to get: [May 15, 18, 21, 24, 27, 30, Jun 2, 5, ...]
CodeSandbox
Line Chart:
import React from 'react'
import { Line } from 'react-chartjs-2'
import date from 'date-and-time'
const startDate = new Date(2020, 4, 15)
//===fake data===
const json = '{"responses":[{"rows":[{"values":["1"]},{"values":["0"]},{"values":["0"]},{"values":["0"]},{"values":["0"]},{"values":["0"]},{"values":["0"]},{"values":["0"]},{"values":["0"]},{"values":["0"]},{"values":["0"]},{"values":["0"]},{"values":["0"]},{"values":["0"]},{"values":["0"]},{"values":["0"]},{"values":["0"]},{"values":["0"]},{"values":["0"]},{"values":["0"]},{"values":["0"]},{"values":["0"]},{"values":["0"]},{"values":["0"]},{"values":["0"]},{"values":["0"]},{"values":["0"]},{"values":["0"]},{"values":["0"]},{"values":["0"]},{"values":["0"]},{"values":["0"]},{"values":["0"]},{"values":["0"]},{"values":["0"]},{"values":["0"]},{"values":["0"]},{"values":["0"]},{"values":["0"]},{"values":["0"]},{"values":["0"]},{"values":["0"]},{"values":["0"]},{"values":["0"]},{"values":["0"]},{"values":["0"]},{"values":["0"]},{"values":["0"]},{"values":["1"]},{"values":["6"]},{"values":["7"]},{"values":["5"]},{"values":["8"]},{"values":["9"]},{"values":["2"]},{"values":["1"]},{"values":["1"]},{"values":["1"]},{"values":["6"]},{"values":["3"]},{"values":["0"]},{"values":["20"]},{"values":["9"]},{"values":["3"]},{"values":["2"]},{"values":["1"]},{"values":["13"]},{"values":["3"]},{"values":["13"]},{"values":["13"]},{"values":["7"]},{"values":["12"]},{"values":["0"]}]}]}'
const values = JSON.parse(json).responses[0].rows.map((row, index) => {
let date = new Date(2020, 4, 20)
date.setDate(startDate.getDate() + index)
return {
y: row.values[0],
x: date,
}
})
//===============
const options = {
legend: {
display: false,
},
hover: {
mode: 'index',
intersect: false,
animationDuration: 0,
},
scales: {
yAxes: [{ position: 'right' }],
xAxes: [{
gridLines: { display: false },
distribution: 'linear',
type: 'time',
time: {
parser: 'MMM D',
tooltipFormat: 'MMM D',
unit: 'day',
unitStepSize: 3,
displayFormats: {
day: 'MMM D',
},
},
ticks: {
min: startDate,
max: date.format(date.addDays(new Date(), 1), 'MMM D'),
autoSkip: true
},
}],
},
tooltips: {
mode: 'x-axis',
},
}
const data = {
datasets: [
{
label: 'test',
fill: false,
data: values,
backgroundColor: '#fff',
borderWidth: 2,
lineTension: 0,
borderColor: 'forestgreen',
hoverBorderWidth: 2,
pointBorderColor: 'rgba(0, 0, 0, 0)',
pointBackgroundColor: 'rgba(0, 0, 0, 0)',
pointHoverBackgroundColor: '#fff',
pointHoverBorderColor: 'forestgreen',
showLine: true,
}
],
}
const LineChart = () => <Line data={data} options={options}/>
export default LineChart

Solution 1 label filter:
According to the filtering labels sample you can set a function to define what should be displayed:
options: {
scales: {
x: {
display: true,
ticks: {
callback: function(dataLabel, index) {
// Apply logic to remove name of the month
return dataLabel
}
}
},
y: {
display: true,
beginAtZero: false
}
}
}
Github source of the example
Solution 2:
You could prepare your labels array beforehand. Filter the occurence of all the upcoming mentions and feed this array to chart.js.

Define different displayFormats for day and month.
Enable ticks.major.
Mark the desired ticks as major through the afterBuildTicks callback.
time: {
...
displayFormats: {
day: 'D',
month: 'MMM D',
},
},
ticks: {
major: {
enabled: true
}
},
afterBuildTicks: (scale, ticks) => {
ticks.forEach((t, i) => t.major = i == 0 || new Date(t.value).getMonth() != new Date(ticks[i - 1].value).getMonth());
return ticks;
}
Please take a look at your amended code and see how it works.
const startDate = new Date(2020, 4, 15)
//===fake data===
const json = '{"responses":[{"rows":[{"values":["1"]},{"values":["0"]},{"values":["0"]},{"values":["0"]},{"values":["0"]},{"values":["0"]},{"values":["0"]},{"values":["0"]},{"values":["0"]},{"values":["0"]},{"values":["0"]},{"values":["0"]},{"values":["0"]},{"values":["0"]},{"values":["0"]},{"values":["0"]},{"values":["0"]},{"values":["0"]},{"values":["0"]},{"values":["0"]},{"values":["0"]},{"values":["0"]},{"values":["0"]},{"values":["0"]},{"values":["0"]},{"values":["0"]},{"values":["0"]},{"values":["0"]},{"values":["0"]},{"values":["0"]},{"values":["0"]},{"values":["0"]},{"values":["0"]},{"values":["0"]},{"values":["0"]},{"values":["0"]},{"values":["0"]},{"values":["0"]},{"values":["0"]},{"values":["0"]},{"values":["0"]},{"values":["0"]},{"values":["0"]},{"values":["0"]},{"values":["0"]},{"values":["0"]},{"values":["0"]},{"values":["0"]},{"values":["1"]},{"values":["6"]},{"values":["7"]},{"values":["5"]},{"values":["8"]},{"values":["9"]},{"values":["2"]},{"values":["1"]},{"values":["1"]},{"values":["1"]},{"values":["6"]},{"values":["3"]},{"values":["0"]},{"values":["20"]},{"values":["9"]},{"values":["3"]},{"values":["2"]},{"values":["1"]},{"values":["13"]},{"values":["3"]},{"values":["13"]},{"values":["13"]},{"values":["7"]},{"values":["12"]},{"values":["0"]}]}]}'
const values = JSON.parse(json).responses[0].rows.map((row, index) => {
let date = new Date(2020, 4, 20);
date.setDate(startDate.getDate() + index)
return {
y: row.values[0],
x: date
}
})
//===============
const options = {
legend: {
display: false
},
hover: {
mode: 'index',
intersect: false,
animationDuration: 0
},
scales: {
yAxes: [{
position: 'right'
}],
xAxes: [{
gridLines: {
display: false
},
distribution: 'linear',
type: 'time',
time: {
tooltipFormat: 'MMM D',
unit: 'day',
unitStepSize: 3,
displayFormats: {
day: 'D',
month: 'MMM D',
},
},
ticks: {
major: {
enabled: true
}
},
afterBuildTicks: (scale, ticks) => {
ticks.forEach((t, i) => t.major = i == 0 || new Date(t.value).getMonth() != new Date(ticks[i - 1].value).getMonth());
return ticks;
}
}]
},
tooltips: {
mode: 'x-axis',
}
};
const data = {
datasets: [{
label: 'test',
fill: false,
data: values,
backgroundColor: '#fff',
borderWidth: 2,
lineTension: 0,
borderColor: 'forestgreen',
hoverBorderWidth: 2,
pointBorderColor: 'rgba(0, 0, 0, 0)',
pointBackgroundColor: 'rgba(0, 0, 0, 0)',
pointHoverBackgroundColor: '#fff',
pointHoverBorderColor: 'forestgreen',
showLine: true,
}],
};
new Chart('myChart', {
type: 'line',
data: data,
options: options
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.bundle.min.js"></script>
<canvas id="myChart" height="90"></canvas>

Related

Is there anyway to overlap one barchart with another in chart js without stacking them?

I tried using the stack and offset but it does not seem to work
This is my code:
import React, {
useEffect
} from 'react';
import {
Bar
} from 'react-chartjs-2';
import useWindowWidth from 'wa-shared/src/hooks/useWindowWidth';
const state = {
count: 0,
data: {
labels: [
['Total Users'],
['Users with', 'Active', 'Session'],
['Created 1', 'or More', 'Videos'],
['Shared 1', 'or More', 'Videos']
],
datasets: [{
backgroundColor: '#26863D',
data: [70, 66, 57, 1],
barThickness: '35',
},
{
backgroundColor: '#F2F2F2',
data: [70, 70, 70, 70],
borderRadius: '5',
barThickness: '35',
}
]
}
}
const App = ({}) => {
const width = useWindowWidth();
useEffect(() => {});
return ( <
div className = 'singlebar-chart'
id = "barchart" >
<Bar> data = {
state.data
}
options = {
{
scales: {
x: {
grid: {
display: false,
},
offset: true,
ticks: {
maxRotation: 0,
minRotation: 0,
font: {
size: 8,
}
},
},
y: {
min: 0,
max: 100,
ticks: {
fontColor: '#8A8A8A',
font: {
size: 8,
},
stepSize: 25,
callback: function(value) {
return value + "%"
},
},
scaleLabel: {
display: true,
labelString: "Percentage",
},
grid: {
display: false,
}
}
},
plugins: {
legend: {
display: false,
},
}
}
</Bar>
</div>
)
}
export default App;
.singlebar-chart{
width: 95%;
}
You can use a second x axis and map the other dataset to that axes:
var options = {
type: 'bar',
data: {
labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
datasets: [{
label: '# of Votes',
data: [12, 19, 3, 5, 2, 3],
backgroundColor: 'pink'
},
{
label: '# of Points',
data: [7, 11, 5, 8, 3, 7],
backgroundColor: 'orange',
xAxisID: 'x2'
}
]
},
options: {
scales: {
x: {},
x2: {
display: false // Dont show the axes since it is just a duplicate
}
}
}
}
var 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.8.0/chart.js"></script>
</body>
Although this gives the exect same result as setting stacked true on the x axis.

chart.js cuts data points to half

I have a chart showing website calls the last 7 days. There it is:
Here is the initialization:
varwebsitecalls_chart = new Chart(websitecalls_chartel, {
type: 'line',
data: {
labels: ["Sa", "So", "Mo", "Di", "Mi", "Do", "Fr"],
datasets: [{
label: 'Websitecalls',
data: [0, 0, 0, 0, 0, 0, 0],
borderWidth: 2,
borderColor: '#00000',
backgroundColor: '#ffff',
pointStyle: 'circle',
pointRadius: 7,
cubicInterpolationMode: 'monotone',
tension: 0.4,
}]
},
options: {
responsive: true,
plugins: {
legend: {
display: false
},
},
scales: {
x: {
grid: {
display: false,
}
},
y: {
min: 0,
ticks: {
precision: 0,
font: {
family: 'Montserrat',
},
},
grid: {
borderDash: [5, 5],
}
},
}
},
});
Problem:
The Problem is that the chart cuts of the circles when the data is 0 because I set min to 0. I have to set min to 0 because negative websitecalls can not exist. If I do not set it -1 will be displayed. Is there a way to fix this designtechnical issue?
Thanks in advance,
Filip.
No idea why, but defining y.beginAtZero: true instead of y.min: 0 will solve the problem.
Please take a look at your amended and runnable code and see how it works.
new Chart('websitecalls_chartel', {
type: 'line',
data: {
labels: ["Sa", "So", "Mo", "Di", "Mi", "Do", "Fr"],
datasets: [{
label: 'Websitecalls',
data: [0, 0, 0, 0, 0, 0, 0],
borderWidth: 2,
borderColor: '#00000',
backgroundColor: '#ffff',
pointStyle: 'circle',
pointRadius: 7,
cubicInterpolationMode: 'monotone',
tension: 0.4,
}]
},
options: {
responsive: true,
plugins: {
legend: {
display: false
},
},
scales: {
x: {
grid: {
display: false,
}
},
y: {
beginAtZero: true,
ticks: {
precision: 0,
font: {
family: 'Montserrat',
},
},
grid: {
borderDash: [5, 5],
}
},
}
},
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.7.1/chart.js"></script>
<canvas id="websitecalls_chartel" height="80"></canvas>
Chart.js documentation states...
beginAtZero: if true, scale will include 0 if it is not already included.
min: user defined minimum number for the scale, overrides minimum value from data.

how to highlight stack bar in ChartJS with onclick

Is it possible to select a column in a stack bar chart with a colored border? Like this
I started from here:
https://jsfiddle.net/sdfx/hwx9awgn/
// Return with commas in between
var numberWithCommas = function(x) {
return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
};
var dataPack1 = [40, 47, 44, 38, 27, 31, 25];
var dataPack2 = [10, 12, 7, 5, 4, 6, 8];
var dataPack3 = [17, 11, 22, 18, 12, 7, 5];
var dates = ["SN 1.0.1", "SN 1.0.2", "SN 1.0.3", "SN 1.0.4", "SN 1.0.5", "SN 2.0.0", "SN 2.0.1"];
// Chart.defaults.global.elements.rectangle.backgroundColor = '#FF0000';
var bar_ctx = document.getElementById('bar-chart');
var bar_chart = new Chart(bar_ctx, {
type: 'bar',
data: {
labels: dates,
datasets: [{
label: 'Bad Style',
data: dataPack1,
backgroundColor: "#512DA8",
hoverBackgroundColor: "#7E57C2",
hoverBorderWidth: 0
}, {
label: 'Warning',
data: dataPack2,
backgroundColor: "#FFA000",
hoverBackgroundColor: "#FFCA28",
hoverBorderWidth: 0
}, {
label: 'Error',
data: dataPack3,
backgroundColor: "#D32F2F",
hoverBackgroundColor: "#EF5350",
hoverBorderWidth: 0
}, ]
},
options: {
animation: {
duration: 10,
},
tooltips: {
mode: 'label',
callbacks: {
label: function(tooltipItem, data) {
return data.datasets[tooltipItem.datasetIndex].label + ": " + numberWithCommas(tooltipItem.yLabel);
}
}
},
scales: {
xAxes: [{
stacked: true,
gridLines: {
display: false
},
}],
yAxes: [{
stacked: true,
ticks: {
callback: function(value) {
return numberWithCommas(value);
},
},
}],
}, // scales legend: {display: true} } // options } );
Yes what you can do is in the onClick as second argument you get an array with all the active elements. So what you can do is loop over each dataset in your chart and see if the index matches one of the list with active elements.
If this is the case you give it a borderWidth of 1, else you put it to 0. After you did this you call chart variable.update();
To make this work you need to remove the hoverBorderWidth of all datasets and give all datasets a borderColor of yellow
Use attribute borderColor with an array and borderWith with and object.
datasets: [
{
label: 'Bad Style',
data: dataPack1,
backgroundColor: "#512DA8",
borderColor: [
'rgb(243, 255, 51)',
'rgb(81,45,168)',
'rgb(243, 255, 51)',
'rgb(81,45,168)',
'rgb(81,45,168)',
'rgb(81,45,168)',
'rgb(81,45,168)',
],
borderWidth: {
top: 0,
right: 4,
bottom: 0,
left: 4
},
},
rgb(243, 255, 51) is yellow color.
To change the color, try this:
var borderColor = [
'rgb(81,45,168)',
'rgb(81,45,168)',
'rgb(81,45,168)',
'rgb(81,45,168)',
'rgb(81,45,168)',
'rgb(81,45,168)',
'rgb(81,45,168)',
];
var bar_ctx = document.getElementById('bar-chart');
var bar_chart = new Chart(bar_ctx, {
type: 'bar',
data: {
labels: dates,
datasets: [
{
label: 'Bad Style',
data: dataPack1,
backgroundColor: "#512DA8",
hoverBackgroundColor: "#7E57C2",
hoverBorderWidth: 0,
borderColor: borderColor,
borderWidth: '4',
},
{
label: 'Warning',
data: dataPack2,
backgroundColor: "#FFA000",
hoverBackgroundColor: "#FFCA28",
hoverBorderWidth: 0,
borderColor: borderColor,
borderWidth: '4',
},
{
label: 'Error',
data: dataPack3,
backgroundColor: "#D32F2F",
hoverBackgroundColor: "#EF5350",
hoverBorderWidth: 0,
borderColor: borderColor,
borderWidth: '4',
},
]
},
options: {
onClick: function(e){
var element = this.getElementAtEvent(e);
borderColor[element[0]._index] = 'rgb(244,140,4)';
this.update();
},
animation: {
duration: 10,
},
tooltips: {
mode: 'label',
callbacks: {
label: function(tooltipItem, data) {
return data.datasets[tooltipItem.datasetIndex].label + ": " + numberWithCommas(tooltipItem.yLabel);
}
}
},
scales: {
xAxes: [{
stacked: true,
gridLines: { display: false },
}],
yAxes: [{
stacked: true,
ticks: {
callback: function(value) { return numberWithCommas(value); },
},
}],
}, // scales
legend: {display: true}
} // options
}
);

Displaying line chart for multiple months using chart.js

I have to display a line chart with two different datasets in one single chart. After execution of the query I got the plan_plan and actual_plan of the following form.
plan_plan = 0: {label: "Feb-20", plan_hrs: "20"}
1: {label: "Oct-20", plan_hrs: "94"}
actual_plan = 0: {label: "Mar-20", actual_hrs: "1"}
javacript code:
function show_Graph()
{
{
var plandata = <?php echo json_encode($plan_plan); ?>;
var actualdata = <?php echo json_encode($actual_plan); ?>;
var labels = [];
for (var i in plandata) {
labels.push(plandata[i].label);
}
for (var j in actualdata) {
labels.push(actualdata[j].label);
}
new Chart("scurve_chart", {
type: 'line',
data: {
labels: Array.from(labels),
datasets: [{
label: "Planned Hours",
fill: false,
borderColor: "rgba(255, 0, 0, 1)",
pointHoverBackgroundColor: "rgba(255, 0, 0, 1)",
data: plandata.map(o => ({ x: Number(o.label), y: Number(o.plan_hrs)}))
},
{
label: "Actual Hours",
fill: false,
backgroundColor: "rgba(0, 255, 0, 0.75)",
borderColor: "rgba(0, 255, 0, 1)",
pointHoverBackgroundColor: "rgba(0, 255, 0, 1)",
pointHoverBorderColor: "rgba(0, 255, 0, 1)",
data: actualdata.map(o => ({x: Number(o.label), y: Number(o.actual_hrs)}))
}
]
},
options: {
tooltips: {
callbacks: {
title: (tooltipItem, data) => "Month " + data.datasets[tooltipItem[0].datasetIndex].data[tooltipItem[0].index].x
}
},
scales: {
yAxes: [{
ticks: {
beginAtZero: true
},
scaleLabel: {
display: true,
labelString: 'Hours'
}
}],
xAxes: [{
ticks: {
min: 0,
max: 53,
stepSize: 1
},
scaleLabel: {
display: true,
labelString: 'Month'
}
}]
}
}
});
}}
I want to get the month in the format (Jan-20) in x-axis and then plan_hrs and actual_hrs data in y-axis which can be shown as a line chart. And also should show a single point entry even when there are no data points to be connected. I have used the script tags:
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.bundle.js"></script>
But it is not showing graph when I am including the following script for bootstrap:
<script src="build/js/custom.min.js">
I can help for parsing and displaying the dates on the xAxis but unfortunately I don't know Bootstrap.
Define your xAxis as follows:
xAxes: [{
type: 'time',
time: {
parser: 'MMM-YY',
unit: 'month',
displayFormats: {
month: 'MMM-YY'
}
}
}]
Chart.js internally uses Moment.js, hence you can use the following date/time formats for parsing and displaying the date. In your case, this is 'MMM-YYD'.
const plan_plan = [{label: "Feb-20", plan_hrs: "20"}, {label: "Oct-20", plan_hrs: "94"}];
const actual_plan = [{label: "Mar-20", actual_hrs: "1"}];
new Chart("scurve_chart", {
type: 'line',
data: {
datasets: [{
label: "Planned Hours",
fill: false,
borderColor: "rgba(255, 0, 0, 1)",
data: plan_plan.map(o => ({ x: o.label, y: Number(o.plan_hrs)}))
},
{
label: "Actual Hours",
fill: false,
borderColor: "rgba(0, 255, 0, 1)",
data: actual_plan.map(o => ({x: o.label, y: Number(o.actual_hrs)}))
}
]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}],
xAxes: [{
type: 'time',
time: {
parser: 'MMM-YY',
unit: 'month',
displayFormats: {
month: 'MMM-YY'
}
}
}]
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.bundle.js"></script>
<canvas id="scurve_chart" height="90"></canvas>

Change color of X axis values to multi color values - Chart.js

I am using Chart.js (http://www.chartjs.org/docs/) for charting.
My type Chart is Bar.
Label of X axis have 4 lines.
I Change color of X axis values. color of values is one color.
But I want one line per color and color same like the bar color.
var barChartData = {
labels: [["Injection", 10, 20], // here I want to change the color
["Electronics", 5, 15],
["TOTAL", 15, 35]
],
datasets: [{
label: "2018",
backgroundColor: window.chartColors.orange,
yAxisID: 'A',
data: [10, 5, 15]
}, {
label: "2017",
backgroundColor: window.chartColors.green,
yAxisID: 'A',
data: [20, 15, 35]
}]
};
var canvas = document.getElementById('canvas').getContext('2d');
new Chart(canvas, {
type: 'bar',
data: barChartData,
options: {
scales: {
yAxes: [{
id: 'A',
type: 'linear',
position: 'left',
}, {
id: 'B',
type: 'linear',
position: 'right',
ticks: {
max: 100,
min: 0
}
}],
xAxes: [{
ticks: {
fontColor: "#222", // This here that I changed.
},
}]
}
}
})
I want to change color of labels are 10, 5, 15 is orange and 20, 15, 35 is green and Injection, Electronics, TOTAL is black
Can I do that? How?
var myData = [
["id1","test 11111","AA",1.95],
["id2","test 2","BB",1.94],
["id3","test 3","CC",1.93],
["id4","test 4","DD",1.93],
["id5","test 5","EE",1.91],
["id6","test 6","FF",1.90],
["id7","test 7","GG",1.82],
["id8","test 8","HH",1.85],
["id9","test 9","II",1.83],
["id10","test 10","JJ",1.79]
];
var ctx = $("#c");
var myChart = new Chart(ctx, {
type: 'bar',
data: {
datasets: [{
label: '# of Votes',
xAxisID:'modelAxis',
data: myData.map((entry)=>entry[3])
}]
},
options:{
scales:{
xAxes:[
{
id:'modelAxis',
type:"category",
ticks:{
//maxRotation:0,
autoSkip: false,
callback:function(label, x2, x3, x4){
return label;
}
},
labels:myData.map((entry=>entry[1]))
},
{
id:'groupAxis',
type:"category",
gridLines: {
display: false,
drawBorder: false,
drawOnChartArea: false,
offsetGridLines: false
},
ticks:{
padding:0,
maxRotation:0,
fontSize: 10,
fontColor: '#FF9090',
autoSkip: false,
callback:function(label){
return label;
}
},
offset: true,
labels:myData.map((entry=>entry[1]))
},{
id:'groupAxis2',
type:"category",
gridLines: {
display: false,
drawBorder: false,
drawOnChartArea: false,
offsetGridLines: false
},
scaleLabel:{
padding: 10,
},
ticks:{
padding:0,
fontSize: 10,
fontColor: '#AB64F4',
maxRotation:0,
autoSkip: false,
callback:function(label){
return label;
}
},
offset: true,
labels:myData.map((entry=>entry[1]))
}
],
yAxes:[{
ticks:{
beginAtZero:true
}
}]
}
}
});

Categories