Avoid data resetting when toggling series - javascript

In this fiddle when you toggle a serie the others reset to their inital values, instead of adding new values to themselves.
How to avoid this behaviour?

You need to store the current state of the data for each series before blanking or resetting the corresponding dataset in enableCheck. Then use this saved state.
Example for the SP dataset
Initialization of the state (spData). I also initialize the dataset (SP)
var spData = [1, 2, 3, 4, 5, 6, 7, 8]
var SP = {}
Saving the state (in enableCheck()) - I get the values from the actual data points
if (SP.data) currentChart.datasets.forEach(function (d) {
if (d.label === 'My First dataset') {
spData = d.points.map(function (e) {
return e.value
});
}
})
Using this saved state (in enableCheck())
SP = {
label: "My First dataset",
fillColor: "rgba(0,0,0,0)",
strokeColor: "rgba(220,0,0,1)",
pointColor: "rgba(220,0,0,1)",
pointStrokeColor: "#fff",
pointHighlightFill: "#fff",
pointHighlightStroke: "rgba(220,0,0,1)",
data: spData
};
And if you want the new values to be inserted for the hidden series as well, update your data insertion statements in your setTimeout
var d = []
if (First) d.push(randomScalingFactor())
else {
spData.shift()
spData.push(randomScalingFactor())
}
if (Second) d.push(randomScalingFactor())
else {
ncData.shift()
ncData.push(randomScalingFactor())
}
if (Third) d.push(randomScalingFactor())
else {
spaData.shift()
spaData.push(randomScalingFactor())
}
Working fiddle - http://jsfiddle.net/Lsg37amf/

Related

Setting Canvas Limits Over the Existing Dataset Values

