Multi-axis line chart with Chart.js - javascript

The following code I tried to display two y-axis on the line chart and I added yAxisID in both the data source. However, it is nothing to shown. May I know what's wrong with my code? Thank you.
function BuildChart(labels, valuesa, valuesb, chartTitle) {
var ctx = document.getElementById("myChart").getContext('2d');
var myChart = new Chart(ctx, {
type: 'line',
data: {
labels: labels,
datasets: [{
label: 'Temperature',
fill: false,
data: valuesa,
yAxisID: 'y1',
backgroundColor: 'red',
borderColor: 'red',
}, {
label: 'Relative Humidity',
fill: false,
data: valuesb,
yAxisID: 'y2',
backgroundColor: 'blue',
borderColor: 'blue',
}]
},
options: {
responsive: true,
maintainAspectRatio: false,
scales: {
y1: {
type: 'linear',
display: true,
position: 'left',
},
y2: {
type: 'linear',
display: true,
position: 'right',
},
xAxes: [{
ticks: {
beginAtZero: true,
scaleLabel: {
display: false,
labelString: ''
}
}
}],
yAxes: [{
scaleLabel: {
display: false,
labelString: '',
}
}]
}
}
})
return myChart;
};
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var json = JSON.parse(this.response);
// Map json labels back to values array
var labels = json.feed.entry.map(function(e) {
return e.gsx$tag.$t;
});
// Map json values back to values array
var valuesa = json.feed.entry.map(function(e) {
return e.gsx$dailytemperature.$t
});
// Map json values back to values array
var valuesb = json.feed.entry.map(function(e) {
return e.gsx$dailyrh.$t
});
BuildChart(labels, valuesa, valuesb, "Temperature", "Relative Humidity");
}
};
xhttp.open("GET", "https://spreadsheets.google.com/", false);
xhttp.send();

Within the chart options of your code, there are too many definitions of yAxes (before and after xAxis).
To make it work, the entire chart options can basically be reduced to what you see below.
options: {
responsive: true,
maintainAspectRatio: false,
scales: {
yAxes: [{
type: 'linear',
position: 'left',
id: 'y1',
},
{
type: 'linear',
position: 'right',
gridLines: {
drawOnChartArea: false
},
id: 'y2',
}
]
}
}
For further information, please consult Create Multiple Axis from the
Chart.js documentation.

Related

ChartJS How to set color to just one bar

I have this barChart and I'm with difficult to set a color by script to just one bar of the index.
Bellow is my chartbar code:
var ctx = document.getElementById("myBarChart");
var myBarChart = new Chart(ctx, {
type: 'bar',
data: {
labels: [],
datasets: [{
label: "Valor",
backgroundColor: "rgba(2,117,216,1)",
borderColor: "rgba(2,117,216,1)",
data: [],
}],
},
options: {
plugins: {
datalabels: {
anchor: 'end',
align: 'top',
formatter: function (value, context) {
if (value != 0) {
return new Date(value * 1000).toISOString().substr(11, 8);
} else {
value = " "
return value;
}
},
font: {
weight: 'bold'
}
}
},
responsive: true,
tooltips: {
/* intersect: false, */
callbacks: {
title: function (tooltipItem, data) {
return data['labels'][tooltipItem[0]['index']];
},
label: function (tooltipItem, data) {
return new Date(parseInt(data['datasets'][0]['data'][tooltipItem[
'index']]) * 1000).toISOString().substr(11,
8);
},
},
},
scales: {
xAxes: [{
time: {
unit: 'month'
},
gridLines: {
display: false
},
}],
yAxes: [{
ticks: {
min: 0,
suggestedMax: 36000,
stepSize: 3600,
beginAtZero: true,
},
}],
},
}
});
I have tried this:
myBarChart.data.datasets[0].backgroundColor[0]
But it doesnt work.
If someone know how to do this in the last version of the chartjs, please help me.
You can provide an array to the backgroundColor property. In this array you can fill it with the default color except for the index where you want the bar to be a different collor

Why is Chart js first bar too small or not showing at all?

