How to add x axis from the line in bar line chart? - chart.js

I have created a bar/line chart. See below:
The bar and the line are on different scales, namely: kilo's and euro's . Therefore, I want to show on the right side of the graph the xAxis scale of the line (euros). Is it also possible to add a label to the axes?

https://jsfiddle.net/qrwvvtxs/
var barChartData = {
labels: ["January", "February", "March", "April", "May", "June", "July"],
datasets: [{
label: 'Dataset 1',
yAxisID: "y-axis-1",
data: [3,2,7,4,5,7,6]
}, {
type: "line",
fill: false,
label: 'Dataset 2',
borderColor: '#faa',
backgroundColor: "#faa",
yAxisID: "y-axis-2",
data: [11,13,21,13,16,21,18]
}]
};
var ctx = document.getElementById("canvas").getContext("2d");
window.myBar = new Chart(ctx, {
type: 'bar',
data: barChartData,
options: {
responsive: true,
title:{
display:true,
text:"Chart.js Bar Chart - Multi Axis"
},
tooltips: {
mode: 'index',
intersect: true
},
scales: {
yAxes: [{
display: true,
position: "left",
id: "y-axis-1",
ticks: {
callback: function(value, index, values) {
return value + " Kg";
}
}
}, {
display: true,
position: "right",
id: "y-axis-2",
gridLines: {
drawOnChartArea: false
},
ticks: {
callback: function(value, index, values) {
return "€ " + value;
}
}
}],
}
}
});
.wrapper {
width: 100%;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.bundle.min.js"></script>
<div class="wrapper">
<canvas id="canvas"></canvas>
</div>

Related

Tooltip on each data point in Chartjs

Here is my code for putting different tooltip on each data point. I want to put different month on each point, but all the months get printed together. How do I separate them out?
function trendsChart(labels1, datasets1, chartId) {
var ctx =
document.getElementById(chartId).getContext('2d');
var MONTHS = ["January", "February", "March", "April", "May", "June"];
console.log(datasets1)
var data = {
labels: labels1,
datasets: datasets1,
};
// Tooltip
const titleTooltip = (tooltipItems) => {
let sum = 77;
MONTHS.forEach(function(tooltipItem) {
sum = tooltipItem;
})
return sum;
}
var randomScalingFactor = function() {
return (Math.random() > 0.5 ? 1.0 : 1.0) * Math.round(Math.random() * 100);
};
var line1 = [randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor()];
myChart = new Chart(ctx, {
type: 'line',
data: data,
options: {
maintainAspectRatio: false,
responsive: true,
scales: {
x: {
barPercentage: 1.6,
gridLines: {
drawBorder: false,
color: 'rgba(225,78,202,0.1)',
zeroLineColor: "transparent",
},
ticks: {
padding: 0,
fontColor: "#9a9a9a"
},
title: {
display: true,
text: 'Week Of'
}
},
y: {
barPercentage: 1.6,
gridLines: {
drawBorder: false,
color: 'rgba(225,78,202,0.1)',
zeroLineColor: "transparent",
},
ticks: {
padding: 0,
fontColor: "#9a9a9a"
},
stacked: false,
title: {
display: true,
text: 'Count'
}
}
},
plugins: {
tooltip: {
//yAlign: 'bottom',
callbacks: {
title: titleTooltip,
}
}
}
}
});
return myChart;
}
Inside titleTooltip in the pasted code, you replace sum with the last entry from MONTHS. The tooltip from the image however suggests that in the real code, you create an array with 77 and all entries from MONTHS, then you probably return 'Sum: ' + sum, which results in the string you can see in the tooltip.
In order to see all the months on a separate line, you could change your code as follows and return sum as an array:
const titleTooltip = ctx => {
let sum = ['Sum: 77'];
MONTHS.forEach(month => {
sum.push(month);
});
return sum;
}
The resulting tooltip still doesn't make much sense but you'll see all months on a different line. Therefore, you to extend the function titleTooltip in order to obtain the desired result.
Please take a loo at your amended code and see how it works.
function trendsChart(labels1, datasets1, chartId) {
var MONTHS = ["January", "February", "March", "April", "May", "June"];
var data = {
labels: labels1,
datasets: datasets1,
};
// Tooltip
const titleTooltip = ctx => {
let sum = ['Sum: 77'];
MONTHS.forEach(month => {
sum.push(month);
});
return sum;
}
var randomScalingFactor = function() {
return (Math.random() > 0.5 ? 1.0 : 1.0) * Math.round(Math.random() * 100);
};
var line1 = [randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor()];
myChart = new Chart(chartId, {
type: 'line',
data: data,
options: {
maintainAspectRatio: false,
responsive: true,
scales: {
x: {
barPercentage: 1.6,
gridLines: {
drawBorder: false,
color: 'rgba(225,78,202,0.1)',
zeroLineColor: "transparent",
},
ticks: {
padding: 0,
fontColor: "#9a9a9a"
},
title: {
display: true,
text: 'Week Of'
}
},
y: {
barPercentage: 1.6,
gridLines: {
drawBorder: false,
color: 'rgba(225,78,202,0.1)',
zeroLineColor: "transparent",
},
ticks: {
padding: 0,
fontColor: "#9a9a9a"
},
stacked: false,
title: {
display: true,
text: 'Count'
}
}
},
plugins: {
tooltip: {
//yAlign: 'bottom',
callbacks: {
title: titleTooltip,
label: ctx => ctx.label + ': ' + ctx.parsed.y
}
}
}
}
});
return myChart;
}
trendsChart(['created', 'tested', 'reviewed', 'approved'], [{ data: [1, 5, 3, 2]}], 'myChart');
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.8.0/chart.js"></script>
<canvas id="myChart"></canvas>

Chartjs and datalabels : automatic y axis (and dynamic data) hide datalabels

I have a chart (chartjs) with labels (datalabels).
When my data changes, my chart updates automatically. However, the largest datalabels are most of the time hidden by the automatic resizing of the y axis. Do you have any idea to fix that ?
It should be a 3 up there :)
Here is my code:
const completionOptions = {
responsive: true,
plugins: {
legend: {
display: false,
},
tooltip: {
backgroundColor: 'rgb(85, 85, 85, 1)',
displayColors: false,
// https://www.chartjs.org/docs/latest/configuration/tooltip.html
},
datalabels: {
color: 'rgb(203, 203, 203)',
anchor: 'end',
align: 'end',
labels: {
title: {
font: {
family: 'karla',
weight: '600',
size: 12,
},
}
}
}
},
scales: {
display: false,
y: {
beginAtZero: true,
display: false,
grid: {
display: false,
},
ticks: {
padding: 10
}
},
x: {
grid: {
display: false,
},
ticks: {
autoSkip: false,
maxRotation: 0,
minRotation: 0,
font: {
size: 20,
}
}
},
}
}
You can use the grace option to add extra space to the y axes:
Chart.register(ChartDataLabels)
const options = {
type: 'bar',
data: {
labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
datasets: [{
label: '# of Votes',
data: [12, 20, 3, 5, 2, 3],
backgroundColor: 'pink'
}]
},
options: {
scales: {
y: {
grace: '10%'
}
},
plugins: {
legend: {
display: false
},
datalabels: {
anchor: 'end',
align: 'end'
}
}
}
}
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.8.0/chart.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/chartjs-plugin-datalabels/2.0.0/chartjs-plugin-datalabels.js"></script>
</body>

