Javascript add int to var name - javascript

I want to add some data for a chart via vue to my javascript.
My Problem is that a don't know how many graphs will be gerenerated (It depends on the data)
Here is my Graph.js File.
import Chart from 'chart.js';
export default
{
template: '<canvas width="200" height="210" id="graph"></canvas>',
props: ['amount', 'values0', 'color0', 'values1', 'color1', 'values2', 'color2'],
ready()
{
var datasetValue = [];
for (var j = 0; j < this.amount; j++)
{
datasetValue[j] =
{
fillColor: "rgba(0, 0, 0 , 0)",
pointColor: "rgba(0, 0, 0, 0)",
pointHighlightFill: "#fff",
pointHighlightStroke: "rgba(220, 220, 220, 1)",
strokeColor : this.color+j,
data: this.values+j,
};
}
var data =
{
labels: ['1s', '2s', '3s', '4s', '5s'],
datasets : datasetValue
};
var context = document.querySelector('#graph').getContext('2d');
new Chart(context).Line(data);
}
}
Here my app.js File:
import Vue from 'vue';
import Graph from './components/Graph';
new Vue({
el: 'body',
components: { Graph }
});
and here my html
<graph
amount="3"
:values0="[3000, 3500, 4000, 6000, 1000]"
color0="rgba(196, 30, 59, 0.7)"
:values1="[4000, 2500, 5000, 3000, 2000]"
color1="rgba(255, 125, 10, 0.7)"
:values2="[5000, 6000, 1000, 5000, 6000]"
color2="rgba(171, 212, 115, 0.7)"
>
</graph>
At the Moment everything is hardcoded, just for testing purposes.
As you can see, I'm using the for Loop to add Multiple Graphs to the Chart. my Problem is that i don't know how to tell Javascript that it has to add the +j directly to the this.color and not the value in it, because i need the values from the html file (which are directly out of the database) and I don't know another effective way to parse them to javascript.
(I know my Code is a bit retarded, I'm new to Javascript...).

Why don't you do something like:
var colors = ['red','green','blue'];
...
strokeColor : colors[j]

Related

SciChart: Working with JavaScript Heatmap Chart

I am using SciChart Library for showing JS Heatmap Chart.
According to the below documentation, the zValues variable is generated using iterate function but when I try to use it in my HTML & CSS based website, Its not working.
https://demo.scichart.com/javascript-heatmap-chart
The error I am getting is:
Uncaught SyntaxError: Unexpected token ':'
I have written the following Code:
Code:
var {sciChartSurface, wasmContext} = await SciChart.SciChartSurface.create("line_chart_3");
// Add XAxis and YAxis
sciChartSurface.xAxes.add(new SciChart.NumericAxis(wasmContext));
sciChartSurface.yAxes.add(new SciChart.NumericAxis(wasmContext));
// Create a Heatmap Data-series. Pass heatValues as a number[][] to the UniformHeatmapDataSeries
var initialZValues: number[][] = iterate(WIDTH, HEIGHT, 200, 0, MAX_SERIES);
var heatmapDataSeries = new SciChart.UniformHeatmapDataSeries(wasmContext,
{
xStart: 100,
xStep: 1,
yStart: 100,
yStep: 1,
zValues: initialZValues
});
// Create a Heatmap RenderableSeries with the color map. ColorMap.minimum/maximum defines the values in
// HeatmapDataSeries which correspond to gradient stops at 0..1
var heatmapSeries = new SciChart.UniformHeatmapRenderableSeries(wasmContext,
{
dataSeries: heatmapDataSeries,
colorMap: new SciChart.HeatmapColorMap(
{
minimum: 0,
maximum: 200,
gradientStops:
[
{ offset: 0, color: "#00008B" },
{ offset: 0.2, color: "#6495ED" },
{ offset: 0.4, color: "#006400" },
{ offset: 0.6, color: "#7FFF00" },
{ offset: 0.8, color: "#FFFF00" },
{ offset: 1.0, color: "#FF0000" }
]
})
});
The above code is arising error on: var initialZValues: number[][] = iterate(WIDTH, HEIGHT, 200, 0, MAX_SERIES);
Please help.
The following line of code is Typescript
var initialZValues: number[][] = iterate(WIDTH, HEIGHT, 200, 0, MAX_SERIES);
remove the : number[][] and it should run.

Using Different Colors In a Chart

My Code:
<div><canvas id="canvas_line" height="200" width="800"></canvas></div>
<div><canvas id="canvas_bar" height="200" width="800"></canvas></div>
<script>
var lineChartData = {
labels : ["14:00","15:00","16:00","17:00","18:00","19:00","20:00","22:00"],
datasets : [
{
label: "CPU IDLE",
fillColor : "rgba(220,220,220,0.2)",
strokeColor : "rgba(220,220,220,1)",
pointColor : "rgba(220,220,220,1)",
pointStrokeColor : "#fff",
pointHighlightFill : "#fff",
pointHighlightStroke : "rgba(220,220,220,1)",
data : [85,35,65,59,90,81,56,55,40,100]
}
]
}
var barChartData = {
labels : ["12:00","13:00","14:00","15:00","16:00","17:00","18:00","19:00","20:00","22:00"],
datasets : [
{
fillColor : "rgba(220,220,220,0.5)",
strokeColor : "rgba(220,220,220,1)",
data : [85,35,65,59,90,81,56,55,40,100]
}
]
}
var ctx_line = document.getElementById("canvas_line").getContext("2d");
window.myLine = new Chart(ctx_line).Line(lineChartData, {
responsive: true
});
var ctx_bar = document.getElementById("canvas_bar").getContext("2d");
window.myLine = new Chart(ctx_bar).Bar(barCharData, {
responsive: true
});
</script>
It looks like this, everything is grey.
But I'd like to change the lineChart's pointColor and barChart's fillcolor to red if its data is above 80, the data below 80 are still grey.
I want it like this, but I don't know how to use different colors in a canvas.
<!DOCTYPE html>
<html>
<head>
<title>123</title>
<script src="http://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script>
<script type="text/javascript" src="http://apps.bdimg.com/libs/Chart.js/0.2.0/Chart.min.js"></script>
</head>
<body>
<canvas id="chartCanvas" height="200" width="800"></canvas>
<script>
$(document).ready(function() {
var chartData = {
labels: ["12:00","13:00","14:00","15:00","16:00","17:00","18:00","19:00","20:00","22:00"],
datasets: [
{
data : [85,35,65,59,90,81,56,55,40,100],
fillColor: 'rgba(220,220,220,0.2)',
strokeColor: 'rgba(220,220,220,1)'
}
]
}
var chartCanvas = document.getElementById("chartCanvas").getContext("2d");
var barChart = new Chart(chartCanvas).Bar(chartData, {responsive: true});
// Set warning color
var bars = barChart.datasets[0].bars;
for(var i = 0; i < bars.length ; i++) {
if(bars[i].value > 80) {
bars[i].fillColor = "rgba(255, 0, 0, 0.2)";
bars[i].strokeColor = "rgba(220, 0, 0, 0.5)";
}
}
// Update the chart
barChart.update();
});
</script>
</body>
</html>
You have to loop to all the bars/points of your chart, check if the value is over 80 and set the color.
Here is an example for the bar chart:
var bars = barChart.datasets[0].bars;
for(var i = 0; i < bars.length; i++) {
if(bars[i].value > 80) {
bars[i].fillColor = "rgba(255, 0, 0, 0.2)";
bars[i].strokeColor = "rgba(220, 0, 0, 0.5)";
}
}
// Update the chart
barChart.update();
Check out this fiddle for a working demo.
To set the color on a line chart you just have to iterate over the points instead of the bars:
var points = lineChart.datasets[0].points;
And of course set the pointColor or whatever you want.

Chart.js remove dataset from tooltip [duplicate]

I'm trying to make a Graph which has to show the Account movement from each Customer.
What I'm trying to do
I've tree lines ;
First line : The minimum balance, if the customer has less than the min. balance, his balance will auto load from his bank account.
Second Line : The current balance
Third Line: The maximum balance : If the customer has more than the max. balance he will become the difference from the system on his bank account.
My Problem
Link to the picture : chartjs tooltip problem
As you see in the tooltip are the all 3 values. The values of the straight lines are irrelevant for the customer because the Limits (max and min are setted from the customer his own) .
To achieve this you can extend the line graph to add an option to show/hide tool-tips on a per dataset basses. The annoying thing is there are only a few changes but whole methods have to be overridden to get the changes in there so the below looks like a lot but its basically 3 changes to the following methods
Initialize - added option to store showTooltip option in each point
getPointsAtEvent - added check to make sure we want to disaply a tool tip when getting points
showTooltip - added check again to make sure we want to dispaly a tool tip
to then use it the chart is set up the same but instead you make it a LineTooltip (thats what i have called the extended chart) and pass anextra option in the datasets call showToolip.
datasets: [{
label: "My First dataset",
fillColor: "rgba(220,220,220,0.5)",
strokeColor: "rgba(220,220,220,0.8)",
highlightFill: "rgba(220,220,220,0.75)",
highlightStroke: "rgba(220,220,220,1)",
showTooltip: false, //NEW OPTION DON"T NEED TO INCLUDE IT IF YOU WANT TO DISPLAY BUT WON"T HURT IF YOU DO
data: [15, 10, 10, 10, 10, 10, 10]
}, {
label: "My second dataset",
fillColor: "rgba(220,220,220,0.5)",
strokeColor: "rgba(220,220,220,0.8)",
highlightFill: "rgba(220,220,220,0.75)",
highlightStroke: "rgba(220,220,220,1)",
showTooltip: false, //NEW OPTION DON"T NEED TO INCLUDE IT IF YOU WANT TO DISPLAY BUT WON"T HURT IF YOU DO
data: [100, 100, 100, 100, 100, 100, 100]
}, {
label: "My third dataset",
fillColor: "rgba(151,187,205,0.5)",
strokeColor: "rgba(151,187,205,0.8)",
highlightFill: "rgba(151,187,205,0.75)",
highlightStroke: "rgba(151,187,205,1)",
data: [28, 48, 40, 19, 86, 27, 90]
}]
i have added bigger comment banners in the below code to try and highlight where the changes got made. I have also added this feature to my fork of chartjs as this could be useful to more people https://github.com/leighquince/Chart.js, using this you can just use a normal line chart and add the showTooltip
Below is the example of extending the Line into a custom chart to include this feature, ive called in LineTooltip as but could be called anything you like that.
Chart.types.Line.extend({
name: "LineTooltip",
/*
* we have to add one item in the init so need to rewrite it again here with the one edit
*/
initialize: function(data) {
//have to get the helpers as we are using this outside chart where it was declared
var helpers = Chart.helpers;
//Declare the extension of the default point, to cater for the options passed in to the constructor
this.PointClass = Chart.Point.extend({
strokeWidth: this.options.pointDotStrokeWidth,
radius: this.options.pointDotRadius,
display: this.options.pointDot,
hitDetectionRadius: this.options.pointHitDetectionRadius,
ctx: this.chart.ctx,
inRange: function(mouseX) {
return (Math.pow(mouseX - this.x, 2) < Math.pow(this.radius + this.hitDetectionRadius, 2));
}
});
this.datasets = [];
//Set up tooltip events on the chart
if (this.options.showTooltips) {
helpers.bindEvents(this, this.options.tooltipEvents, function(evt) {
var activePoints = (evt.type !== 'mouseout') ? this.getPointsAtEvent(evt) : [];
this.eachPoints(function(point) {
point.restore(['fillColor', 'strokeColor']);
});
helpers.each(activePoints, function(activePoint) {
activePoint.fillColor = activePoint.highlightFill;
activePoint.strokeColor = activePoint.highlightStroke;
});
this.showTooltip(activePoints);
});
}
//Iterate through each of the datasets, and build this into a property of the chart
helpers.each(data.datasets, function(dataset) {
var datasetObject = {
label: dataset.label || null,
fillColor: dataset.fillColor,
strokeColor: dataset.strokeColor,
pointColor: dataset.pointColor,
pointStrokeColor: dataset.pointStrokeColor,
showTooltip: dataset.showTooltip,
points: []
};
this.datasets.push(datasetObject);
helpers.each(dataset.data, function(dataPoint, index) {
//Add a new point for each piece of data, passing any required data to draw.
datasetObject.points.push(new this.PointClass({
/*
* set wether to show the tooltip or not, left this as being able to be undfined
* and default to true
*/
showTooltip: dataset.showTooltip === undefined ? true : dataset.showTooltip,
value: dataPoint,
label: data.labels[index],
datasetLabel: dataset.label,
strokeColor: dataset.pointStrokeColor,
fillColor: dataset.pointColor,
highlightFill: dataset.pointHighlightFill || dataset.pointColor,
highlightStroke: dataset.pointHighlightStroke || dataset.pointStrokeColor
}));
}, this);
this.buildScale(data.labels);
this.eachPoints(function(point, index) {
helpers.extend(point, {
x: this.scale.calculateX(index),
y: this.scale.endPoint
});
point.save();
}, this);
}, this);
this.render();
},
/*
* need to edit how points at event works so it only uses points that we want to show the tool tip for
*/
getPointsAtEvent: function(e) {
//have to get the helpers as we are using this outside chart where it was declared
var helpers = Chart.helpers;
var pointsArray = [],
eventPosition = helpers.getRelativePosition(e);
helpers.each(this.datasets, function(dataset) {
helpers.each(dataset.points, function(point) {
if (point.inRange(eventPosition.x, eventPosition.y) && point.showTooltip) pointsArray.push(point);
});
}, this);
return pointsArray;
},
/*
* also need to change how the core showTooltip functions as otherwise, it trys to be helpful
* and grab any points it thinks also need to be displayed
*/
showTooltip: function(ChartElements, forceRedraw) {
//have to get the helpers as we are using this outside chart where it was declared
var helpers = Chart.helpers;
var each = helpers.each;
var indexOf = helpers.indexOf;
var min = helpers.min;
var max = helpers.min;
// Only redraw the chart if we've actually changed what we're hovering on.
if (typeof this.activeElements === 'undefined') this.activeElements = [];
var isChanged = (function(Elements) {
var changed = false;
if (Elements.length !== this.activeElements.length) {
changed = true;
return changed;
}
each(Elements, function(element, index) {
if (element !== this.activeElements[index]) {
changed = true;
}
}, this);
return changed;
}).call(this, ChartElements);
if (!isChanged && !forceRedraw) {
return;
} else {
this.activeElements = ChartElements;
}
this.draw();
if (ChartElements.length > 0) {
// If we have multiple datasets, show a MultiTooltip for all of the data points at that index
if (this.datasets && this.datasets.length > 1) {
var dataArray,
dataIndex;
for (var i = this.datasets.length - 1; i >= 0; i--) {
dataArray = this.datasets[i].points || this.datasets[i].bars || this.datasets[i].segments;
dataIndex = indexOf(dataArray, ChartElements[0]);
if (dataIndex !== -1) {
break;
}
}
var tooltipLabels = [],
tooltipColors = [],
medianPosition = (function(index) {
// Get all the points at that particular index
var Elements = [],
dataCollection,
xPositions = [],
yPositions = [],
xMax,
yMax,
xMin,
yMin;
helpers.each(this.datasets, function(dataset) {
dataCollection = dataset.points || dataset.bars || dataset.segments;
/*
*check to make sure we want to show the point
*/
if (dataCollection[dataIndex] && dataCollection[dataIndex].hasValue() && (dataCollection[dataIndex].showTooltip === undefined || dataCollection[dataIndex].showTooltip)) {
Elements.push(dataCollection[dataIndex]);
}
});
helpers.each(Elements, function(element) {
xPositions.push(element.x);
yPositions.push(element.y);
//Include any colour information about the element
tooltipLabels.push(helpers.template(this.options.multiTooltipTemplate, element));
tooltipColors.push({
fill: element._saved.fillColor || element.fillColor,
stroke: element._saved.strokeColor || element.strokeColor
});
}, this);
yMin = min(yPositions);
yMax = max(yPositions);
xMin = min(xPositions);
xMax = max(xPositions);
return {
x: (xMin > this.chart.width / 2) ? xMin : xMax,
y: (yMin + yMax) / 2
};
}).call(this, dataIndex);
new Chart.MultiTooltip({
x: medianPosition.x,
y: medianPosition.y,
xPadding: this.options.tooltipXPadding,
yPadding: this.options.tooltipYPadding,
xOffset: this.options.tooltipXOffset,
fillColor: this.options.tooltipFillColor,
textColor: this.options.tooltipFontColor,
fontFamily: this.options.tooltipFontFamily,
fontStyle: this.options.tooltipFontStyle,
fontSize: this.options.tooltipFontSize,
titleTextColor: this.options.tooltipTitleFontColor,
titleFontFamily: this.options.tooltipTitleFontFamily,
titleFontStyle: this.options.tooltipTitleFontStyle,
titleFontSize: this.options.tooltipTitleFontSize,
cornerRadius: this.options.tooltipCornerRadius,
labels: tooltipLabels,
legendColors: tooltipColors,
legendColorBackground: this.options.multiTooltipKeyBackground,
title: ChartElements[0].label,
chart: this.chart,
ctx: this.chart.ctx
}).draw();
} else {
each(ChartElements, function(Element) {
var tooltipPosition = Element.tooltipPosition();
new Chart.Tooltip({
x: Math.round(tooltipPosition.x),
y: Math.round(tooltipPosition.y),
xPadding: this.options.tooltipXPadding,
yPadding: this.options.tooltipYPadding,
fillColor: this.options.tooltipFillColor,
textColor: this.options.tooltipFontColor,
fontFamily: this.options.tooltipFontFamily,
fontStyle: this.options.tooltipFontStyle,
fontSize: this.options.tooltipFontSize,
caretHeight: this.options.tooltipCaretSize,
cornerRadius: this.options.tooltipCornerRadius,
text: template(this.options.tooltipTemplate, Element),
chart: this.chart
}).draw();
}, this);
}
}
return this;
},
});
var ctx = document.getElementById("chart").getContext("2d");
var data = {
labels: ["January", "February", "March", "April", "May", "June", "July"],
datasets: [{
label: "My First dataset",
fillColor: "rgba(220,220,220,0.5)",
strokeColor: "rgba(220,220,220,0.8)",
highlightFill: "rgba(220,220,220,0.75)",
highlightStroke: "rgba(220,220,220,1)",
showTooltip: false, //TO USE JUST ADD THIS NEW OPTION ONLY REALLY NEEDS TO PRESENT IF SETTING TO FALSE
data: [15, 10, 10, 10, 10, 10, 10]
}, {
label: "My second dataset",
fillColor: "rgba(220,220,220,0.5)",
strokeColor: "rgba(220,220,220,0.8)",
highlightFill: "rgba(220,220,220,0.75)",
highlightStroke: "rgba(220,220,220,1)",
showTooltip: false, //TO USE JUST ADD THIS NEW OPTION ONLY REALLY NEEDS TO PRESENT IF SETTING TO FALSE
data: [100, 100, 100, 100, 100, 100, 100]
}, {
label: "My third dataset",
fillColor: "rgba(151,187,205,0.5)",
strokeColor: "rgba(151,187,205,0.8)",
highlightFill: "rgba(151,187,205,0.75)",
highlightStroke: "rgba(151,187,205,1)",
data: [28, 48, 40, 19, 86, 27, 90]
}]
};
var myBarChart = new Chart(ctx).LineTooltip(data);
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/1.0.2/Chart.min.js"></script>
<canvas id="chart" width="600px"></canvas>
and a fiddle if you find that easy to view http://jsfiddle.net/leighking2/1Lammwpt/

Different labels in tooltip with chartjs

I am making a radar chart with chartjs. The labels on the side of the radar I have given numbers (so the dataset Labels are numbers, 1 to 10). In the tooltip I do not want to these numbers, but a text linked to it (the text the number refers to). These are in a difrent array.
Is there a way to do this?
At the moment I have the following code:
$scope.drawGraph = function() {
radarOptions = {
scaleShowLabels : false,
scaleFontSize: 10,
pointLabelFontSize : 14,
scaleBeginAtZero: true,
showScale: true,
scaleOverride: true,
scaleSteps: 10,
scaleStepWidth: 10,
scaleStartValue: 0,
showTooltips: true,
customTooltips: false,
tooltipTemplate: "<%if (datasetLabel){%><%=datasetLabel%>: <%}%><%= value + '%'%>"
};
var tempComp = []
for (var i = 0; i < $scope.competencesDB.length; i++) {
tempComp.push({
number: i + 1,
competence: $scope.competencesDB[i]
})
}
var tempLabels = [];
var tempData = [];
var tempName = [];
for (var i = 0; i < tempComp.length; i++) {
// console.log($scope.competencesDB[i])
tempName.push(tempComp[i].competence.name)
tempLabels.push(tempComp[i].number);
if (tempComp[i].competence.progress.length === 0) {
tempData.push(0)
} else{
tempData.push(tempComp[i].competence.progress[tempComp[i].competence.progress.length -1].value);
}
}
radarData = {
//names : tempName
labels : tempLabels,
datasets : [
{
label: tempName,
fillColor : "rgba(173, 209, 244, 0.54)",
strokeColor : "rgba(49, 137, 225, 0.94)",
data : tempData
},
]
};
//Get the context of the Radar Chart canvas element we want to select
var ctx = document.getElementById("radarChart").getContext("2d");
// Create the Radar Chart
var myRadarChart = new Chart(ctx).Radar(radarData, radarOptions);
}
I think I need to change something in the following part:
tooltipTemplate: "<%if (datasetLabel){%><%=datasetLabel%>: <%}%><%= value + '%'%>"
But I don't know how this part of the code works. Can I but some kind of forloop in this to loop through the second datasetLabel part?
Thanks!
You can do this using a function instead of a template string. As you guessed you need to figure out the name from the number.
Here is a generic sample
var numberNames = [
{ number: 1, name: "Eating" },
{ number: 2, name: "Drinking" },
{ number: 3, name: "Sleeping" },
{ number: 4, name: "Designing" },
{ number: 8, name: "Coding" },
{ number: 9, name: "Cycling" },
{ number: 10, name: "Running" }
];
var data = {
labels: numberNames.map(function(e) { return e.number }),
datasets: [
{
label: "My First dataset",
fillColor: "rgba(220,220,220,0.2)",
strokeColor: "rgba(220,220,220,1)",
pointColor: "rgba(220,220,220,1)",
pointStrokeColor: "#fff",
pointHighlightFill: "#fff",
pointHighlightStroke: "rgba(220,220,220,1)",
data: [65, 59, 9, 10, 56, 55, 40]
}
]
};
var ctx = document.getElementById("myChart").getContext("2d");
var myChart = new Chart(ctx).Radar(data, {
tooltipTemplate: function (valueObject) {
return numberNames.filter(function (e) { return e.number === valueObject.label })[0].name + ': ' + valueObject.value;
}
});
I used numberNames but you should be able to replace that with tempComp (after adjusting the labels property and the tooltipTemplate function body slightly).
Fiddle - http://jsfiddle.net/80wdhbwo/

Performance issue with QML QChart

I am using QML bindings for Charts.js, which is based on HTML5 javascript library using the canvas element.
I am trying to use a LinePlot and add data to it during run time. But it gets really slow just a few seconds after i start it.
I am not sure if my code is the reason for the slowdown or the library. Is there anything I can optimize to make my plot behave more smoothly?
I have made the RealtimePlot component below:
import QtQuick 2.0
import jbQuick.Charts 1.0
Rectangle {
property var label: []
property var values: []
property int length: 0
Timer {
id: dataTimer
interval: 100
repeat: true
onTriggered: addData([5, 10])
}
Timer {
id: plotUpdateTimer
interval: 100
repeat: true
running: true
onTriggered: {
chart.repaint()
}
}
Chart {
id: chart
height: parent.height
width: parent.width
chartAnimated: false
//chartAnimationEasing: Easing.InOutElastic
//chartAnimationDuration: 2
chartType: Charts.ChartType.LINE
Component.onCompleted: {
//Start simulated data timer.
dataTimer.start()
//Set data visual properties and data/label variables.
chartData = {
labels: label,
datasets: [
{
label: "Dataset",
fillColor: "rgba(220,220,220,0.2)",
strokeColor: "rgba(220,220,220,1)",
pointColor: "rgba(220,220,220,1)",
pointStrokeColor: "#fff",
pointHighlightFill: "#fff",
pointHighlightStroke: "rgba(220,220,220,1)",
data: values
},
]
};
}
}
function addData(data)
{
//Add new labels/values.
for (var i = length; i < (length + data.length); i++)
{
label.push(i)
values.push(data[i - length])
}
//Update total labels/values length.
length += data.length
}
}

Categories

Resources