ChartJS using multiple Y axes - javascript

I've created a line chart with two datasets, each one its own Y scale&axis using Chart.js.my datasets and options'code is like below.
datasets: [{ fill:false,
label: 'Heat',
yAxisID: "y-axis-1",
data: warm,
},
{ fill:false,
yAxisID: "y-axis-0",
label:'Mass',
data:volume,
]
options:{
scales: {
yAxes: [{ position: "left",
"id": "y-axis-0",
display: true,
ticks: { steps: 10,
stepValue: 5,
callback:(label,index,labels)=>{ return label + "%"; } }
},
{ position: "right",
"id": "y-axis-1",
display: true,
ticks: { steps: 10,
stepValue: 5,
callback:(label,index,labels)=>{ return label + " c"; } } }] }
}
it is looking like the folowing image at the moment.
when I toggle Mass label,the YAxes on the left is still appearing.I want to hide it if I toggle the labels.can you please guide me to solve this problem?

You could achieve this using the following chartjs plugin ...
Chart.plugins.register({
beforeDraw: function(c) {
var canvas_id = c.chart.canvas.id;
if (canvas_id === 'myChart') {
if (c.data.datasets[0]._meta[0].hidden) {
c.options.scales.yAxes[1].display = false;
} else c.options.scales.yAxes[1].display = true;
if (c.data.datasets[1]._meta[0].hidden) {
c.options.scales.yAxes[0].display = false;
} else c.options.scales.yAxes[0].display = true;
}
}
});
ᴅᴇᴍᴏ
Chart.plugins.register({
beforeDraw: function(c) {
var canvas_id = c.chart.canvas.id;
if (canvas_id === 'myChart') {
if (c.data.datasets[0]._meta[0].hidden) {
c.options.scales.yAxes[1].display = false;
} else c.options.scales.yAxes[1].display = true;
if (c.data.datasets[1]._meta[0].hidden) {
c.options.scales.yAxes[0].display = false;
} else c.options.scales.yAxes[0].display = true;
}
}
});
var canvas = document.getElementById('myChart');
var warm = [0, 0, 0, 0, 25, 25, 25, 25, 25, 25];
var volume = [98, 12, 0, 7, 7, 7, 7, 78, 62, 62];
var data = {
labels: ["23.05.2017 15:34:48", "23.05.2017 15:35:02", "23.05.2017 15:35:14", "23.05.2017 15:35:28", "23.05.2017 15:59:35", "23.05.2017 16:00:11", "23.05.2017 16:07:22", "23.05.2017 16:38:04", "23.05.2017 16:38:43", "23.05.2017 16:57:48"],
datasets: [{
fill: false,
label: 'Heat',
pointHoverRadius: 5,
pointHitRadius: 5,
lineTension: 0,
yAxisID: "y-axis-1",
data: warm,
backgroundColor: "rgba(255,153,0,0.4)"
}, {
fill: false,
pointHoverRadius: 5,
pointHitRadius: 5,
lineTension: 0,
yAxisID: "y-axis-0",
label: 'Mass',
data: volume,
backgroundColor: "rgba(153,255,51,0.4)"
}]
};
var option = {
maintainAspectRatio: false,
responsive: true,
bezierCurveTension: 0,
scales: {
xAxes: [{
display: true,
ticks: {
maxTicksLimit: 3,
fontSize: 10
}
}],
yAxes: [{
position: "left",
"id": "y-axis-0",
display: true,
ticks: {
steps: 10,
stepValue: 5,
//max: 100,
callback: (label, index, labels) => {
return label + "%";
}
}
}, {
position: "right",
"id": "y-axis-1",
display: true,
ticks: {
steps: 10,
stepValue: 5,
//max: 100,
callback: (label, index, labels) => {
return label + " c";
}
}
}]
}
};
var myLineChart = Chart.Line(canvas, {
data: data,
options: option
});
function adddata() {
myLineChart.data.datasets[0].data[7] = 50;
myLineChart.data.labels[7] = "test add";
myLineChart.update();
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.5.0/Chart.min.js"></script>
<canvas id="myChart" width="400" height="250"></canvas>
ChartJS v2.5.0

Related

Chart js two same line charts on different Y

I have 3 charts on my canvas 1 stacked bar chart and 2 line charts.
Line charts have same Y values but located at different heights.
I have 3.6 version Chart js
dataset
is data for my stacked bars
Line and linePrediction are my graphs and have same values
const line = {
label: 'Signed',
data: [
{x: 1, y: 12226000},
{x: 2, y: 12716000},
{x: 3, y: 14176000},
...
],
backgroundColor: 'rgba(55, 128, 189, 1)',
borderColor: 'rgba(55, 128, 189, 1)',
tension: 0.4,
type: 'line',
order: 1,
}
const data = {
labels: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12],
datasets: [ ...dataset, line, linePrediction]
};
const config = {
type: 'bar',
data,
options: {
responsive: true,
plugins: {
tooltip: {
enabled: true,
callbacks: {
title: function(tooltipItems, data) {
return tooltipItems[0].formattedValue || '';
},
label: function(context) {
return ' ' + context.dataset.label || '';
}
}
},
legend: {
display: true,
position: 'bottom',
labels: {
padding: 10
}
}
},
scales: {
x: {
stacked: true
},
y: {
beginAtZero: true,
stacked: true
},
},
}
};
const chart = new Chart(document.getElementById('chart'), config);

How can I change background color of a specific area in my chart's grid using Chart.js and Annotation?

I'm having some trouble trying to change the backgroundColor of a specific chart area between two yAxis ticks.This is what I have so far:
And this is what I wanted:
I've seen some similar posts about that and people recommend using Annotation to do this. I tried using it on my chart and it didn't work. This is my first time building a chart with chart.js so I'm still learning. Here's my code:
var profileChart = new Chart(ctx1, {
type: "line",
data: {
labels: ["", "D", "I", "S", "C", ""],
datasets:[{
data: [],
borderWidth: 1,
pointBackgroundColor: "black",
backgroundColor: "black",
borderColor: "black",
fill: false,
lineTension: 0,
yAxisID: 'first-y-axis'
},
{
yAxisID: 'third-y-axis'
}],
},
options: {
title: {
display: true,
text: 'Gráfico do Perfil DISC',
fontSize: 20,
},
scales: {
yAxes: [{
id: 'first-y-axis',
type: 'linear',
gridLines: {
drawOnChartArea: false
},
scaleLabel: {
display: true,
padding: '15px',
labelString: 'Intensity'
},
ticks: {
max: 28,
min: 1,
stepSize: 1
}
},
{
id: 'second-y-axis',
type: 'linear',
position: 'left',
gridLines: {
drawOnChartArea: true
},
ticks: {
display: false,
min: 1,
max: 8,
stepSize: 1
}
},
{
id: 'third-y-axis',
position: 'right',
type: 'linear',
gridLines: {
drawOnChartArea: false
},
scaleLabel: {
display: true,
padding: '10px',
labelString: 'Segment'
},
ticks: {
max: 7.5,
min: 0.5,
stepSize: 1
},
afterTickToLabelConversion: function(scaleInstance) {
scaleInstance.ticks[0] = null;
scaleInstance.ticks[scaleInstance.ticks.length - 1] = null;
scaleInstance.ticksAsNumbers[0] = null;
scaleInstance.ticksAsNumbers[scaleInstance.ticksAsNumbers.length - 1] = null;
},
}]
},
legend: {
display: false
},
tooltips: {
callbacks: {
label: function(tooltipItem) {
return tooltipItem.yLabel;
}
}
}
},
annotation: {
drawTime: "afterDraw",
annotations: [{
id: 'box1',
type: 'box',
yScaleID: 'second-y-axis',
yMin: 12.5,
yMax: 16.5,
backgroundColor: 'grey',
}]
}
});
You can draw the rectangle directly on the canvas using the Plugin Core API. The API offers a range of hooks that may be used for performing custom code.
In your amended code below, I use the beforeDraw hook to draw the rectangle through CanvasRenderingContext2D.fillRect().
var profileChart = new Chart('canvas', {
type: "line",
plugins: [{
beforeDraw: chart => {
var ctx = chart.chart.ctx;
var xAxis = chart.scales['x-axis-0'];
var yAxis = chart.scales['first-y-axis'];
ctx.save();
ctx.fillStyle = 'lightgray';
ctx.beginPath();
var yTop = yAxis.getPixelForValue(16.5);
var yBottom = yAxis.getPixelForValue(12.5);
ctx.fillRect(xAxis.left, yTop, xAxis.right - xAxis.left, yBottom - yTop);
ctx.stroke();
ctx.restore();
}
}],
data: {
labels: ["", "D", "I", "S", "C", ""],
datasets: [{
data: [,25.5, 8, 7.5, 11],
borderWidth: 1,
pointBackgroundColor: "black",
backgroundColor: "black",
borderColor: "black",
fill: false,
lineTension: 0,
yAxisID: 'first-y-axis'
},
{
yAxisID: 'third-y-axis'
}
],
},
options: {
title: {
display: true,
text: 'Gráfico do Perfil DISC',
fontSize: 20,
},
scales: {
yAxes: [{
id: 'first-y-axis',
type: 'linear',
gridLines: {
drawOnChartArea: false
},
scaleLabel: {
display: true,
padding: '15px',
labelString: 'Intensity'
},
ticks: {
max: 28,
min: 1,
stepSize: 1
}
},
{
id: 'second-y-axis',
type: 'linear',
position: 'left',
gridLines: {
drawOnChartArea: true
},
ticks: {
display: false,
min: 1,
max: 8,
stepSize: 1
}
},
{
id: 'third-y-axis',
position: 'right',
type: 'linear',
gridLines: {
drawOnChartArea: false
},
scaleLabel: {
display: true,
padding: '10px',
labelString: 'Segment'
},
ticks: {
max: 7.5,
min: 0.5,
stepSize: 1
},
afterTickToLabelConversion: function(scaleInstance) {
scaleInstance.ticks[0] = null;
scaleInstance.ticks[scaleInstance.ticks.length - 1] = null;
scaleInstance.ticksAsNumbers[0] = null;
scaleInstance.ticksAsNumbers[scaleInstance.ticksAsNumbers.length - 1] = null;
},
}
]
},
legend: {
display: false
},
tooltips: {
callbacks: {
label: function(tooltipItem) {
return tooltipItem.yLabel;
}
}
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.bundle.min.js"></script>
<canvas id="canvas" height="200">

How to display value after the bar using chart.js

My chart.js
var ctx_1 = document.getElementById('https_http').getContext('2d');
var myChart_1 = new Chart(ctx_1, {
type: 'horizontalBar',
data: {
labels: ['HTTPS Pages','HTTP Pages'],
datasets: [{
data: [ {{ $array_https_http[0] }}, {{ $array_https_http[1] }}],
backgroundColor: [
'rgb(81, 170, 120)',
'rgb(198, 222, 208)'
]
}]
},
options: {
showAllTooltips: true,
tooltips: {
enabled: true,
displayColors: false,
yPadding: 20,
xPadding: 30,
caretSize: 10,
backgroundColor: 'rgba(240, 240, 240, 1)',
bodyFontSize: 16,
bodyFontColor: 'rgb(50, 50, 50)',
borderColor: 'rgba(0,0,0,1)',
borderWidth: 1,
cornerRadius: 0,
yAlign: 'bottom',
xAlign: 'center',
position: 'custom',
custom: function(tooltip) {
if (!tooltip) return;
// disable displaying the color box;
tooltip.displayColors = false;
},
callbacks: {
// use label callback to return the desired label
label: function(tooltipItem, data) {
return tooltipItem.yLabel + " : " + tooltipItem.xLabel ;
},
// remove title
title: function(tooltipItem, data) {
return;
}
}
},
responsive: false,
legend: { display: false },
scales: {
yAxes: [{
ticks: {
beginAtZero:true,
},
gridLines: {
display: false
},
}],
xAxes: [{
ticks: {
stepSize:100
}
}],
}
}
});
My tooltips code
Chart.Tooltip.positioners.custom = function(elements, position) {
if (!elements.length)
return false;
var em = elements[0]._model;
return {
x: em.x-((em.x-em.base)/2),
y: em.y+em.height/4
}
}
My output
My expected output
Is there anyone can help me how to put those value after the bar like the second picture. I just want to display the value to know even its zero. My custom tooltips was to show a different hover rather than default. All your help are appreciated and thank you in advance.
You can use the chartjs.datalabel plugin for achieving the need. I have created a fiddle for you -> http://jsfiddle.net/Labkrpf4/
Hope it helps!
var ctx_1 = document.getElementById('https_http').getContext('2d');
var myChart_1 = new Chart(ctx_1, {
type: 'horizontalBar',
data: {
labels: ['HTTPS Pages', 'HTTP Pages'],
datasets: [{
data: [0, 430],
backgroundColor: [
'rgb(81, 170, 120)',
'rgb(198, 222, 208)'
]
}]
},
options: {
showAllTooltips: true,
tooltips: {
enabled: true,
displayColors: false,
yPadding: 20,
xPadding: 30,
caretSize: 10,
backgroundColor: 'rgba(240, 240, 240, 1)',
bodyFontSize: 16,
bodyFontColor: 'rgb(50, 50, 50)',
borderColor: 'rgba(0,0,0,1)',
borderWidth: 1,
cornerRadius: 0,
yAlign: 'bottom',
xAlign: 'center',
position: 'custom',
custom: function(tooltip) {
if (!tooltip) return;
// disable displaying the color box;
tooltip.displayColors = false;
},
callbacks: {
// use label callback to return the desired label
label: function(tooltipItem, data) {
return tooltipItem.yLabel + " : " + tooltipItem.xLabel;
},
// remove title
title: function(tooltipItem, data) {
return;
}
}
},
responsive: false,
legend: {
display: false
},
scales: {
yAxes: [{
ticks: {
beginAtZero: true,
},
gridLines: {
display: false
},
}],
xAxes: [{
ticks: {
stepSize: 100
}
}],
},
plugins: {
datalabels: {
align: 'end',
anchor: 'end',
backgroundColor: function(context) {
return context.dataset.backgroundColor;
},
borderRadius: 4,
color: 'white',
formatter: Math.round
}
}
}
});

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>

Hide Series on Click with jQuery Flot

I have a Flot graph which I am trying to make it so that when you click a particular legend item it makes that data disappear from the chart.
I am having limited success in getting this to work. I've gotten as far as being able to click a legend item and a series line is removed, but not the points, and it appears to be the wrong line data as well.
Any help on this would be really appreciated :)
var Graphs = function () {
return {
//main function
initCharts: function () {
if (!jQuery.plot) {
return;
}
function showChartTooltip(x, y, xValue, yValue) {
$('<div id="tooltip" class="chart-tooltip">' + yValue + '<\/div>').css({
position: 'absolute',
display: 'none',
top: y - 40,
left: x - 40,
border: '0px solid #ccc',
padding: '2px 6px',
'background-color': '#fff'
}).appendTo("body").fadeIn(200);
}
if ($('#site_revenue').size() != 0) {
//site revenue
var previousPoint2 = null;
var plot_statistics = null;
var data = [];
togglePlot = function(seriesIdx)
{
var previousPoint2 = plot_statistics.getData();
previousPoint2[seriesIdx].lines.show = !previousPoint2[seriesIdx].lines.show;
plot_statistics.setData(previousPoint2);
plot_statistics.draw();
}
$('#site_revenue_loading').hide();
$('#site_revenue_content').show();
var data = [{
label: "Gross Revenue",
color: ['#44b5b1'],
points: {
fillColor: "#44b5b1"
},
data: [
['Sep', 264.41],
['Aug', 6653.98],
['Jul', 921.35],
['Jun', 937.00],
['May', 1839.25],
['Apr', 1561.96],
['Mar', 2289.62],
['Feb', 2661.91],
['Jan', 6021.44],
['Dec', 4129.21],
['Nov', 0.00],
['Oct', 2865.28],
],
idx:1
},{
label: "Tax",
color: ['#8fc2ed'],
points: {
fillColor: "#8fc2ed"
},
data: [
['Sep', 0.00],
['Aug', 2865.28],
['Jul', 2661.91],
['Jun', 6653.98],
['May', 6021.44],
['Apr', 0.00],
['Mar', 2289.62],
['Feb', 1561.96],
['Jan', 921.35],
['Dec', 937.00],
['Nov', 1839.25],
['Oct', 4129.21]
],
idx: 2
}];
var plot_statistics = $.plot($("#site_revenue"), data, {
series: {
lines: {
show: true,
fill: 0.2,
lineWidth: 0,
fill: false,
lineWidth: 3
},
shadowSize: 1,
points: {
show: true,
fill: true,
radius: 4,
lineWidth: 2
},
},
xaxis: {
tickLength: 0,
tickDecimals: 0,
mode: "categories",
min: 0,
font: {
lineHeight: 18,
style: "normal",
variant: "small-caps",
color: "#6F7B8A"
}
},
yaxis: {
ticks: 5,
tickDecimals: 0,
tickColor: "#eee",
font: {
lineHeight: 14,
style: "normal",
variant: "small-caps",
color: "#6F7B8A"
}
},
grid: {
hoverable: true,
clickable: true,
tickColor: "#eee",
borderColor: "#eee",
borderWidth: 1
},
legend: {
show: true,
placement: 'outsideGrid',
container: $('#site_revenue_legend'),
labelFormatter: function(label, series){
return ''+label+'';
}
}
});
$("#site_revenue").bind("plothover", function (event, pos, item) {
$("#x").text(pos.x.toFixed(2));
$("#y").text(pos.y.toFixed(2));
if (item) {
if (previousPoint2 != item.dataIndex) {
previousPoint2 = item.dataIndex;
$("#tooltip").remove();
var x = item.datapoint[0].toFixed(2),
y = item.datapoint[1].toFixed(2);
showChartTooltip(item.pageX, item.pageY, item.datapoint[0], '$' + item.datapoint[1]);
}
}
});
$('#site_revenue').bind("mouseleave", function () {
$("#tooltip").remove();
});
}
}
};
}();
jQuery(document).ready(function() {
Graphs.initCharts(); // init index page's custom scripts
});
JSFiddle: http://jsfiddle.net/fxc4vyg3/
You must be tired, you just have an off-by-one error, and you only called the update for the lines, not the points.
togglePlot = function(seriesIdx)
{
var previousPoint2 = plot_statistics.getData();
seriesIdx--; // ***HERE***
previousPoint2[seriesIdx].points.show = // ***AND HERE***
previousPoint2[seriesIdx].lines.show = !previousPoint2[seriesIdx].lines.show;
plot_statistics.setData(previousPoint2);
plot_statistics.draw();
}
Here's the fixed fiddle: http://jsfiddle.net/it_turns_out/fxc4vyg3/3/

Categories

Resources