Chart.js - Multiple bar Charts - Only Show Last Chart - django

Chart.js - Multiple Bar Charts - Only Show Last Chart.Basically data comes from django and is rendered in the template.Data is proper but only one of 2 charts are being rendered.
I also tried changing ctx but it did not worked
HTML Code
<div class="container">
<div id="container" class="col-6">
<canvas id="indiacanvas"></canvas>
</div>
<div id="container" class="col-6">
<canvas id="usacanvas"></canvas>
</div>
</div>
Basically data comes from django and is rendered in the template.Data is proper but only one of 2 charts are being rendered.
I also tried changing ctx but it did not worked
Script.js
//BAR CHART USD
var barChartData = {
labels: [{% for item in listyear1 %}'{{item| date:"Y"}}', {% endfor %}],
datasets: [
{
label: "Total amount",
backgroundColor: "lightblue",
borderColor: "blue",
borderWidth: 1,
data: [{% for inr in USATOTAL %}'{{inr}}', {% endfor %}],
},
{
label: "Amount Recieved",
backgroundColor: "lightgreen",
borderColor: "green",
borderWidth: 1,
data: [{% for rinr in RUSDS %} '{{rinr}}', {% endfor %}],
},
{
label: "Amount Left",
backgroundColor: "pink",
borderColor: "red",
borderWidth: 1,
data: [{% for linr in LUSDS %} '{{linr}}', {% endfor %}],
},
],
};
var chartOptions = {
responsive: true,
legend: {
position: "top",
},
title: {
display: true,
text: "YearWise Summary USD",
},
scales: {
yAxes: [
{
ticks: {
beginAtZero: true,
},
},
],
},
};
window.onload = function () {
var ctx = document.getElementById("usacanvas").getContext("2d");
window.myBar = new Chart(ctx, {
type: "bar",
data: barChartData,
options: chartOptions,
});
};
// Bar Chart India
var barChartData = {
labels: [{% for item in listyear %}'{{item| date:"Y"}}', {% endfor %}],
datasets: [
{
label: "Total amount",
backgroundColor: "lightblue",
borderColor: "blue",
borderWidth: 1,
data: [{% for inr in INDIATOTAL %}'{{inr}}', {% endfor %}],
},
{
label: "Amount Recieved",
backgroundColor: "lightgreen",
borderColor: "green",
borderWidth: 1,
data: [{% for rinr in RINR %} '{{rinr}}', {% endfor %}],
},
{
label: "Amount Left",
backgroundColor: "pink",
borderColor: "red",
borderWidth: 1,
data: [{% for linr in LINR %} '{{linr}}', {% endfor %}],
},
],
};
var chartOptions = {
responsive: true,
legend: {
position: "top",
},
title: {
display: true,
text: "YearWise Summary INR",
},
scales: {
yAxes: [
{
ticks: {
beginAtZero: true,
},
},
],
},
};
window.onload = function () {
var ctx = document.getElementById("indiacanvas").getContext("2d");
window.myBar = new Chart(ctx, {
type: "bar",
data: barChartData,
options: chartOptions,
});
};

Due to JavaScripts async nature, ctx might get reassigned. Try using ctx2 as variable name for the second chart.

Related

How can I give values like below screenshot using Line Chart

how to show those straight Lines.
I added x: { offset: true }, but the next point not looks straight..
My Code
const labels = ["A", "B", "C", "D"];
const data = {
labels: labels,
borderColor: "",
datasets: [
{
label: "Title",
data: [0, 50, 50, -10],
fill: false,
borderWidth: 5,
borderColor: "yellow",
tension: 0.1,
},
],
};
You could use a scatter as following:
const myChart = new Chart(ctx, {
type: 'scatter',
data: {
datasets: [{
data: [{x:0, y:0}, {x:0, y:10}, {x:2, y:10}, {x:2, y:0}],
}]
},
options: {
showLine: true
}
});
const ctx = document.getElementById('myChart').getContext('2d');
const myChart = new Chart(ctx, {
type: 'scatter',
data: {
datasets: [{
data: [{x:0, y:0}, {x:0, y:10}, {x:2, y:10}, {x:2, y:0}],
}]
},
options: {
showLine: true,
scales: {
y: {
max: 20
}
}
}
});
.myChartDiv {
max-width: 600px;
max-height: 400px;
}
<script src="https://cdn.jsdelivr.net/npm/chart.js#4.1.1/dist/chart.umd.min.js"></script>
<html>
<body>
<div class="myChartDiv">
<canvas id="myChart" width="600" height="400"/>
</div>
</body>
</html>

