pass data to data line chart - javascript

rates: [
{
id: 1,
idea_id: this.$route.params.id_Idae,
// group_id: "1",
moon: 1,
revenue: 0,
total_revenue: 0,
cost: 0,
total_cost: 0,
profit: 0,
},
],
addDataToChart() {
this.rates.map((item, index) => {
var l = this.rates[index].profit;
this.trazMali.push({
id: l,
});
console.log(l);
console.error(index);
});
},
var x = this.trazMali;
datasets: [
{
label: "# of Votes",
data: x,
borderColor: ["rgba(255, 159, 64, 1)"],
borderWidth: 1,
},
],
i want pass data from a p tag to data of line chart but my codes Maximum call stack size exceeded

Related

ChartJS radar-chart hover text

How do you add custom text over points in radar charts when you hover over them?
I have been following this tutorial but the data in radar chart are in array formats instead of object as specified here so it doesn't apply.
My current radar chart:
JSfiddle
let dataValues = [100, 120, 80, 100, 90, 110, 100, 100, 100]
If you wait until Chart.js version 3.8 is getting released you can use object notation with radar charts:
let dataValues = [{
value: 100,
text: 'f'
},
{
value: 120,
text: 'd'
},
{
value: 80,
text: 'q'
},
{
value: 100,
text: 'b'
},
{
value: 90,
text: 'z'
},
{
value: 110,
text: 'efw'
},
{
value: 100,
text: 'ffew'
},
{
value: 100,
text: 'ffdddew'
},
{
value: 100,
text: 'fffff'
}
]
const sum = dataValues.reduce((a, b) => a.value + b.value, 0);
const avg = sum / dataValues.length;
const sorted = [...dataValues].sort(function(a, b) {
return a.value - b.value;
})
const data = {
labels: [
'Signal 1',
'Signal 2',
'Signal 3',
'Signal 4',
'Signal 5',
'Signal 6',
'Signal 7',
'Signal 8',
'Signal 9'
],
datasets: [{
label: '9 signals',
data: dataValues,
fill: true,
backgroundColor: 'rgba(210, 203, 203, 0.4)',
borderColor: 'rgb(210, 203, 203, 0.6)',
pointBackgroundColor: function(context) {
const index = context.dataIndex;
const value = context.dataset.data[index].value;
return value < sorted[3].value ? 'blue' :
value < sorted[5].value ? 'green' :
value < sorted[7].value ? 'orange' :
'red';
},
pointBorderColor: '#fff',
pointHoverBackgroundColor: '#fff',
pointHoverBorderColor: 'rgb(255, 99, 132)'
}]
};
const config = {
type: 'radar',
data: data,
options: {
plugins: {
tooltip: {
callbacks: {
label: (ctx) => (`${ctx.dataset.label}: ${ctx.parsed.r} ${ctx.dataset.data[ctx.dataIndex].text}`)
}
}
},
parsing: {
key: 'value'
},
elements: {
line: {
borderWidth: 3
},
point: {
pointRadius: 5
}
},
scales: {
r: {
angleLines: {
lineWidth: 2
},
grid: {
circular: true,
lineWidth: 2
}
}
}
}
};
let myChart = new Chart(
document.getElementById('myChart'),
config
);
<div class="chartBox">
<canvas id="myChart"></canvas>
<script src="https://www.chartjs.org/dist/master/chart.js"></script>
</div>

ChartJS: Adjust Tooltip with sums in body