How to show different product name for every bar in chart js

I am using chart js for showing top 3 sold products in last week.
I want to show product name in tooltip for every bar which has obviously different products.
Here is my code :
function productChart() {
var data = {
labels: productHistoryDates,
datasets: [{
label: 'Product 1',
data: productHistoryProducts1,
backgroundColor: "#26B99A"
},
{
label: 'Product 2',
data: productHistoryProducts2,
backgroundColor: "#03586A",
},
{
label: 'Product 3',
data: productHistoryProducts3,
backgroundColor: "#03226A",
}]
};
var ctx = document.getElementById("productChart").getContext("2d");
var myBarChart = new Chart(ctx, {
type: 'bar',
data: data,
options: {
tooltips: {
enabled: true,
mode: 'single',
},
scales: {
yAxes: [{
gridLines: {
display: true
}
}],
xAxes: [{
gridLines: {
display: true
},
barPercentage: 0.8
}]
}
}
});
}
I am getting output like this.
But instead of product 1 label I want product name for that particular bar how can I achieve that ?
I solved it.
by passing an array to the label in data. And rest of the code is as below.
function productChart() {
var data = {
labels: productHistoryDates,
datasets: [{
label: productHistoryProducts1.name,
data: productHistoryProducts1.quantity,
backgroundColor: "#26B99A"
},
{
label: productHistoryProducts2.name,
data: productHistoryProducts2.quantity,
backgroundColor: "#03586A",
},
{
label: productHistoryProducts3.name,
data: productHistoryProducts3.quantity,
backgroundColor: "#03226A",
}]
};
var ctx = document.getElementById("productChart").getContext("2d");
var myBarChart = new Chart(ctx, {
type: 'bar',
data: data,
options: {
tooltips: {
enabled: true,
mode: 'single',
callbacks: {
label: function (tooltipItems, data) {
var tooltip = data.datasets[tooltipItems.datasetIndex].label[tooltipItems.index];
return tooltip;
}
}
},
scales: {
yAxes: [{
gridLines: {
display: true
}
}],
xAxes: [{
gridLines: {
display: true
},
ticks: { mirror: true },
barPercentage: 0.8
}]
}
}
});
}