charts js have a bar spanning negative/positive on y-axis

Is there a way in chartjs to have a bar span across the zero line? As an example,
lets say I have a bar with
data:[x:1, y:100]
How do I tell it to span the y-axis from -100 to 100 (instead of from 0 to 100)?
I have sort of a playground here where I can do either negative or positive per bar, but not both for one bar.
https://jsbin.com/dufonoceja/1/edit?js,output
This can be done since Chart.js v2.9.0, which now supports floating bars. Individual bars can now be specified with the syntax [min, max].
<html>
<head>
<title>Floating Bars</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script>
<style>
canvas {
-moz-user-select: none;
-webkit-user-select: none;
-ms-user-select: none;
}
</style>
</head>
<body>
<div>
<canvas id="canvas" height="120"></canvas>
</div>
<script>
var chartData = {
labels: [1,2,3,4,5,6],
datasets: [{
type: 'bar',
label: 'Red Bar',
borderColor: 'black',
borderWidth: 1,
backgroundColor: 'rgba(128,0,0,0.2)',
data: [[0, 100], [-100, 100], [-30, 40], 0, 0, 0],
}, {
type: 'bar',
label: 'Green Bar',
backgroundColor: 'rgba(0,128,0,0.2)',
borderColor: 'black',
borderWidth: 1,
data: [0, 0, 0, 0, [-50, 70], 100],
}
]
};
window.onload = function() {
var ctx = document.getElementById('canvas').getContext('2d');
window.myBar = new Chart(ctx, {
type: 'bar',
data: chartData,
options: {
scaleBeginAtZero: false,
responsive: true,
spanGaps: true,
tooltips: {
mode: 'index',
intersect: true
},
scales: {
xAxes: [{
gridLines: {
display: false
},
}],
yAxes: [{
type: 'linear',
ticks: {
beginAtZero: false,
min:-100,
max:100,
stepSize:30
}
}],
}
}
});
};
</script>
</body>
</html>

Show Dates in x-axis when using chart.js