I have the following output at the moment:
However, I would like to have the following table:
Minimum: 90
25th: 95
25th to Median: 100
(the blue one I dont want to show)
75th: 105
Max: 110
I have the following code, I hope this will be enough:
const data = {
labels: [
REMockProducts[0].valuations[0].short,
REMockProducts[0].valuations[1].short,
REMockProducts[0].valuations[2].short,
REMockProducts[0].valuations[3].short,
REMockProducts[0].valuations[4].short,
REMockProducts[0].valuations[5].short,
REMockProducts[0].valuations[6].short,
],
datasets: [
{
label: "Minimum",
data: [
REMockProducts[0].valuations[0].min,
REMockProducts[0].valuations[1].min,
REMockProducts[0].valuations[2].min,
REMockProducts[0].valuations[3].min,
REMockProducts[0].valuations[4].min,
REMockProducts[0].valuations[5].min,
REMockProducts[0].valuations[6].min,
],
toCheck: 0,
},
{
label: "25th",
data: [
lwpercDistance(0, 0)[0],
lwpercDistance(0, 1)[0],
lwpercDistance(0, 2)[0],
lwpercDistance(0, 3)[0],
lwpercDistance(0, 4)[0],
lwpercDistance(0, 5)[0],
lwpercDistance(0, 6)[0],
],
toCheck: 1,
},
{
label: "25th to Median",
data: [
medianDistance(0, 0)[0],
medianDistance(0, 1)[0],
medianDistance(0, 2)[0],
medianDistance(0, 3)[0],
medianDistance(0, 4)[0],
medianDistance(0, 5)[0],
medianDistance(0, 6)[0],
],
toCheck: 2,
},
{
label: false,
data: [0, 0, 0, 0, 0, 0, 0],
toCheck: 3,
},
{
label: "75th",
data: [
hipercDistance(0, 0)[0],
hipercDistance(0, 1)[0],
hipercDistance(0, 2)[0],
hipercDistance(0, 3)[0],
hipercDistance(0, 4)[0],
hipercDistance(0, 5)[0],
hipercDistance(0, 6)[0],
],
toCheck: 4,
},
{
label: "Max",
data: [
maxDistance(0, 0)[0],
maxDistance(0, 1)[0],
maxDistance(0, 2)[0],
maxDistance(0, 3)[0],
maxDistance(0, 4)[0],
maxDistance(0, 5)[0],
maxDistance(0, 6)[0],
],
toCheck: 5
},
],
};
[...] <Bar
data={data}
options={{
plugins: {
legend: {
position: "top",
},
tooltips: {
callbacks: {
label : function(data, tooltip) {
let k = 0;
let j = 0;
for (k; k < 5; k++) {
for (j; j < 7; j++) {
if (k > 0) {
let tooltip =
data.datasets[0].data[j] + data.datasets[k].data[j];
} else {
let tooltip = data.datasets[0].data[j];
}
}
return { text: tooltip };
}
},
},
},
},
indexAxis: "y",
scales: {
x: {
stacked: true,
ticks: {
autoSkip: false,
},
},
y: {
stacked: true,
ticks: {
autoSkip: false,
},
},
},
}}
/>
It is probably pretty clear that I am inexperiences with nested loops in JS.
The basic idea was to run through each dataset and either take the face value of the "Minimum" data or add them up.
Hovering over my tooltip variable actually shows the following:
I clearly must make an obvious mistake I can't figure out.
Links that helped me so far:
ChartJs different data for Tooltips
If condition not working for ChartJS
[Edit] I actually just realized that I did the sum incorrectly. Doesn't change much though
Basically your question is two parts.
Filter the 0 values
Add accumulative sum to each datapoint in tooltip
I simplified your code as you had a for loop which was not needed as it could be done all in Chart JS tooltip.
I created a video with the entire breakdown and explanation. You can watch here for more understanding: ChartJS: Adjust Tooltip with sums in body
See code below:
<script>
// setup
const data = {
labels: ['Red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange'],
datasets: [{
label: '# of Votes',
data: [12, 19, 3, 5, 2, 3],
backgroundColor: 'rgba(255, 99, 132, 0.2)',
borderColor: 'rgba(255, 99, 132, 1)',
borderWidth: 1
},{
label: '# of Cost',
data: [11, 4, 0, 7, 10, 13],
backgroundColor: 'rgba(54, 162, 235, 0.2)',
borderColor: 'rgba(54, 162, 235, 1)',
borderWidth: 1
},{
label: '# of Sales',
data: [10, 0, 10, 0, 10, 22],
backgroundColor:
'rgba(255, 206, 86, 0.2)',
borderColor: 'rgba(255, 206, 86, 1)',
borderWidth: 1
}]
};
// tooltip block
const tooltip = {
yAlign: 'bottom',
filter: function filterZeroData(datapoint) {
return datapoint.raw > 0;
},
callbacks: {
label: function(context) {
const stackedBarArray = [];
for (i = 0; i <= context.datasetIndex; i++){
stackedBarArray.push(context.parsed._stacks.y[i]);
};
console.log(stackedBarArray);
// reduce array
const reducer = (accumulator, currentValue) => accumulator + currentValue;
// return value in tooltip
console.log(context.dataset.label)
const labelName = context.dataset.label;
const labelValue = stackedBarArray.reduce(reducer);
return `${labelName} ${labelValue}`;
}
}
};
// config
const config = {
type: 'bar',
data,
options: {
plugins: {
tooltip,
},
scales: {
x: {
stacked: true
},
y: {
stacked: true,
beginAtZero: true
}
}
}
};
// render init block
const myChart = new Chart(
document.getElementById('myChart'),
config
);
</script>

