chart.js datapoint offset multiple charts - javascript

I am pretty new to using Javascript, so forgive me if this is a nobish question.
I am trying to make a chart with 4 datasets, where 3rd dataset is stacked with 1st and 4th is stacked with 2nd. I've tried using the grouped stacked bar chart, but it just stacks 3rd and 4th on the 2nd.
I've tested using some standard inputs like in the link below.
The below approach works fine with 1 chart, just doesn't seem to work on multiple charts on the same page, as it tries to run the plugin on both charts as soon as the first one is done, which means the 2nd is not done rendering.
How to add an offset to a dataset in Chart js
I've tried using the inline plugin approach from the chart.js doc, but it still runs on both charts.
Is there anyway to get the specific chart instance or is there some other approach to this?
var ctx = document.getElementById("myChartTEC").getContext("2d");
var myChart = new Chart.Line(ctx, {
type: 'line',
data: {
labels: ["JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JUL", "AUG", "SEP", "OCT", "NOV", "DEC", ""],
datasets: [{
data: [5, 10.5, 18.2, 33.9, 121.2, 184.9, 179.9, 196.1, 158.3, 166.3, 66.4, 20.6, null],
pointLabelFontSize: 4,
borderWidth: 2,
fill: false,
lineTension: .3,
borderColor: "#f37029",
borderCapStyle: 'round',
borderDash: [],
borderDashOffset: 0.0,
borderJoinStyle: 'bevel',
pointBorderColor: "#f37029",
pointBackgroundColor: "#f37029",
pointBorderWidth: 1,
pointHoverRadius: 4,
pointHoverBackgroundColor: "rgba(220,220,220,1)",
pointHoverBorderColor: "rgba(220,220,220,1)",
pointHoverBorderWidth: 2,
pointRadius: 4,
pointHitRadius: 10,
spanGaps: false,
},
{
data: [10, 20, 5.2, 35.9, 121.2, 184.9, 179.9, 196.1, 158.3, 166.3, 66.4, 20.6, null],
pointLabelFontSize: 4,
borderWidth: 2,
fill: false,
lineTension: .3,
borderColor: "#f37029",
borderCapStyle: 'round',
borderDash: [],
borderDashOffset: 0.0,
borderJoinStyle: 'bevel',
pointBorderColor: "#f37029",
pointBackgroundColor: "#f37029",
pointBorderWidth: 1,
pointHoverRadius: 4,
pointHoverBackgroundColor: "rgba(220,220,220,1)",
pointHoverBorderColor: "rgba(220,220,220,1)",
pointHoverBorderWidth: 2,
pointRadius: 4,
pointHitRadius: 10,
spanGaps: false,
}
]
},
plugins: [{
afterUpdate: function (chart) {
var dataset = chart.config.data.datasets[0];
var offset = -20;
for (var i = 0; i < dataset._meta[0].data.length; i++) {
var model = dataset._meta[0].data[i]._model;
model.x += offset;
model.controlPointNextX += offset;
model.controlPointPreviousX += offset;
}
var dataset2 = chart.config.data.datasets[1];
var offset2 = 20;
for (var o = 0; o < dataset2._meta[0].data.length; o++) {
var model2 = dataset2._meta[0].data[o]._model;
model2.x += offset2;
model2.controlPointNextX += offset2;
model2.controlPointPreviousX += offset2;
}
}
}],
options: {
scales: {
xAxes: [{
gridLines: {
offsetGridLines: true,
display: false,
borderDash: [6, 2],
tickMarkLength: 5
},
ticks: {
fontSize: 8,
labelOffset: 10,
maxRotation: 0
}
}],
yAxes: [{
gridLines: {
display: false
},
ticks: {
beginAtZero: true,
max: 200,
min: 0,
stepSize: 20,
fontSize: 8
}
}]
},
legend: {
display: false
},
responsive: false,
maintainAspectRatio: true
}
});
var ctx = document.getElementById("myChart").getContext("2d");
var myChart = new Chart.Line(ctx, {
type: 'line',
data: {
labels: ["JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JUL", "AUG", "SEP", "OCT", "NOV", "DEC", ""],
datasets: [{
data: [5, 10.5, 18.2, 33.9, 121.2, 184.9, 179.9, 196.1, 158.3, 166.3, 66.4, 20.6, null],
pointLabelFontSize: 4,
borderWidth: 2,
fill: false,
lineTension: .3,
borderColor: "#f37029",
borderCapStyle: 'round',
borderDash: [],
borderDashOffset: 0.0,
borderJoinStyle: 'bevel',
pointBorderColor: "#f37029",
pointBackgroundColor: "#f37029",
pointBorderWidth: 1,
pointHoverRadius: 4,
pointHoverBackgroundColor: "rgba(220,220,220,1)",
pointHoverBorderColor: "rgba(220,220,220,1)",
pointHoverBorderWidth: 2,
pointRadius: 4,
pointHitRadius: 10,
spanGaps: false,
},
{
data: [10, 20, 5.2, 35.9, 121.2, 184.9, 179.9, 196.1, 158.3, 166.3, 66.4, 20.6, null],
pointLabelFontSize: 4,
borderWidth: 2,
fill: false,
lineTension: .3,
borderColor: "#f37029",
borderCapStyle: 'round',
borderDash: [],
borderDashOffset: 0.0,
borderJoinStyle: 'bevel',
pointBorderColor: "#f37029",
pointBackgroundColor: "#f37029",
pointBorderWidth: 1,
pointHoverRadius: 4,
pointHoverBackgroundColor: "rgba(220,220,220,1)",
pointHoverBorderColor: "rgba(220,220,220,1)",
pointHoverBorderWidth: 2,
pointRadius: 4,
pointHitRadius: 10,
spanGaps: false,
}]
},
// This part is not working. Uncaught TypeError: Cannot read property 'data' of undefined
plugins: [{
afterUpdate: function (chart) {
var dataset = chart.config.data.datasets[0];
var offset = -20;
for (var i = 0; i < dataset._meta[0].data.length; i++) {
var model = dataset._meta[0].data[i]._model;
model.x += offset;
model.controlPointNextX += offset;
model.controlPointPreviousX += offset;
}
var dataset2 = chart.config.data.datasets[1];
var offset2 = 20;
for (var o = 0; o < dataset2._meta[0].data.length; o++) {
var model2 = dataset2._meta[0].data[o]._model;
model2.x += offset2;
model2.controlPointNextX += offset2;
model2.controlPointPreviousX += offset2;
}
}
}],
options: {
scales: {
xAxes: [{
gridLines: {
offsetGridLines: true,
display: false,
borderDash: [6, 2],
tickMarkLength: 5
},
ticks: {
fontSize: 8,
labelOffset: 10,
maxRotation: 0
}
}],
yAxes: [{
gridLines: {
display: false
},
ticks: {
beginAtZero: true,
max: 200,
min: 0,
stepSize: 20,
fontSize: 8
}
}]
},
legend: {
display: false
},
responsive: false,
maintainAspectRatio: true
}
});