I am using chart.js library. I am creating a graph and want to show dates in x-axis like here: http://www.chartjs.org/samples/latest/scales/time/line.html
I have provided the same configuration (except the date format of graph data) for graph as the above example provides but my graph showing time i.e 2 am, 2 am, .. instead of dates i.e 2018-02-01, 2018-02-10, ...
For date formatting i am using the moment.js library recommended by Chart.js
I am using following code:
<!doctype html>
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.20.1/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.1/Chart.min.js"></script>
</head>
<body>
<div style="width:75%;">
<canvas id="canvas"></canvas>
</div>
<script>
var timeFormat = 'YYYY-MM-DD';
var config = {
type: 'line',
data: {
datasets: [{
label: "Thi is graph label",
backgroundColor: "rgb(54, 162, 235)",
borderColor: "rgb(255, 159, 64)",
fill: false,
data: [{
x: moment("2010-03-01").format(timeFormat),
y: 0.668525
}, {
x: moment("2010-03-02").format(timeFormat),
y: 0.668827
}],
}]
},
options: {
title: {
text: "This is title"
},
scales: {
xAxes: [{
type: "time",
time: {
parser: timeFormat,
tooltipFormat: 'll HH:mm'
},
scaleLabel: {
display: true,
labelString: 'Date'
}
},],
yAxes: [{
scaleLabel: {
display: true,
labelString: 'value'
}
}]
},
}
};
window.onload = function () {
var ctx = document.getElementById("canvas").getContext("2d");
console.log(config);
window.myLine = new Chart(ctx, config);
};
</script>
</body>
</html>
<html>
<head>
<title>Line Chart</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.13.0/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.2/Chart.bundle.js"></script>
<style>
canvas {
-moz-user-select: none;
-webkit-user-select: none;
-ms-user-select: none;
}
</style>
</head>
<body>
<div style="width:75%;">
<canvas id="canvas"></canvas>
</div>
<br>
<br>
<button id="randomizeData">Randomize Data</button>
<button id="addDataset">Add Dataset</button>
<button id="removeDataset">Remove Dataset</button>
<button id="addData">Add Data</button>
<button id="removeData">Remove Data</button>
<script>
var timeFormat = 'MM/DD/YYYY HH:mm';
function newDate(days) {
return moment().add(days, 'd').toDate();
}
function newDateString(days) {
return moment().add(days, 'd').format(timeFormat);
}
var color = Chart.helpers.color;
var config = {
type: 'line',
data: {
labels: [ // Date Objects
newDate(0),
newDate(1),
newDate(2),
newDate(3),
newDate(4),
newDate(5),
newDate(6)
],
datasets: [{
label: 'My First dataset',
backgroundColor: color(window.chartColors.red).alpha(0.5).rgbString(),
borderColor: window.chartColors.red,
fill: false,
data: [
randomScalingFactor(),
randomScalingFactor(),
randomScalingFactor(),
randomScalingFactor(),
randomScalingFactor(),
randomScalingFactor(),
randomScalingFactor()
],
}, {
label: 'My Second dataset',
backgroundColor: color(window.chartColors.blue).alpha(0.5).rgbString(),
borderColor: window.chartColors.blue,
fill: false,
data: [
randomScalingFactor(),
randomScalingFactor(),
randomScalingFactor(),
randomScalingFactor(),
randomScalingFactor(),
randomScalingFactor(),
randomScalingFactor()
],
}, {
label: 'Dataset with point data',
backgroundColor: color(window.chartColors.green).alpha(0.5).rgbString(),
borderColor: window.chartColors.green,
fill: false,
data: [{
x: newDateString(0),
y: randomScalingFactor()
}, {
x: newDateString(5),
y: randomScalingFactor()
}, {
x: newDateString(7),
y: randomScalingFactor()
}, {
x: newDateString(15),
y: randomScalingFactor()
}],
}]
},
options: {
title: {
text: 'Chart.js Time Scale'
},
scales: {
xAxes: [{
type: 'time',
time: {
format: timeFormat,
// round: 'day'
tooltipFormat: 'll HH:mm'
},
scaleLabel: {
display: true,
labelString: 'Date'
}
}],
yAxes: [{
scaleLabel: {
display: true,
labelString: 'value'
}
}]
},
}
};
window.onload = function() {
var ctx = document.getElementById('canvas').getContext('2d');
window.myLine = new Chart(ctx, config);
};
document.getElementById('randomizeData').addEventListener('click', function() {
config.data.datasets.forEach(function(dataset) {
dataset.data.forEach(function(dataObj, j) {
if (typeof dataObj === 'object') {
dataObj.y = randomScalingFactor();
} else {
dataset.data[j] = randomScalingFactor();
}
});
});
window.myLine.update();
});
var colorNames = Object.keys(window.chartColors);
document.getElementById('addDataset').addEventListener('click', function() {
var colorName = colorNames[config.data.datasets.length % colorNames.length];
var newColor = window.chartColors[colorName];
var newDataset = {
label: 'Dataset ' + config.data.datasets.length,
borderColor: newColor,
backgroundColor: color(newColor).alpha(0.5).rgbString(),
data: [],
};
for (var index = 0; index < config.data.labels.length; ++index) {
newDataset.data.push(randomScalingFactor());
}
config.data.datasets.push(newDataset);
window.myLine.update();
});
document.getElementById('addData').addEventListener('click', function() {
if (config.data.datasets.length > 0) {
config.data.labels.push(newDate(config.data.labels.length));
for (var index = 0; index < config.data.datasets.length; ++index) {
if (typeof config.data.datasets[index].data[0] === 'object') {
config.data.datasets[index].data.push({
x: newDate(config.data.datasets[index].data.length),
y: randomScalingFactor(),
});
} else {
config.data.datasets[index].data.push(randomScalingFactor());
}
}
window.myLine.update();
}
});
document.getElementById('removeDataset').addEventListener('click', function() {
config.data.datasets.splice(0, 1);
window.myLine.update();
});
document.getElementById('removeData').addEventListener('click', function() {
config.data.labels.splice(-1, 1); // remove the label first
config.data.datasets.forEach(function(dataset) {
dataset.data.pop();
});
window.myLine.update();
});
</script>
</body>
</html>
You need to set:
scales: {
xAxes: [
{
.....
ticks: {
source: 'date'
},
}
......
],

Is there a way to put an image into the legend of a bar chart (chart.js)?

A simple stacked bar graph
<head>
<title>Stacked Bar Chart</title>
<script src="Chart.bundle.js"></script>
<script src="utils.js"></script>
<style>
canvas {
-moz-user-select: none;
-webkit-user-select: none;
-ms-user-select: none;
}
</style>
</head>
<body>
<div style="width: 75%">
<canvas id="canvas"></canvas>
</div>
<button id="randomizeData">Randomize Data</button>
<script>
chartColors = {
redborder: 'rgba(206, 0, 23, 1)',
darkredborder: 'rgba(206, 0, 23, 0.75)',
lightredborder: 'rgba(206, 0, 23, 0.5)',
};
var barChartData = {
labels: [1<img src='images/badges/Manchester United.png' alt='Manchester United.png' height='30' width='30'>,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32],
datasets: [{
label: 'Goals',
backgroundColor: window.chartColors.redborder,
data: [0,1,3,0,2,0,0,2,0,1,0,1,1,0,0,1,0,0,2,1,0,1,2,1,1,0,0,0,2,2,0,3]
}, {
label: 'Assists',
backgroundColor: window.chartColors.darkredborder,
data: [0,0,1,1,0,0,0,0,1,0,0,0,0,0,0,0,1,0,1,0,0,0,0,0,0,0,0,0,1,0,0,1]
}, {
label: 'Indirect',
backgroundColor: window.chartColors.lightredborder,
data: [0,0,1,0,0,0,0,0,1,1,0,1,0,0,1,0,0,0,1,1,0,1,2,0,0,0,1,0,0,0,0,1]
}]
};
window.onload = function() {
var ctx = document.getElementById('canvas').getContext('2d');
window.myBar = new Chart(ctx, {
type: 'bar',
data: barChartData,
options: {
title: {
display: true,
text: 'Chart.js Bar Chart - Stacked'
},
tooltips: {
mode: 'index',
intersect: false
},
responsive: true,
scales: {
xAxes: [{
stacked: true,
}],
yAxes: [{
stacked: true
}]
}
}
});
};
document.getElementById('randomizeData').addEventListener('click', function() {
barChartData.datasets.forEach(function(dataset) {
dataset.data = dataset.data.map(function() {
return randomScalingFactor();
});
});
window.myBar.update();
});
</script>
</body>
</html>
in the x-axis labels, I am trying to get a small icon (image) to be displayed instead of a number. I have tried to put just the image tag in all possible combinations of " and ' as well as with the number. But to no avail. The chart does not render. It seems that the label needs to recognized as a value to render and the html tag knocks this out of place. I don't see why an image tag cannot be put in there, is there a way to do this?

How to set bar width

Please help out how to set bar width for dynamic values. I want fixed width for single value:
var config = {
type: 'bar',
data: {
labels: ["January"],
datasets: [{
type: 'bar',
label: 'Dataset 1',
backgroundColor: "red",
data: [65, 4, 30, 20, 70],
}, {
type: 'bar',
label: 'Dataset 3',
backgroundColor: "blue",
data: [-65]
}]
},
options: {
scales: {
xAxes: [{
stacked: true
}],
yAxes: [{
stacked: true
}]
}
}
};
var ctx = document.getElementById("myChart").getContext("2d");
new Chart(ctx, config);
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.1.0/Chart.bundle.min.js"></script>
<div style="width:600px">
<canvas id="myChart"></canvas>
</div>