How to make ticks evenly spaced with Chart.js

I have a horizontalBar chart with one column. I want to have ticks got from 0 to 70, evenly spaced and 10 point increments. I've tried several options, but can't seem to make it work out. Best I could do was this:
Here is the code I used to generate this chart:
<div style="width: 330px; height: 100px;">
<canvas id="chartBarChart1" style="margin-right: auto; margin-left: auto; display: block;" height="100"></canvas>
</div>
<script>
var ctx = document.getElementById('chartBarChart1').getContext('2d');
var myChart = new Chart(ctx, {
type: 'horizontalBar',
data: {
labels: ['CI'],
datasets: [
{
label: 'CI',
data: [45],
backgroundColor: 'Red'
}
]
},
options: {
scales: {
xAxes: [{
ticks: {
max: 70,
beginAtZero: true
}
}]
}, legend: { display: false },
responsive: false,
maintainAspectRatio: false
});
</script>
Is there a way?
Use "stepSize" to configure the ticks like this:
var ctx = document.getElementById('chartBarChart1').getContext('2d');
var myChart = new Chart(ctx, {
type: 'horizontalBar',
data: {
labels: ['CI'],
datasets: [{
label: 'CI',
data: [45],
backgroundColor: 'Red'
}]
},
options: {
scales: {
xAxes: [{
ticks: {
max: 70,
beginAtZero: true,
stepSize: 10
}
}]
},
},
});
https://jsfiddle.net/hdahle/zxdjqo82/

Chartjs change grid line color

First I don't know what's it called. But how do you change its color from gray to white? Or is it even possibe?
It is possible to either remove the grid lines or have them display in a different color.
In both options.scales.xAxes and options.scales.yAxes you can add
gridLines: {
display: false ,
color: "#FFFFFF"
},
(obviously you do not need to assign a colour if you are not disaplying them)
var chartColors = {
red: 'rgb(255, 99, 132)',
orange: 'rgb(255, 159, 64)',
yellow: 'rgb(255, 205, 86)',
green: 'rgb(75, 192, 192)',
blue: 'rgb(54, 162, 235)',
purple: 'rgb(153, 102, 255)',
grey: 'rgb(231,233,237)'
};
var randomScalingFactor = function() {
return (Math.random() > 0.5 ? 1.0 : -1.0) * Math.round(Math.random() * 100);
}
var MONTHS = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
var config = {
type: 'line',
data: {
labels: ["January", "February", "March", "April", "May", "June", "July"],
datasets: [{
label: "My First dataset",
backgroundColor: chartColors.red,
borderColor: chartColors.red,
data: [
randomScalingFactor(),
randomScalingFactor(),
randomScalingFactor(),
randomScalingFactor(),
randomScalingFactor(),
randomScalingFactor(),
randomScalingFactor()
],
fill: false,
}, {
label: "My Second dataset",
fill: false,
backgroundColor: chartColors.blue,
borderColor: chartColors.blue,
data: [
randomScalingFactor(),
randomScalingFactor(),
randomScalingFactor(),
randomScalingFactor(),
randomScalingFactor(),
randomScalingFactor(),
randomScalingFactor()
],
}]
},
options: {
responsive: true,
title: {
display: true,
text: 'Chart.js Line Chart'
},
tooltips: {
mode: 'label',
},
hover: {
mode: 'nearest',
intersect: true
},
scales: {
xAxes: [{
display: true,
gridLines: {
display: false
},
scaleLabel: {
display: true,
labelString: 'Month'
}
}],
yAxes: [{
display: true,
gridLines: {
display: false
},
scaleLabel: {
display: true,
labelString: 'Value'
}
}]
}
}
};
var ctx = document.getElementById("canvas").getContext("2d");
window.myLine = new Chart(ctx, config);
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.2.1/Chart.js"></script>
<div style="width:100%;">
<canvas id="canvas"></canvas>
</div>
Since v3 the scales have been changed so if you want your gridlines to have a different color you will need to configure it in options.scales[scaleID].grid.color:
var 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: {
grid: {
color: 'white'
}
},
x: {
grid: {
color: 'red'
}
}
}
}
}
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.6.0/chart.js"></script>
</body>
Try this:
options: {
scales: {
x: {
display: true,
grid: {
display: false
},
},
y: {
display: true,
grid: {
display: false
},
}
}
}