I've got a little problem with html5 canvas. I've got a couple of line charts made but they have a problem with maximum grid values (sort of field limits inside the canvas itself). The chart is building from a dataset coming from the database and only through these values.
The example: sample chart
As you can see here, the above limit is 5.55, and the question is how to change that to a bigger value (for example, using a percentage of such maximum value or something so that other charts' offsets would match as well)?
The code:
$('#graf_' + i + '').html('<canvas id="lineChart' + i + '" width="' + $(".graf").width() + '" height="200"></canvas>');
var lineData = {
labels: data["headers"],
datasets: [{
label: data["rates"][i]["VltName"],
fillColor: "transparent",
strokeColor: data["rates"][i]["VltColor"],
pointColor: data["rates"][i]["VltColor"],
pointStrokeColor: "#fff",
pointHighlightFill: "#fff",
pointHighlightStroke: "rgba(220,220,220,1)",
data: getRatesArr
}]
};
var lineOptions = {
scaleShowGridLines: true,
scaleGridLineColor: "rgba(0,0,0,.05)",
scaleGridLineWidth: 1,
bezierCurve: false,
pointDot: true,
pointDotRadius: 4,
pointDotStrokeWidth: 1,
pointHitDetectionRadius: 20,
datasetStroke: true,
datasetStrokeWidth: 2,
datasetFill: true
};
var ctx = document.getElementById("lineChart" + i).getContext("2d");
var myNewChart = new Chart(ctx).Line(lineData, lineOptions);
Hope my explanation is not too vague. Thanks in advance!
If you update to the latest Chart.js version (currently v2.6.0), you can use the max tick configuration option to set the max number to display on the axis:
options: {
scales: {
yAxes: [{
ticks: {
max: yourMaxNum
}
}]
}
}
If you want to set yourMaxNum to the largest number in all your dataset arrays, simply use the JavaScript Math.max() method to determine this number, and set the above chart config option to this number when you create all your line charts.
The Chart.js documentation lists additional tick configuration options that you might also find useful.

Chart.js - get base 64 encoded string as variable

I'm creating a chart using the Chart.js library and it's working well. I'm using the .toBase64Image() function to generate a base 64 encoded string of the chart (png data url).
I can see this when I inspect the chart in my browser developer tools, e.g.:
data:image/png;base64,iVBORw0KGgoAAAA etc
I now need to call a URL to another application that will pass the data url as a parameter - I'm just stuck at how to get the data url as a parameter to pass to my URL that I will then call.
Here's my script as it currently stands:
var radarChartData = {
labels: ["Eating", "Drinking", "Sleeping", "Designing", "Coding", "Cycling", "Running"],
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: [3, 2, 1, 5, 6, 8, 5]
},
]
};
window.onload = function() {
window.myRadar = new Chart(document.getElementById("canvas").getContext("2d")).Radar(radarChartData, {
responsive: true,
scaleOverride: true,
scaleSteps: 10,
scaleStepWidth: 1,
scaleStartValue: 0,
onAnimationComplete: function() {
document.getElementById("canvas").innerHTML = myRadar.toBase64Image();
theURL = "fmp://$/chartingFile?script=getChartToContainer&param=";
window.location = theURL;
}
});
}
I need to append the "data:image/png;base64,iVBORw0KGgoAAAA" string to the 'theURL' variable but can't figure out how to get this as a string?
Managed to work this out as follows:
onAnimationComplete: function() {
document.getElementById("canvas").innerHTML = myRadar.toBase64Image();
var x = document.getElementById("canvas").innerHTML = myRadar.toBase64Image();
theParam = encodeURIComponent(x);
theURL = "fmp://$/chartingFile?script=getChartToContainer&param=" + theParam;
window.location = theURL;
Not sure if it's optimal etc but it's working well so far.

Looping inside variable (json data)

Anyone know how looping json data INSIDE varibale?? Example
var data = {
$.each(data, function(i, item) {
console.log(data[i].PageName);
});​
labels: [dateLoop],
datasets: [{
}]
};
Well that code is didnt work for me. I want looping inside that varibale. Anyway this coding for Chart.js
Why i need looping?? cuase i have filter buyer and date range, if i choose 3 buyer, and date range from january 2016 to May 2016. On data will show data buyer, each data buyer will have value from date range. Exmaple data json
data [Buyer 1] : ["167404", "129770", "113598", "127301", "156868", "634789", "242188", "166312", "169418"];
data [Buyer 2] : ["9580", "22250", "3500", "5558", "254556", "268500", "77750", "69850", "55"];
So what i need how too looping inside variable?? Sorry my bad languange.
Edit probbaly someone dont know what i mean,
example i have pick 2 buyer, Buyer A (Json["data"][0]) and Buyer B (Json["data"][1]) and each that buyer have value (wich this value order by month if i pick January and May, it will show "222","555")
and the code i mean like this :
var data = {
labels: [dateLoop], #ignore this
datasets: [{ label : (Json["data"][0])
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: [(value orderby month in Json["data"][0]]
},
{ label : (Json["data"][1])
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: [(value orderby month in Json["data"][1]]
}
]
};
That i want it. But i sue each make error. :/
try this, you need 2 loop first loop is for keys and second is for the values inside array
var data = {
'Buyer 1': ["167404", "129770", "113598", "127301", "156868", "634789", "242188", "166312", "169418"],
'Buyer 2': ["9580", "22250", "3500", "5558", "254556", "268500", "77750", "69850", "55"]
}
for(var key in data) {
for (var x in data[key]) {
console.log(data[key][x]);
}
}

Control which lines have points?

With Chart.js, you can set in the options of the graph to show points or not:
pointDot: true,
I have a graph with three static lines and one line that shows some fluctuations. I'd like the straight lines not to have points but the fluctuation line show the points. Is there a setting somewhere on the line that I can set the point size to nothing?
** Edit **
Each line is its own set of data configured like this:
datasets: [
{
label: "Cycle Time Per Last Piece",
strokeColor: "red",
fillColor: "red",
pointHighlightFill: "red",
data: [#foreach (var item in Model.DataPoints) {
#(Model.ExpectedCycleTimePerPart * 1.20M)#:,
}]
},
{
label: "Expected Cycle Time Per Part",
strokeColor: "black",
pointHighlightFill: "black",
data: [#foreach (var item in Model.DataPoints) {
#Model.ExpectedCycleTimePerPart#:,
}]
}
The pointDot option drives the display property, so you can do something like
myChart.datasets[0].points[2].display = false;
where myChart is your chart object.

chart.js Hide empty Chart and keep previous data if no data? .net MVC

I have a chart where based on date, data changes. Problem current date is default and sometimes there is no data to show. is it possible with chart.js to check for if there is data in current chart and keep previous if there is none. Subing it with DIV placeholder ect. Same data is also in DataTable. Not really good at writing conditions yet.
Things I tried so far:
if (sampleTable != null && sampleTable.rows.count > 0) {
$("#labelDiv").hide();
}
if (parsedData.Item2 = null)
{
$("#labelDiv").hide();
}
if (buyerData == null) {
$("#labelDiv").hide();
}
chart
var buyerData = {
labels: parsedData.Item2,
datasets: [
{
label: "Lazi Chart",
fillColor: "rgba(10,190,10,0.6)",
strokeColor: "rgba(151,187,205,0.8)",
highlightFill: "rgba(151,187,205,0.75)",
highlightStroke: "rgba(151,187,205,1)",
data: parsedData.Item3,
}
]
}
barChartOptions.datasetFill = false;
barChart.Bar(barChartData, barChartOptions);
I figured it out. I check if object is empty and then if it is place a div saying experimental data and fake chart. Tnx for Any Help.
if (parsedData.Item1 != "") {
$("#labelDiv").hide();
$("#buyers").show();
}
else {
$("#labelDiv").show();
$("#FakeData").show();
$("#buyers").hide();
var barData = {
labels: ['SaaS', 'Virtual Machines', 'Networking', 'Storage', 'Data Managment'],
datasets: [
{
label: '2010 customers #',
fillColor: '#382765',
data: [2500, 1902, 1041, 610, 1245]
},
{
label: '2014 customers #',
fillColor: '#7BC225',
data: [3104, 1689, 1318, 589, 1199]
}
]
};
var context = document.getElementById('FakeData').getContext('2d');
var clientsChart = new Chart(context).Bar(barData);
I don't know chart.js, but by it's name I'll assume it's a plugin to draw graphs.
Probably, it'll require that you feed them with data, or at least, with an endpoint where read the data, so it can draw a graph that represent these data.
Now... if you have a data collection, or an endpoint where check for data, won't be easy to check these data and redirect your code execution than try to do that from within a plugin?
If the collection of data is empty or you don't get data from the endpoint just end the execution or return it to the last call (which you could have stored previously if necessary)

Categories

Resources