The issue is, whenever you create an inline-plugin for a new chart instance, you would also need to increase the index number of _meta[index] in both the for loops. SO, for the first chart it will be _meta[0] , second chart _meta[1] , third chart _meta[2] and so on ...
Here is the working version of your code ...
var ctx = document.getElementById("myChartTEC").getContext("2d");
var myChart = new Chart.Line(ctx, {
type: 'line',
data: {
labels: ["JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JUL", "AUG", "SEP", "OCT", "NOV", "DEC", ""],
datasets: [{
data: [5, 10.5, 18.2, 33.9, 121.2, 184.9, 179.9, 196.1, 158.3, 166.3, 66.4, 20.6, null],
pointLabelFontSize: 4,
borderWidth: 2,
fill: false,
lineTension: .3,
borderColor: "#f37029",
borderCapStyle: 'round',
borderDash: [],
borderDashOffset: 0.0,
borderJoinStyle: 'bevel',
pointBorderColor: "#f37029",
pointBackgroundColor: "#f37029",
pointBorderWidth: 1,
pointHoverRadius: 4,
pointHoverBackgroundColor: "rgba(220,220,220,1)",
pointHoverBorderColor: "rgba(220,220,220,1)",
pointHoverBorderWidth: 2,
pointRadius: 4,
pointHitRadius: 10,
spanGaps: false,
}, {
data: [10, 20, 5.2, 35.9, 121.2, 184.9, 179.9, 196.1, 158.3, 166.3, 66.4, 20.6, null],
pointLabelFontSize: 4,
borderWidth: 2,
fill: false,
lineTension: .3,
borderColor: "#f37029",
borderCapStyle: 'round',
borderDash: [],
borderDashOffset: 0.0,
borderJoinStyle: 'bevel',
pointBorderColor: "#f37029",
pointBackgroundColor: "#f37029",
pointBorderWidth: 1,
pointHoverRadius: 4,
pointHoverBackgroundColor: "rgba(220,220,220,1)",
pointHoverBorderColor: "rgba(220,220,220,1)",
pointHoverBorderWidth: 2,
pointRadius: 4,
pointHitRadius: 10,
spanGaps: false,
}]
},
plugins: [{
afterUpdate: function(chart) {
var dataset = chart.config.data.datasets[0];
var offset = -20;
for (var i = 0; i < dataset._meta[0].data.length; i++) {
var model = dataset._meta[0].data[i]._model;
model.x += offset;
model.controlPointNextX += offset;
model.controlPointPreviousX += offset;
}
var dataset2 = chart.config.data.datasets[1];
var offset2 = 20;
for (var o = 0; o < dataset2._meta[0].data.length; o++) {
var model2 = dataset2._meta[0].data[o]._model;
model2.x += offset2;
model2.controlPointNextX += offset2;
model2.controlPointPreviousX += offset2;
}
}
}],
options: {
scales: {
xAxes: [{
gridLines: {
offsetGridLines: true,
display: false,
borderDash: [6, 2],
tickMarkLength: 5
},
ticks: {
fontSize: 8,
labelOffset: 10,
maxRotation: 0
}
}],
yAxes: [{
gridLines: {
display: false
},
ticks: {
beginAtZero: true,
max: 200,
min: 0,
stepSize: 20,
fontSize: 8
}
}]
},
legend: {
display: false
},
responsive: false,
maintainAspectRatio: true
}
});
var ctx = document.getElementById("myChart").getContext("2d");
var myChart = new Chart.Line(ctx, {
type: 'line',
data: {
labels: ["JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JUL", "AUG", "SEP", "OCT", "NOV", "DEC", ""],
datasets: [{
data: [5, 10.5, 18.2, 33.9, 121.2, 184.9, 179.9, 196.1, 158.3, 166.3, 66.4, 20.6, null],
pointLabelFontSize: 4,
borderWidth: 2,
fill: false,
lineTension: .3,
borderColor: "#f37029",
borderCapStyle: 'round',
borderDash: [],
borderDashOffset: 0.0,
borderJoinStyle: 'bevel',
pointBorderColor: "#f37029",
pointBackgroundColor: "#f37029",
pointBorderWidth: 1,
pointHoverRadius: 4,
pointHoverBackgroundColor: "rgba(220,220,220,1)",
pointHoverBorderColor: "rgba(220,220,220,1)",
pointHoverBorderWidth: 2,
pointRadius: 4,
pointHitRadius: 10,
spanGaps: false,
}, {
data: [10, 20, 5.2, 35.9, 121.2, 184.9, 179.9, 196.1, 158.3, 166.3, 66.4, 20.6, null],
pointLabelFontSize: 4,
borderWidth: 2,
fill: false,
lineTension: .3,
borderColor: "#f37029",
borderCapStyle: 'round',
borderDash: [],
borderDashOffset: 0.0,
borderJoinStyle: 'bevel',
pointBorderColor: "#f37029",
pointBackgroundColor: "#f37029",
pointBorderWidth: 1,
pointHoverRadius: 4,
pointHoverBackgroundColor: "rgba(220,220,220,1)",
pointHoverBorderColor: "rgba(220,220,220,1)",
pointHoverBorderWidth: 2,
pointRadius: 4,
pointHitRadius: 10,
spanGaps: false,
}]
},
plugins: [{
afterUpdate: function(chart) {
var dataset = chart.config.data.datasets[0];
var offset = -20;
for (var i = 0; i < dataset._meta[1].data.length; i++) {
var model = dataset._meta[1].data[i]._model;
model.x += offset;
model.controlPointNextX += offset;
model.controlPointPreviousX += offset;
}
var dataset2 = chart.config.data.datasets[1];
var offset2 = 20;
for (var o = 0; o < dataset2._meta[1].data.length; o++) {
var model2 = dataset2._meta[1].data[o]._model;
model2.x += offset2;
model2.controlPointNextX += offset2;
model2.controlPointPreviousX += offset2;
}
}
}],
options: {
scales: {
xAxes: [{
gridLines: {
offsetGridLines: true,
display: false,
borderDash: [6, 2],
tickMarkLength: 5
},
ticks: {
fontSize: 8,
labelOffset: 10,
maxRotation: 0
}
}],
yAxes: [{
gridLines: {
display: false
},
ticks: {
beginAtZero: true,
max: 200,
min: 0,
stepSize: 20,
fontSize: 8
}
}]
},
legend: {
display: false
},
responsive: false,
maintainAspectRatio: true
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.min.js"></script>
<canvas id="myChartTEC"></canvas>
<canvas id="myChart"></canvas>

Related

Charts.js how to set zero-value on axis?

I'm trying to implement a horizontal bar chart with Charts.js (sample page)
Standard behavior is, that the bars split at the "mirror line" at "0"
See image
How can I set it up to use a different value as mirror line? Like:
See image
Thank your for your advice !
I've found this code on a another post, it will shift the whole graph to the right, maybe this helps?
jsFiddle
var ctx = document.getElementById("canvas");
Chart.pluginService.register({
afterUpdate: function(chart) {
var dataset = chart.config.data.datasets[0];
var offset = 20;
for (var i = 0; i < dataset._meta[0].data.length; i++) {
var model = dataset._meta[0].data[i]._model;
model.x += offset;
model.controlPointNextX += offset;
model.controlPointPreviousX += offset;
}
}
});
var myChart = new Chart.Line(ctx, {
type: 'line',
data: {
labels: ["JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JUL", "AUG", "SEP", "OCT", "NOV", "DEC", ""],
datasets: [{
data: [5, 10.5, 18.2, 33.9, 121.2, 184.9, 179.9, 196.1, 158.3, 166.3, 66.4, 20.6, null],
pointLabelFontSize : 4,
borderWidth: 2,
fill: false,
lineTension: .3,
borderColor: "#f37029",
borderCapStyle: 'round',
borderDash: [],
borderDashOffset: 0.0,
borderJoinStyle: 'bevel',
pointBorderColor: "#f37029",
pointBackgroundColor: "#f37029",
pointBorderWidth: 1,
pointHoverRadius: 4,
pointHoverBackgroundColor: "rgba(220,220,220,1)",
pointHoverBorderColor: "rgba(220,220,220,1)",
pointHoverBorderWidth: 2,
pointRadius: 4,
pointHitRadius: 10,
spanGaps: false,
}]
},
options: {
scales: {
xAxes: [{
gridLines: {
offsetGridLines: true,
display: false,
borderDash: [6, 2],
tickMarkLength:5
},
ticks: {
fontSize: 8,
labelOffset: 10,
maxRotation: 0
}}],
yAxes: [{
gridLines: {
display:false
},
ticks: {
beginAtZero: true,
max: 200,
min: 0,
stepSize: 20,
fontSize: 8
}
}]
},
legend: {
display: false
},
responsive: false,
maintainAspectRatio: true
}
});

Sum of results filtered by month in a chart [LARAVEL]

I am currently trying to do a chart with chart.js, and I would like to get the total number of sales over a year in 1 month increments. I'm currently wondering how to break down the number of sales I make every month knowing that I have the "created_at" column for each order. I know how to do the total for each month with a foreach loop, but to cut out the sales and put the total in a table, I don't see how I could do it.
This is what my table looks like:
This is what my chart looks like:
moment().locale('fr');
var canvas = document.getElementById("bellegaiaChart");
var ctx = canvas.getContext('2d');
// Global Options:
Chart.defaults.global.defaultFontColor = 'black';
Chart.defaults.global.defaultFontSize = 16;
var data = {
labels: ["Jan", "Fev", "Mar", "Avr", "Mai", "Juin", "Jui", "AoĆ»", "Sep", "Oct", "Nov", "Dec"],
datasets: [{
label: "Ventes",
fill: false,
lineTension: 0.1,
backgroundColor: "rgba(225,0,0,0.4)",
borderColor: "red", // The main line color
borderCapStyle: 'square',
borderDash: [], // try [5, 15] for instance
borderDashOffset: 0.0,
borderJoinStyle: 'miter',
pointBorderColor: "black",
pointBackgroundColor: "white",
pointBorderWidth: 1,
pointHoverRadius: 8,
pointHoverBackgroundColor: "yellow",
pointHoverBorderColor: "brown",
pointHoverBorderWidth: 2,
pointRadius: 4,
pointHitRadius: 10,
// notice the gap in the data and the spanGaps: true
data: [65, 59, 80, 81, 56, 110, 40 ,60,55,30,78],
spanGaps: false,
}, {
label: "Nouveaux Clients",
fill: false,
lineTension: 0.1,
backgroundColor: "rgba(167,105,0,0.4)",
borderColor: "rgb(167, 105, 0)",
borderCapStyle: 'butt',
borderDash: [],
borderDashOffset: 0.0,
borderJoinStyle: 'miter',
pointBorderColor: "white",
pointBackgroundColor: "black",
pointBorderWidth: 1,
pointHoverRadius: 8,
pointHoverBackgroundColor: "brown",
pointHoverBorderColor: "yellow",
pointHoverBorderWidth: 2,
pointRadius: 4,
pointHitRadius: 10,
// notice the gap in the data and the spanGaps: false
data: [10, 20, 60, 95, 64, 78, 90,70,40,70,89, 73],
spanGaps: false,
}
]
};
// Notice the scaleLabel at the same level as Ticks
var options = {
scales: {
yAxes: [{
ticks: {
beginAtZero:true
},
scaleLabel: {
display: true,
labelString: 'Moola',
fontSize: 20
}
}]
}
};
// Chart declaration:
var myBarChart = new Chart(ctx, {
type: 'line',
data: data,
options: options
});
This chart is currently integrated in my blade view.
The goal would be to have a table containing all the sales totals per month (so 12 entries in the table) in order to be able to specify it in the data of my chart.

Chart JS - Grid colors and gradient fill not showing

I have the following chart:
var canvas = document.getElementById('chart');
var data = {
labels: ["Q1","Q2","Q3","Q4","Q5"],
datasets: [
{
label: "Your answers",
fill: false,
lineTension: 0.1,
backgroundColor: "rgba(75,192,192,0.4)",
borderColor: "rgba(75,192,192,1)",
borderCapStyle: 'butt',
borderDash: [],
borderDashOffset: 0.0,
borderJoinStyle: 'miter',
pointBorderColor: "rgba(75,192,192,1)",
pointBackgroundColor: "rgba(75,192,192,1)",
pointBorderWidth: 1,
pointHoverRadius: 5,
pointHoverBackgroundColor: "rgba(75,192,192,1)",
pointHoverBorderColor: "rgba(220,220,220,1)",
pointHoverBorderWidth: 2,
pointRadius: 5,
decimals : false,
pointHitRadius: 10,
data: [3,5,6,3,7],
stack: 4
},
{
label: "Average answers",
fill: false,
lineTension: 0.1,
borderColor: "rgba(79,104,241,1)",
borderCapStyle: 'butt',
borderDash: [],
borderDashOffset: 0.0,
borderJoinStyle: 'miter',
pointBorderColor: "rgba(75,192,192,1)",
pointBackgroundColor: "rgba(79,104,241,1)",
pointBorderWidth: 1,
pointHoverRadius: 5,
pointHoverBackgroundColor: "rgba(79,104,241,1)",
pointHoverBorderColor: "rgba(220,220,220,1)",
pointHoverBorderWidth: 2,
pointRadius: 5,
decimals : false,
pointHitRadius: 10,
data: [2,7,5,10,3],
stack: 5
},
{
label: "Your average",
pointStyle: 'line',
fill: false,
borderColor: "#ffffff",
borderCapStyle: 'round',
borderDash: [0.5,5],
borderDashOffset: 1,
lineTension: 0.1,
data: [5,5,5,5,5],
},
{
label: "Audit average",
pointStyle: 'line',
fill: false,
borderColor: "#ffffff",
borderCapStyle: 'round',
borderDash: [5,8],
borderDashOffset: 0.6,
lineTension: 0.1,
data: [7,7,7,7,7],
},
]
};
var option = {
plugins: {
filler: {
propagate: true
}
},
legend : {
display:false
},
showLines: true,
scales: {
yAxes: [{
gridLines: {
color: 'rgb(255, 255, 255)',
display: true,
},
scaleLabel: {
display: true,
labelString: 'Scores'
},
stacked: false,
ticks: {
beginAtZero: 0,
suggestedMin: 1,
suggestedMax: 10,
stepSize: 2,
userCallback: function(label, index, labels) {
// when the floored value is the same as the value we have a whole number
if (Math.floor(label) === label) {
return label;
}
},
}
}],
xAxes: [{
gridLines: {
color: 'rgb(255, 255, 255)',
display: true,
},
scaleLabel: {
display: true,
labelString: 'Questions'
},
}]
},
annotation: {
annotations: [
{
drawTime: "beforeDatasetsDraw",
type: "box",
id: "n",
xScaleID: "x-axis-0",
yScaleID: "y-axis-0",
xMin: "Q1",
xMax: "Q5",
yMin: 0,
yMax: 3.7,
backgroundColor: "rgba(26,26,26,0.6)",
borderColor: "rgba(26,26,26,0.6)",
borderWidth: 1,
},
{
drawTime: "beforeDatasetsDraw",
type: "box",
xScaleID: "x-axis-0",
yScaleID: "y-axis-0",
xMin: "Q1",
xMax: "Q5",
yMin: 3.7,
yMax: 7,
backgroundColor: 'rgba(88,88,88,0.6)',
borderColor: 'rgba(88,88,88,0.6)',
borderWidth: 1,
},
{
drawTime: "beforeDatasetsDraw",
type: "box",
xScaleID: "x-axis-0",
yScaleID: "y-axis-0",
xMin: "Q1",
xMax: "Q5",
yMin: 7,
yMax: 10,
backgroundColor: 'rgba(31,42,97,0.6)',
borderColor: 'rgba(88,88,88,0.6)',
borderWidth: 0,
}
]
}
};
var myLineChart = Chart.Line(canvas,{
data:data,
options: {
responsive: true,
maintainAspectRatio: false,
tooltips: {
mode: 'index'
},
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
});
.wrap { background-color:#000; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.5.0/Chart.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/chartjs-plugin-annotation/0.5.5/chartjs-plugin-annotation.js"></script>
<div class="wrap">
<canvas id="chart" width="400" height="250"></canvas>
</div>
I'm trying to achieve two things:
Change border and gridline colour to white.
Change the gradient fill.
For 1. I have the following code added to the x and y:
gridLines: {
color: 'rgb(255, 255, 255)',
display: true,
}
For 2, I have background colour defined under annotation: {
Why is neither of it working?
Here's a visual of what I'm trying to achieve:
Edit:
I have changed to the following:
var myLineChart = Chart.Line(document.getElementById('chart'), {
data: data,
options: options
});
With the above, the grids and background colors appear as I wanted (thanks to uminders answer). However, the label / key now is not there.
With the following:
var myLineChart = Chart.Line(document.getElementById('chart'), {
data: data,
options: {
responsive: true,
maintainAspectRatio: false
tooltips: {
mode: 'index'
}
}
});
With the above, the key now appears, but the gridlines and background colours do not.
Is there a middle ground I can reach here? I want both, the key and colors.
To show gridlines as expected, define a positive z-index of gridline layer as follows (see Grid Line Configuration).
gridLines: {
color: 'rgb(255, 255, 255)',
z: 2
},
To show gradient fill, use the previously defined options object (renamed from option) when you create the chart.
var myLineChart = Chart.Line(document.getElementById('chart'), {
data: data,
options: options
});
var data = {
labels: ["Q1", "Q2", "Q3", "Q4", "Q5"],
datasets: [{
label: "Your answers",
fill: false,
lineTension: 0.1,
backgroundColor: "rgba(75,192,192,0.4)",
borderColor: "rgba(75,192,192,1)",
borderCapStyle: 'butt',
borderDash: [],
borderDashOffset: 0.0,
borderJoinStyle: 'miter',
pointBorderColor: "rgba(75,192,192,1)",
pointBackgroundColor: "rgba(75,192,192,1)",
pointBorderWidth: 1,
pointHoverRadius: 5,
pointHoverBackgroundColor: "rgba(75,192,192,1)",
pointHoverBorderColor: "rgba(220,220,220,1)",
pointHoverBorderWidth: 2,
pointRadius: 5,
decimals: false,
pointHitRadius: 10,
data: [3, 5, 6, 3, 7],
stack: 4
},
{
label: "Average answers",
fill: false,
lineTension: 0.1,
borderColor: "rgba(79,104,241,1)",
borderCapStyle: 'butt',
borderDash: [],
borderDashOffset: 0.0,
borderJoinStyle: 'miter',
pointBorderColor: "rgba(75,192,192,1)",
pointBackgroundColor: "rgba(79,104,241,1)",
pointBorderWidth: 1,
pointHoverRadius: 5,
pointHoverBackgroundColor: "rgba(79,104,241,1)",
pointHoverBorderColor: "rgba(220,220,220,1)",
pointHoverBorderWidth: 2,
pointRadius: 5,
decimals: false,
pointHitRadius: 10,
data: [2, 7, 5, 10, 3],
stack: 5
},
{
label: "Your average",
pointStyle: 'line',
fill: false,
borderColor: "#ffffff",
borderCapStyle: 'round',
borderDash: [0.5, 5],
borderDashOffset: 1,
lineTension: 0.1,
data: [5, 5, 5, 5, 5],
},
{
label: "Audit average",
pointStyle: 'line',
fill: false,
borderColor: "#ffffff",
borderCapStyle: 'round',
borderDash: [5, 8],
borderDashOffset: 0.6,
lineTension: 0.1,
data: [7, 7, 7, 7, 7],
},
]
};
var options = {
plugins: {
filler: {
propagate: true
}
},
responsive: true,
maintainAspectRatio: false,
tooltips: {
mode: 'index'
},
showLines: true,
scales: {
yAxes: [{
gridLines: {
color: 'rgb(255, 255, 255)',
z: 2
},
scaleLabel: {
display: true,
labelString: 'Scores'
},
stacked: false,
ticks: {
beginAtZero: 0,
suggestedMin: 1,
suggestedMax: 10,
stepSize: 2,
userCallback: function(label, index, labels) {
// when the floored value is the same as the value we have a whole number
if (Math.floor(label) === label) {
return label;
}
},
}
}],
xAxes: [{
gridLines: {
color: 'rgb(255, 255, 255)',
z: 2
},
scaleLabel: {
display: true,
labelString: 'Questions'
},
}]
},
annotation: {
annotations: [
{
drawTime: "beforeDatasetsDraw",
type: "box",
id: "n",
xScaleID: "x-axis-0",
yScaleID: "y-axis-0",
xMin: "Q1",
xMax: "Q5",
yMin: 0,
yMax: 3.7,
backgroundColor: "rgba(26,26,26,0.6)",
borderColor: "rgba(26,26,26,0.6)",
borderWidth: 1,
},
{
drawTime: "beforeDatasetsDraw",
type: "box",
xScaleID: "x-axis-0",
yScaleID: "y-axis-0",
xMin: "Q1",
xMax: "Q5",
yMin: 3.7,
yMax: 7,
backgroundColor: 'rgba(88,88,88,0.6)',
borderColor: 'rgba(88,88,88,0.6)',
borderWidth: 1,
},
{
drawTime: "beforeDatasetsDraw",
type: "box",
xScaleID: "x-axis-0",
yScaleID: "y-axis-0",
xMin: "Q1",
xMax: "Q5",
yMin: 7,
yMax: 10,
backgroundColor: 'rgba(31,42,97,0.6)',
borderColor: 'rgba(88,88,88,0.6)',
borderWidth: 0
}
]
}
};
var myLineChart = Chart.Line(document.getElementById('chart'), {
data: data,
options: options
});
canvas { background-color:#000; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/chartjs-plugin-annotation/0.5.7/chartjs-plugin-annotation.js"></script>
<canvas id="chart" width="400" height="250"></canvas>
Why don't you use var option variable in the declarations? for example:
var myLineChart = Chart.Line(canvas,{
data:data,
options: option
});

Chart.JS Multiline Chart with unknown numbers of Lines from JSON

I try do to a Multi - Linechart with chart.js. I have a json dataset from a database. The number of dataset can be different. Here is a example (x can be more) with JSON Data.
[{"name":"name1","jan":4067.5,"feb":1647,
"mrz":1375,"apr":10191,"mai":0,"jun":28679,"jul":59502},
{"name":"name2","jan":47548,"feb":63280.5,
"mrz":51640.26,"apr":75029,"mai":41137,"jun":89114.26,"jul":77332},
{"name":"name3","jan":38099,"feb":55023.5,
"mrz":62668,"apr":39482,"mai":44193.3,"jun":52826.5,"jul":77072},
{"name":"namex","jan":34930.5,"feb":36831.5,
"mrz":24391,"apr":35051,"mai":38038,"jun":12700,"jul":51080}]
I have abbreviated the example, in reality it is until December.
I try to do a chart with a line for every name. The X-axis should be the months of January to December and the Y-axis sales.
34/5000
From what I understand, your dataset will get dynamically updated.
You can just change your dataset then call the update() function.
For example:
First initialize your chart with all the data using:
var canvas = document.getElementById("barChart");
var ctx = canvas.getContext('2d');
var data = {
labels: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"],
datasets: [{
label: "name 1",
fill: false,
lineTension: 0.1,
backgroundColor: "rgba(225,0,0,0.4)",
borderColor: "red",
borderCapStyle: 'square',
borderDash: [],
borderDashOffset: 0.0,
borderJoinStyle: 'miter',
pointBorderColor: "black",
pointBackgroundColor: "white",
pointBorderWidth: 1,
pointHoverRadius: 8,
pointHoverBackgroundColor: "yellow",
pointHoverBorderColor: "brown",
pointHoverBorderWidth: 2,
pointRadius: 4,
pointHitRadius: 10,
data: [65, 59, 80, 81, 56, 55, 40, ,60,55,30,78]
}, {
label: "name 2",
fill: true,
lineTension: 0.1,
backgroundColor: "rgba(167,105,0,0.4)",
borderColor: "rgb(167, 105, 0)",
borderCapStyle: 'butt',
borderDash: [],
borderDashOffset: 0.0,
borderJoinStyle: 'miter',
pointBorderColor: "white",
pointBackgroundColor: "black",
pointBorderWidth: 1,
pointHoverRadius: 8,
pointHoverBackgroundColor: "brown",
pointHoverBorderColor: "yellow",
pointHoverBorderWidth: 2,
pointRadius: 4,
pointHitRadius: 10,
data: [10, 20, 60, 95, 64, 78, 90,,70,40,70,89]
}
]
};
var options = {
scales: {
yAxes: [{
ticks: {
beginAtZero:true
},
scaleLabel: {
display: true,
labelString: 'Moola',
fontSize: 20
}
}]
}
};
// Chart declaration:
var myBarChart = new Chart(ctx, {
type: 'line',
data: data,
options: options
});
Then if you later want to update your data, you can just:
myBarChart.data.datasets = [{
label: "name 3",
fill: true,
lineTension: 0.1,
backgroundColor: "rgba(167,105,0,0.4)",
borderColor: "rgb(167, 105, 0)",
borderCapStyle: 'butt',
borderDash: [],
borderDashOffset: 0.0,
borderJoinStyle: 'miter',
pointBorderColor: "white",
pointBackgroundColor: "black",
pointBorderWidth: 1,
pointHoverRadius: 8,
pointHoverBackgroundColor: "brown",
pointHoverBorderColor: "yellow",
pointHoverBorderWidth: 2,
pointRadius: 4,
pointHitRadius: 10,
data: [10, 20, 60, 95, 64, 78, 90,,70,40,70,89]
},
...............
];
myBarChart.update();
Also, you will need to format your data in a way that can be used with the charts.
Format your data so that you can create a proper dataset.

ChartJS Scatter plot with JSON list variable not working

I want to plot scatter plots from a JSON variable (list of lists; in the format needed for Chart JS scatter plots) that I passed from Flask.
render_template('chart.html',data2 = data2)
The below code when I manually create datasets using jinja variable {{data2}} is working:
var chartData = {
datasets : [{
label: 'Cluster 1',
fill: false,
showLine: false,
lineTension: 0.1,
backgroundColor: "green",
borderColor: "black", // The main line color
borderCapStyle: 'square',
borderDash: [], // try [5, 15] for instance
borderDashOffset: 0.0,
borderJoinStyle: 'miter',
pointBorderColor: "green",
pointBackgroundColor: "green",
pointBorderWidth: 1,
pointHoverRadius: 8,
pointHoverBackgroundColor: "yellow",
pointHoverBorderColor: "brown",
pointHoverBorderWidth: 2,
pointRadius: 4,
pointHitRadius: 10,
// notice the gap in the data and the spanGaps: true
data :{{data2[0]}},
spanGaps: true,
},
{
label: 'Cluster 2',
fill: false,
showLine: false,
lineTension: 0.1,
backgroundColor: "blue",
borderColor: "black", // The main line color
borderCapStyle: 'square',
borderDash: [], // try [5, 15] for instance
borderDashOffset: 0.0,
borderJoinStyle: 'miter',
pointBorderColor: "blue",
pointBackgroundColor: "blue",
pointBorderWidth: 1,
pointHoverRadius: 8,
pointHoverBackgroundColor: "yellow",
pointHoverBorderColor: "brown",
pointHoverBorderWidth: 2,
pointRadius: 4,
pointHitRadius: 10,
// notice the gap in the data and the spanGaps: true
data :{{data2[1]}},
spanGaps: true,
},
{
label: 'Cluster 3',
fill: false,
showLine: false,
lineTension: 0.1,
backgroundColor: "red",
borderColor: "black", // The main line color
borderCapStyle: 'square',
borderDash: [], // try [5, 15] for instance
borderDashOffset: 0.0,
borderJoinStyle: 'miter',
pointBorderColor: "red",
pointBackgroundColor: "red",
pointBorderWidth: 1,
pointHoverRadius: 8,
pointHoverBackgroundColor: "yellow",
pointHoverBorderColor: "brown",
pointHoverBorderWidth: 2,
pointRadius: 4,
pointHitRadius: 10,
// notice the gap in the data and the spanGaps: true
data :{{data2[2]}},
spanGaps: true,
},.....so on
// get chart canvas
var holder = document.getElementById("myChart2");
var ctx = document.getElementById("myChart2").getContext("2d");
// create the chart using the chart canvas
var myChart = new Chart(ctx, {
type: 'scatter',
data: chartData,
options: {
scales: {
xAxes: [{
display: true,
ticks: {
beginAtZero: true,
autoSkip: true,
autoSkipPadding: 30,
stepSize: 500,
maxTicksLimit: 10
},
scaleLabel: {
display: true,
labelString: 'Days',
fontStyle: 'bold'
}
}],
yAxes: [{
display: true,
scaleLabel: {
display: true,
labelString: 'Oil Rate',
fontStyle: 'bold'
}
}]
}
}
});
But when I use tojson and use the same variable in a for loop its not working (Rendering a blank chart):
var ds = []
var d2 = {{data2|tojson}}
for (var j=0; j < {{o}}; j++){
ds.push ({
label: 'Cluster' +j,
fill: false,
showLine: false,
lineTension: 0.1,
backgroundColor: colorlist[j],
borderColor: colorlist[j], // The main line color
borderCapStyle: 'square',
borderDash: [], // try [5, 15] for instance
borderDashOffset: 0.0,
borderJoinStyle: 'miter',
pointBorderColor: "green",
pointBackgroundColor: "green",
pointBorderWidth: 1,
pointHoverRadius: 8,
pointHoverBackgroundColor: "yellow",
pointHoverBorderColor: "brown",
pointHoverBorderWidth: 2,
pointRadius: 4,
pointHitRadius: 10,
// notice the gap in the data and the spanGaps: true
data :d2[j],
spanGaps: true,
});
}
var chartData2 = {
datasets : ds
}
var holder = document.getElementById("myChart2");
var ctx = document.getElementById("myChart2").getContext("2d");
// create the chart using the chart canvas
var myChart2 = new Chart(ctx, {
type: 'scatter',
data: chartData2,
options: {
scales: {
xAxes: [{
display: true,
ticks: {
beginAtZero: true,
autoSkip: true,
autoSkipPadding: 30,
stepSize: 500,
maxTicksLimit: 10
},
scaleLabel: {
display: true,
labelString: 'Days',
fontStyle: 'bold'
}
}],
yAxes: [{
display: true,
scaleLabel: {
display: true,
labelString: 'Oil Rate',
fontStyle: 'bold'
}
}]
}
}
});
For more clarity, this is how my data2 was created for scatter chart js:
x2 = {}
y2 = {}
data = {}
for i in n:
x2[i] = list(df_no_anamolies['Days'[df_no_anamolies["clusters_oilvsDays"]==i])
y2[i] = list(df_no_anamolies['Oil_rate(stb/d)'[df_no_anamolies["clusters_oilvsDays"]==i])
T = []
for j,k in zip(x2[i],y2[i]):
T.append({'x': j, 'y': k})
data[i] = str(T).replace('\'', '')
dt2 = list(data.items())
data2 = []
for i in range(len(dt2)):
data2.append(dt2[i][1])
This how my data2 looks like:
['[{x: 429, y: 21862.782000000003}, {x: 430, y: 21769.1868}]',
'[{x: 431, y: 21752.5183}, {x: 432, y: 21406.0022}]',
'[{x: 433, y: 20823.7369},'[{x: 434, y: 21101.5033}]',
'[{x: 435, y: 22031.354}, {x: 434, y: 21101.5033}]'....]
Can someone help me with how to do this with a loop.
Your "Y" objects are Decimal objects and the JsonEnconder doesn't accept Decimal objects. I usually just create a subclass of the json.JSONEncoder.
class DecimalEncoder(json.JSONEncoder):
def _iterencode(self, o, markers=None):
if isinstance(o, decimal.Decimal):
return (str(o) for o in [o])
return super(DecimalEncoder, self)._iterencode(o, markers)
then you can use it as
json.dumps({'Y': decimal.Decimal('21769.1868')}, cls=DecimalEncoder)
I think you'll need to parse those json strings before passing them to chart.js
var chartData2 = {
datasets : [{label: 'Cluster 1',
fill: false,
showLine: false,
lineTension: 0.1,
backgroundColor: "green",
borderColor: "black",
borderCapStyle: 'square',
borderDash: [],
borderDashOffset: 0.0,
borderJoinStyle: 'miter',
pointBorderColor: "green",
pointBackgroundColor: "green",
pointBorderWidth: 1,
pointHoverRadius: 8,
pointHoverBackgroundColor: "yellow",
pointHoverBorderColor: "brown",
pointHoverBorderWidth: 2,
pointRadius: 4,
pointHitRadius: 10,
data : JSON.parse( {{ data[1] }} ),
spanGaps: true,
}]
}

Categories

Resources