Hi I am trying to show some bar charts using charts js, my problem is that the first column isn't showing properly.
This is my code:
var options = {
scales: {
yAxes: [{
display: true
}],
xAxes: [{
display: false
}]
},
legend: {
display: false
}
};
var dataD = {
labels: ["2020-09-01 18:05:33", "2020-10-13 11:08:28"],
datasets: [{
label: "PA",
data: [132, 139],
backgroundColor: "#4cb6cb"
}]
};
var methods = new Chart($("#line192"), {
type: "bar",
data: dataD,
animation: true,
options: options
});
And this is the jsfiddle example
Any thoughts? thank you!
By default, the axes start at your minimum value. Set ticks.beginAtZero to true on your Y-axis to display and your first bar will be visible:
var options = {
scales: {
yAxes: [{
display: true,
ticks: {
beginAtZero: true
}
}],
xAxes: [{
display: false
}]
},
legend: {
display: false
}
};
var dataD = {
labels: ["2020-09-01 18:05:33", "2020-10-13 11:08:28"],
datasets: [{
label: "PA",
data: [132, 139],
backgroundColor: "#4cb6cb"
}]
};
var methods = new Chart($("#line192"), {
type: "bar",
data: dataD,
animation: true,
options: options
});
Here is the fixed jsfiddle

How to edit my custom tooltips in my line chart using chart.js?

This is my code
var ctx = document.getElementById("myChart").getContext('2d');
var myChart = new Chart(ctx, {
type: 'line',
data: {
labels: [{{ $nDate }}],
datasets: [{
label: 'All Users',
data: [ {{ $nUser }} ],
backgroundColor: ['rgba(54, 162, 235, 0.2)'],
borderColor: ['rgba(54, 162, 235, 1)'],
borderWidth: 3,
lineTension: 0,
labelFontSize : '16',
}]
},
options: {
tooltips: {
mode: 'index',
intersect: false,
position: 'nearest'
},
responsive: false,
legend: { display: false },
scales: {
yAxes: [{
ticks: {
beginAtZero:true,
type: 'category',
labelOffset: 10,
stepSize:250,
callback: function(value, index) {
if (value !== 0) return value;
}
},
gridLines:{
drawBorder:false
}
}],
xAxes: [{
gridLines: {
display: false,
},
}],
},
plugins:{
datalabels:{
display:false
}
}
}
});
My output
My Expected Output
How can I able to put/edit custom tooltip in my line chart? I just want to get the exact tooltips in the second picture but I don't have any idea how to fix it? Another thing is my $nDateI only want to show four dates like 8,15,22,29 But when I tried to create a new array label with value of this [" ", " "]; my chart crashed.
You can use custom callback function to render with your own choice html tags and colors, Follow the official documentation link for further guidance.
http://www.chartjs.org/docs/latest/configuration/tooltip.html#external-custom-tooltips
options: {
tooltips: {
enabled: false,
custom: function(tooltipModel) {}
}
}

How to show border around tooltip chart.js and show y-axis integer value along with text in tooltip title?

i am drawing a line chart using chart.js and showed a tooltip on graph.But i am not able to draw a border around tooltip and in title i want to show text and current y-axis value as title(eg.total count:2 but instead of 2 it showing undefined.Now i removed code from title callback). I am trying for many days but still no luck. Please help me. Here is my code
var ctx = document.getElementById("myChart").getContext('2d');
var myChart = new Chart(ctx, {
type: 'line',
data: {
labels:["a","b","c"],
datasets: [{
label: 'Total count',
lineTension: 0,
data: [2,4,6],
fill: false,
borderColor: 'rgba(39,50,139,1)',
pointBackgroundColor:'rgba(176,179,214,1)',
pointBorderColor:'rgba(39,50,139,1)',
pointRadius:5,
pointHoverBackgroundColor:'rgba(39,50,139,1)',
borderWidth:2
}]
},
options: {
responsive: true,
maintainAspectRatio: false,
legend:{
display:false
},
chartArea: {
backgroundColor: '#fff'
},
scales: {
yAxes: [{
ticks: {
beginAtZero:true,
maxTicksLimit:3
}
}],
xAxes: [{
gridLines: {
display: false,
color: "black"
},
ticks: {
max:12,
maxTicksLimit:12
}
}]
},
tooltips: {
callbacks: {
title:function(tooltipItem, data) {
},
afterLabel: function(tooltipItem, data) {
return userNamesResult[tooltipItem.index];
}
},
titleSpacing:0,
titleMarginBottom:0,
titleFontColor:'#000',
backgroundColor: '#f2f3f4',
bodyFontColor: '#000',
//bodyFontStyle:'bold',
bodyFontSize: 14,
displayColors: false,
borderColor:'#ff0000',
borderWidth:5,
}
}
});