Echarts: Plot the variance of signals

I want to plot the variance of multiple signals in a chart (or basically fillup the space between an upper and a lower signal).
Is it possible to create such kind of charts?
I saw the confidence-band example (https://echarts.apache.org/examples/en/editor.html?c=confidence-band) , however this seems to work only for one signal in a chart.
Another solution would be to draw thousands of small rectangles using markArea around the signals but this slows down the performance of the chart (e.g. when scrolling the x-axisis) and doesnt look very smooth.
As I know the common practice in Echarts community draw usual chart type (bar, line, ...) with series (read docs) and write visual logic by custom series for unique. Also Echarts has some API methods (undocumented) like registerVisual, registerLayout that can be used for redefine layouts, computation and so on.
For described task you need to use custom series for calculate bands coordinates. It's not very simple because (it seems to me) mandatory requirements with confidence band is rare.
About performance. Echarts by default use Canvas for render visual parts. Usually Canvas has no many parts in HTML for display chart, it's just imageData rendered by browser and it almost doesn't matter how many data point need to display. In other words, we see PNG, and not a lot of div, svg, g and others layers with geometric primitives as in SVG but heavy computation complex business logic may affect the responsiveness of UI as in other charts.
Below example how would I implement this feature. I'm not sure that's the right way but it work and can be tuned.
var dates = ['2020-01-03','2020-01-31','2020-02-17','2020-02-18','2020-03-13','2020-04-10','2020-05-01','2020-05-19','2020-05-22','2020-05-25'];
var sensor1 = [0.6482086334797242, 0.9121368038482911, 0.3205730196548609, 0.8712238348969002, 0.4487714576177558, 0.9895025457815625, 0.0415490306934774, 0.1592908349676395, 0.5356690594518069, 0.9949108727912939];
var sensor2 = [0.8278430459565170, 0.5700757488718124, 0.9803575576802187, 0.0770264671179814,0.2843735619252158,0.8140209568127250,0.6055633547296827,0.9554255125528607,0.1703504100638565,0.5653245914197297];
// Calculate fake bands coordinates
function calcContourCoords(seriesData, ctx){
var addNoise = idx => Math.round(Math.random() * 8 * idx);
var pixelCoords = seriesData.map((dataPoint, idx) => {
return [
ctx.convertToPixel({ xAxisIndex: 0 }, idx) + addNoise(idx),
ctx.convertToPixel({ yAxisIndex: 0 }, dataPoint) + addNoise(idx)
]
});
var polyfilltype = ClipperLib.PolyFillType.pftEvenOdd;
var linePath = new ClipperLib.Path();
var delta = 15;
var scale = 1;
for (var i = 0; i < pixelCoords.length; i++){
var point = new ClipperLib.IntPoint(...pixelCoords[i]);
linePath.push(point);
}
var co = new ClipperLib.ClipperOffset(1.0, 0.25);
co.AddPath(linePath, ClipperLib.JoinType.jtRound, ClipperLib.EndType.etOpenSquare);
co.Execute(linePath, delta * scale);
return co.m_destPoly.map(c => [c.X, c.Y])
}
// Render visual by calculated coords
function renderItem(params, api){
// Prevent multiple call
if (params.context.rendered) return;
params.context.rendered = true;
// Get stored in series data for band
var series = myChart.getModel().getSeriesByName(params.seriesName)[0];
var seriesData = series.get('data');
// Calculate band coordinates for series
var bandCoords = calcContourCoords(seriesData, myChart);
// Draw band
return {
type: 'polygon',
shape: {
points: echarts.graphic.clipPointsByRect(bandCoords, {
x: params.coordSys.x,
y: params.coordSys.y,
width: params.coordSys.width,
height: params.coordSys.height
})
},
style: api.style({
fill: series.option.itemStyle.color
})
};
}
// =============
var option = {
tooltip: {},
legend: {
data:['Label']
},
xAxis: [
{ name: 'x0', data: dates, boundaryGap: true },
{ name: 'x1', data: dates, boundaryGap: true, show: false },
],
yAxis: [
{ name: 'y0' },
{ name: 'y1', show: false },
],
series: [
// First line
{
name: 'Sensor1',
type: 'line',
data: sensor1,
itemStyle: { color: 'rgba(69, 170, 242, 1)' },
yAxisIndex: 0,
xAxisIndex: 0,
},
{
name: 'BandSensor1',
type: 'custom',
data: sensor1,
itemStyle: { color: 'rgba(69, 170, 242, 0.2)' },
renderItem: renderItem,
yAxisIndex: 0,
xAxisIndex: 0,
},
// Second line
{
name: 'Sensor2',
type: 'line',
data: sensor2,
itemStyle: { color: 'rgba(253, 151, 68, 1)' },
yAxisIndex: 1,
xAxisIndex: 1,
},
{
name: 'BandSensor2',
type: 'custom',
data: sensor2,
itemStyle: { color: 'rgba(253, 151, 68, 0.2)' },
renderItem: renderItem,
yAxisIndex: 1,
xAxisIndex: 1,
},
]
};
var myChart = echarts.init(document.getElementById('main'));
myChart.setOption(option);
<script src="https://cdn.jsdelivr.net/npm/clipper-lib#6.4.2/clipper.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/echarts/4.7.0/echarts.min.js"></script>
<div id="main" style="width: 800px;height:600px;"></div>
Improved version of #Sergey Fedorov- this solution takes into account min,max values or. dynamic border thicness of the band
var dates = ['2020-01-03', '2020-01-31', '2020-02-17', '2020-02-18', '2020-03-13', '2020-04-10', '2020-05-01', '2020-05-19', '2020-05-22', '2020-05-25', '2020-05-27'];
const data_raw1 = [
{ min: -5, mean: 0, max: 0 },
{ min: 1, mean: 2, max: 5 },
{ min: 2, mean: 4, max: 6 },
{ min: 4, mean: 5, max: 8 },
{ min: 7, mean: 11, max: 14 },
{ min: 11, mean: 15, max: 17 },
{ min: 6, mean: 8, max: 8.5 },
{ min: -1, mean: 5, max: 6 },
{ min: 4, mean: 9, max: 12 },
{ min: 14, mean: 18, max: 22 },
{ min: 18, mean: 20, max: 21 },
];
const data_raw2 = [
{ min: 10, mean: 15, max: 20 },
{ min: 12, mean: 25, max: 30 },
{ min: 22, mean: 26, max: 32 },
{ min: 30, mean: 31, max: 45 },
{ min: 47, mean: 49, max: 50 },
{ min: 30, mean: 32, max: 41 },
{ min: 34, mean: 36, max: 38 },
{ min: 40, mean: 42, max: 45 },
{ min: 47, mean: 49, max: 56 },
{ min: 60, mean: 68, max: 70 },
{ min: 75, mean: 80, max: 85 },
];
const data_raw3 = data_raw2.map(d => ({ min: d.min * 1.2 + 10, mean: d.mean * 1.4 + 11, max: d.max * 1.5 + 12 }))
function calcContourCoords(seriesData, ctx) {
console.log("seriesData=", seriesData);
const pixelCoords = []
for (let i = 0; i < seriesData.length; i++) {
console.log(i, seriesData[i]);
pixelCoords.push([
ctx.convertToPixel({ xAxisIndex: 0 }, i),
ctx.convertToPixel({ yAxisIndex: 0 }, seriesData[i].max)
]);
}
console.log("\n")
for (let i = seriesData.length - 1; i >= 0; i--) {
console.log(i, seriesData[i]);
pixelCoords.push([
ctx.convertToPixel({ xAxisIndex: 0 }, i),
ctx.convertToPixel({ yAxisIndex: 0 }, seriesData[i].min)
]);
if (i == 0) {
pixelCoords.push([
ctx.convertToPixel({ xAxisIndex: 0 }, i),
ctx.convertToPixel({ yAxisIndex: 0 }, seriesData[i].max)
]);
}
}
var linePath = new ClipperLib.Path();
var delta = 10;
var scale = 1;
for (var i = 0; i < pixelCoords.length; i++) {
var point = new ClipperLib.IntPoint(...pixelCoords[i]);
linePath.push(point);
}
var co = new ClipperLib.ClipperOffset(1.0, 0.25);
co.AddPath(linePath, ClipperLib.JoinType.jtRound, ClipperLib.EndType.etClosedPolygon);
co.Execute(linePath, delta * scale);
return co.m_destPoly.map(c => [c.X, c.Y])
}
// Render visual by calculated coords
function renderItem(params, api) {
// Prevent multiple call
if (params.context.rendered) return;
params.context.rendered = true;
// Get stored in series data for band
var series = myChart.getModel().getSeriesByName(params.seriesName)[0];
var seriesData = series.get('data');
// Calculate band coordinates for series
var bandCoords = calcContourCoords(seriesData, myChart);
// Draw band
return {
type: 'polygon',
shape: {
points: echarts.graphic.clipPointsByRect(bandCoords, {
x: params.coordSys.x,
y: params.coordSys.y,
width: params.coordSys.width,
height: params.coordSys.height
})
},
style: api.style({
fill: series.option.itemStyle.color
})
};
}
// =============
var option = {
tooltip: {},
legend: {
data: ['Label']
},
xAxis: [
{ name: 'x0', data: dates, boundaryGap: true },
{ name: 'x1', data: dates, boundaryGap: true, show: false },
],
yAxis: [
{ name: 'y0' },
{ name: 'y1', show: false },
],
series: [
// First line
{
name: 'Sensor1',
type: 'line',
data: data_raw1.map(d => d.mean),
itemStyle: { color: 'rgba(69, 170, 242, 1)' },
yAxisIndex: 0,
xAxisIndex: 0,
itemStyle: { color: 'red' },
},
{
name: 'BandSensor1',
type: 'custom',
data: data_raw1,
itemStyle: { color: 'rgba(69, 170, 242, 0.2)' },
renderItem: renderItem,
yAxisIndex: 0,
xAxisIndex: 0,
itemStyle: { color: 'red', opacity: 0.1 },
},
{
name: 'Sensor2',
type: 'line',
data: data_raw2.map(d => d.mean),
itemStyle: { color: 'rgba(69, 170, 242, 1)' },
yAxisIndex: 0,
xAxisIndex: 0,
itemStyle: { color: 'blue' },
},
{
name: 'BandSensor2',
type: 'custom',
data: data_raw2,
itemStyle: { color: 'rgba(69, 170, 242, 0.2)' },
renderItem: renderItem,
yAxisIndex: 0,
xAxisIndex: 0,
itemStyle: { color: 'blue', opacity: 0.1 },
},
{
name: 'Sensor3',
type: 'line',
data: data_raw3.map(d => d.mean),
itemStyle: { color: 'rgba(69, 170, 242, 1)' },
yAxisIndex: 0,
xAxisIndex: 0,
itemStyle: { color: 'green' },
},
{
name: 'BandSensor3',
type: 'custom',
data: data_raw3,
itemStyle: { color: 'rgba(69, 170, 242, 0.2)' },
renderItem: renderItem,
yAxisIndex: 0,
xAxisIndex: 0,
itemStyle: { color: 'green', opacity: 0.1 },
},
]
};
var myChart = echarts.init(document.getElementById('chart'));
myChart.setOption(option);

Displaying line chart for multiple datasets using chart.js

I have to display a line chart with two different datasets in one single chart. After execution of query I got the plan_plan and actual_plan of the following form.
plan_plan = 0: {week: "46", planned_del: "20"}
1: {week: "53", planned_del: "94"}
actual_plan = 0: {week: "8", actual_del: "1"}
javascript part:
function show_Graph()
{
{
var plandata = <?php echo json_encode($plan_plan); ?>;
var actualdata = <?php echo json_encode($actual_plan); ?>;
console.log(plandata);
var labels = [];
var plandel = [];
var actualdel = [];
for (var i in plandata) {
labels.push(plandata[i].week);
plandel.push(plandata[i]);
}
for (var j in actualdata) {
labels.push(actualdata[j].week);
actualdel.push(actualdata[j]);
}
var chartdata = {
labels: labels,
datasets: [
{
label: "Planned Deliverables",
fill: false,
borderColor: "rgba(255, 0, 0, 1)",
pointHoverBackgroundColor: "rgba(255, 0, 0, 1)",
data: plandel
},
{
label: "Actual Deliverables",
fill: false,
backgroundColor: "rgba(0, 255, 0, 0.75)",
borderColor: "rgba(0, 255, 0, 1)",
pointHoverBackgroundColor: "rgba(0, 255, 0, 1)",
pointHoverBorderColor: "rgba(0, 255, 0, 1)",
data: actualdel
}
]
};
var graphTarget = $("#scurve_chart");
var barGraph = new Chart(graphTarget, {
type: 'line',
data: chartdata,
options: {
elements: {
point:{
radius: 1,
}
},
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}],
xAxes: [{
barValueSpacing: 2,
barPercentage: 0.2
}]
}
}
});
}}
I want to get the week in x axis and then planned_del and actual_del data in y axis which can be shown as line chart. And also should show a single point entry even when there is no data points to be connected.
One way for achieving this, would be to defined data.labels as an array of numbers from 0 to 53.
labels: [0, 1, 2, ... 53]
The data inside the two datasets would then only contain the definitions of individual points.
data: [{ x: 46, y: 20 }, { x: 53, y: 94 }] // plandata
...
data: [{ x: 8, y: 1}] // actualdata
Here's the JavaScript part that illustrates how the desired result can be obtained.
var plandata = [{ week: "46", planned_del: "20" }, { week: "53", planned_del: "94" }];
var actualdata = [{ week: "8", actual_del: "1" }];
new Chart("scurve_chart", {
type: 'line',
data: {
labels: Array.from(new Array(54), (x, i) => i),
datasets: [{
label: "Planned Deliverables",
fill: false,
borderColor: "rgba(255, 0, 0, 1)",
pointHoverBackgroundColor: "rgba(255, 0, 0, 1)",
data: plandata.map(o => ({ x: Number(o.week), y: Number(o.planned_del)}))
},
{
label: "Actual Deliverables",
fill: false,
backgroundColor: "rgba(0, 255, 0, 0.75)",
borderColor: "rgba(0, 255, 0, 1)",
pointHoverBackgroundColor: "rgba(0, 255, 0, 1)",
pointHoverBorderColor: "rgba(0, 255, 0, 1)",
data: actualdata.map(o => ({x: Number(o.week), y: Number(o.actual_del)}))
}
]
},
options: {
tooltips: {
callbacks: {
title: (tooltipItem, data) => "Week " + data.datasets[tooltipItem[0].datasetIndex].data[tooltipItem[0].index].x
}
},
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}],
xAxes: [{
ticks: {
min: 0,
max: 53,
stepSize: 1
}
}]
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.bundle.js"></script>
<canvas id="scurve_chart" height="90"></canvas>

Refreshing the image of a chart using chart.js

I'm doing an app that displays daily personal work data.
I store the data in an array called "dailyTimePerProjectPerWeek", for now I define the data for 3 weeks.
I have placed two buttons in the html, "Previous Week" and "Next Week", to navigate between the weeks.
When the page is loaded for the first time it shows the most recent week corresponding to the highest index of the array mentioned above.
The problem is that it does something strange to me to visualize the data, it's like that I created several charts.
How can I refresh the image of the chart properly?
There goes my html code:
<!DOCTYPE html>
<html lang="en" >
<head>
<meta charset="UTF-8">
<title>Charts4DailyProgress</title>
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<body>
<h1>Weekly Time per Project</h1>
<div id="canvas-container">
<canvas id="ctx" width="1000"></canvas>
<button type="button" onclick="decrementWeek()">Previous Week</button>
<button type="button" onclick="incrementWeek()">Next Week</button>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.min.js"></script>
<script src="js/index.js"></script>
</body>
</html>
There goes my javascript code:
var dailyTimePerProjectPerWeek =[];
dailyTimePerProjectPerWeek[0] = {
labels: ['M', 'TU','W','TH','F','SA','SU'], // responsible for how many bars are gonna show on the chart
// create 12 datasets, since we have 12 items
// data[0] = labels[0] (data for first bar - 'Standing costs') | data[1] = labels[1] (data for second bar - 'Running costs')
// put 0, if there is no data for the particular bar
datasets: [{
label: 'Master Project. Second Part',
data: [300, 480, 360,180, 240, 300,480],
backgroundColor: '#D4AF37'
}, {
label: 'Guild Ideas - Learning Angular',
data: [60, 0, 240, 180, 120, 0, 60],
backgroundColor: '#C0C0C0'
}, {
label: 'Charts For Daily Progress',
data: [60, 180, 120, 180, 120, 120, 0],
backgroundColor: '#133a7c'
}, {
label: 'Project Manager',
data: [120, 180, 120, 120, 0],
backgroundColor: '#109618'
}, {
label: 'TOOYS',
data: [0, 180, 120, 0, 120, 0,0],
backgroundColor: '#990099'
}, {
label: 'Web Pc Explorer',
data: [0, 0, 120, 180, 0, 120, 0],
backgroundColor: '#54161F'
}, {
label: 'Mind Maps Program',
data: [0, 0, 180, 180, 0, 0, 0],
backgroundColor: '#708238'
}, {
label: 'Chain System',
data: [0, 0, 180, 0, 0, 0],
backgroundColor: '#E86100'
}, {
label: 'Code Generator',
data: [60, 0, 0, 0, 0, 0],
backgroundColor: '#F81894'
}, {
label: 'Electronic Brain',
data: [0, 0, 0, 0, 0, 0,240],
backgroundColor: '#6cc4ee'
}]
}
dailyTimePerProjectPerWeek[1] = {
labels: ['M', 'TU','W','TH','F','SA','SU'], // responsible for how many bars are gonna show on the chart
// create 12 datasets, since we have 12 items
// data[0] = labels[0] (data for first bar - 'Standing costs') | data[1] = labels[1] (data for second bar - 'Running costs')
// put 0, if there is no data for the particular bar
datasets: [{
label: 'Master Project. Second Part',
data: [0, 480, 360,180, 240, 300,480],
backgroundColor: '#D4AF37'
}, {
label: 'Guild Ideas - Learning Angular',
data: [0, 0, 240, 180, 120, 0, 60],
backgroundColor: '#C0C0C0'
}, {
label: 'Charts For Daily Progress',
data: [0, 180, 120, 180, 120, 120, 0],
backgroundColor: '#133a7c'
}, {
label: 'Project Manager',
data: [0, 180, 120, 120, 0],
backgroundColor: '#109618'
}, {
label: 'TOOYS',
data: [0, 180, 120, 0, 120, 0,0],
backgroundColor: '#990099'
}, {
label: 'Web Pc Explorer',
data: [0, 0, 120, 180, 0, 120, 0],
backgroundColor: '#54161F'
}, {
label: 'Mind Maps Program',
data: [0, 0, 180, 180, 0, 0, 0],
backgroundColor: '#708238'
}, {
label: 'Chain System',
data: [0, 0, 180, 0, 0, 0],
backgroundColor: '#E86100'
}, {
label: 'Code Generator',
data: [0, 0, 0, 0, 0, 0],
backgroundColor: '#F81894'
}, {
label: 'Electronic Brain',
data: [0, 0, 0, 0, 0, 0,240],
backgroundColor: '#6cc4ee'
}]
}
dailyTimePerProjectPerWeek[2] = {
labels: ['M', 'TU','W','TH','F','SA','SU'], // responsible for how many bars are gonna show on the chart
// create 12 datasets, since we have 12 items
// data[0] = labels[0] (data for first bar - 'Standing costs') | data[1] = labels[1] (data for second bar - 'Running costs')
// put 0, if there is no data for the particular bar
datasets: [{
label: 'Master Project. Second Part',
data: [300, 480, 360,180, 240, 300,0],
backgroundColor: '#D4AF37'
}, {
label: 'Guild Ideas - Learning Angular',
data: [60, 0, 240, 180, 120, 0, 0],
backgroundColor: '#C0C0C0'
}, {
label: 'Charts For Daily Progress',
data: [60, 180, 120, 180, 120, 120, 0],
backgroundColor: '#133a7c'
}, {
label: 'Project Manager',
data: [120, 180, 120, 120, 0],
backgroundColor: '#109618'
}, {
label: 'TOOYS',
data: [0, 180, 120, 0, 120, 0,0],
backgroundColor: '#990099'
}, {
label: 'Web Pc Explorer',
data: [0, 0, 120, 180, 0, 120, 0],
backgroundColor: '#54161F'
}, {
label: 'Mind Maps Program',
data: [0, 0, 180, 180, 0, 0, 0],
backgroundColor: '#708238'
}, {
label: 'Chain System',
data: [0, 0, 180, 0, 0, 0],
backgroundColor: '#E86100'
}, {
label: 'Code Generator',
data: [60, 0, 0, 0, 0, 0],
backgroundColor: '#F81894'
}, {
label: 'Electronic Brain',
data: [0, 0, 0, 0, 0, 0,0],
backgroundColor: '#6cc4ee'
}]
}
var currentWeek = dailyTimePerProjectPerWeek.length - 1;
var weekValue = currentWeek; //At first time weekValue points to the current week
function drawData(){
var chart = new Chart(ctx, {
type: 'bar',
data: dailyTimePerProjectPerWeek[weekValue],
options: {
responsive: false,
legend: {
position: 'right' // place legend on the right side of chart
},
scales: {
xAxes: [{
stacked: true // this should be set to make the bars stacked
}],
yAxes: [{
stacked: true // this also..
}]
}
}
});
}
function incrementWeek(){
if(weekValue === dailyTimePerProjectPerWeek.length - 1){
console.log("This is the current week");
} else {
weekValue += 1;
drawData();
}
}
function decrementWeek(){
if(weekValue === 0){
console.log("This is the oldest week of the time series");
} else {
weekValue -= 1;
drawData();
}
}
/*
function selectWeek(){
}
*/
/*
function fixWeek(){
}*/
//Main Program
var chart = new Chart(ctx, {
type: 'bar',
data: dailyTimePerProjectPerWeek[weekValue],
options: {
responsive: false,
legend: {
position: 'right' // place legend on the right side of chart
},
scales: {
xAxes: [{
stacked: true // this should be set to make the bars stacked
}],
yAxes: [{
stacked: true // this also..
}]
}
}
});
The truth is that I use the following code to try to refresh the image:
function drawData(){
var chart = new Chart(ctx, {
type: 'bar',
data: dailyTimePerProjectPerWeek[weekValue],
options: {
responsive: false,
legend: {
position: 'right' // place legend on the right side of chart
},
scales: {
xAxes: [{
stacked: true // this should be set to make the bars stacked
}],
yAxes: [{
stacked: true // this also..
}]
}
}
});
}
Change your drawData() function to:
function drawData() {
chart.data = dailyTimePerProjectPerWeek[weekValue];
chart.update();
}

Categories