Chart.js stacked bar chart in opposite direction

I am trying to achieve something like this using chart.js. I wanted to show data of male/female according to each age group:
Here is my chart options:
var options = {
layout: {
padding: {
top: 5,
}
},
scales:
{
yAxes: [{
display: true,
barPercentage: 0.4,
ticks: {
fontSize: 12
},
stacked: true,
}],
xAxes: [{
stacked: true,
}]
},
responsive: true,
maintainAspectRatio: false,
legend: {
display: false,
},
animation: {
animateScale: true,
animateRotate: true
},
};
var opt = {
type: "horizontalBar",
data: {
labels: ageGroup,
datasets: [{
label: 'Male',
data: maleData,
backgroundColor: '#2196F3',
hoverBackgroundColor: '#2196F3'
},
{
label: 'Female',
data: femaleData,
backgroundColor: '#E91E63',
hoverBackgroundColor: '#E91E63'
}]
},
options: options
};
I changed the positive in femaleData array into a negative number to achieve the result above:
for (var i = 0; i < femaleData.length; i++) {
femaleData[i] = -Math.abs(femaleData[i]);
}
However, the y-axis at 0 is not centralized as it pushed to the right hand side since left hand side got more data. I not even sure if this is the correct way to set the chart in opposite direction. How can I do this correctly?
as per the requirements mentioned in OP­'s comment section
ꜱʜᴏᴡ ᴘᴏꜱɪᴛɪᴠᴇ ᴠᴀʟᴜᴇꜱ ᴏɴ x-ᴀxɪꜱ
use the following callback function for x-axis ticks :
callback: function(t, i) {
return t < 0 ? Math.abs(t) : t;
}
ꜱʜᴏᴡ ᴘᴏꜱɪᴛɪᴠᴇ ᴠᴀʟᴜᴇ ᴏɴ ᴛᴏᴏʟᴛɪᴘ
use the following callback function for tooltips :
callbacks: {
label: function(t, d) {
var datasetLabel = d.datasets[t.datasetIndex].label;
var xLabel = Math.abs(t.xLabel);
return datasetLabel + ': ' + xLabel;
}
}
ᴡᴏʀᴋɪɴɢ ᴇxᴀᴍᴘʟᴇ ⧩
var ageGroup = ['0-10', '11-20', '21-30', '31-40', '41-50', '51-60', '61-70', '71-80', '80+'];
var maleData = [30, 0, 0, 0, 10, 0, 0, 0, 0];
var femaleData = [0, 0, 0, -20, -50, -20, 0, 0, 0];
var options = {
layout: {
padding: {
top: 5,
}
},
scales: {
yAxes: [{
display: true,
barPercentage: 0.4,
ticks: {
fontSize: 12
},
stacked: true,
}],
xAxes: [{
stacked: true,
ticks: {
callback: function(t, i) {
return t < 0 ? Math.abs(t) : t;
}
}
}]
},
tooltips: {
callbacks: {
label: function(t, d) {
var datasetLabel = d.datasets[t.datasetIndex].label;
var xLabel = Math.abs(t.xLabel);
return datasetLabel + ': ' + xLabel;
}
}
},
responsive: true,
//maintainAspectRatio: false,
legend: {
display: false,
},
animation: {
animateScale: true,
animateRotate: true
},
};
var opt = {
type: "horizontalBar",
data: {
labels: ageGroup,
datasets: [{
label: 'Male',
data: maleData,
backgroundColor: '#2196F3',
hoverBackgroundColor: '#2196F3'
}, {
label: 'Female',
data: femaleData,
backgroundColor: '#E91E63',
hoverBackgroundColor: '#E91E63'
}]
},
options: options
};
new Chart(ctx, opt);
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.min.js"></script>
<canvas id="ctx"></canvas>

Categories

Resources