Flot Chart area getting smaller at each iteration - javascript

I'm using Flot Charts to plot the data and I am facing a strange problem. At each iteration, the plot area gets smaller, in the images attached this can be seen. I will post the function I'm using to plot to make it easier to understand or to locate the error.
<script type="text/javascript">
$(document).ready(function () {
var xVal = 0;
var data3 = [[],[]];
var dataset4=<?php echo json_encode($dataset4); ?>;
var dataset5=<?php echo json_encode($dataset5); ?>;
var totallength = dataset4.length;
var options3 = {
};
var plot = $.plot( $("#placeholder3"), data3, options3);
var yVal1 = [];
var yVal2 = [];
function getData(){
yVal1 = parseFloat(dataset5[xVal]);
//yVal2 = parseFloat(dataset5[xVal +1]);
var datum1 = [parseFloat(dataset4[xVal]), yVal1];
//var datum2 = [parseFloat(dataset4[xVal + 1]), yVal2];
data3[0].push(datum1);
//data3[1].push(datum2);
if(data[0].length>10){
data3[0] = data3[0].splice(1);
//data3[1] = data3[1].splice(1);
}
xVal++;
plot.setData(data3);
plot.setupGrid();
if(xVal<=totallength){
plot.draw();
}
}
var plot = $.plot( $("#placeholder3"), data3, options3);
setInterval(getData, 1000);
});
</script>
Maybe the error is at the setupGrid, or at the plot.draw... I just don't know. Thanks for your time in advance!

It seems that moving the plot action inside the if statement where I had the plot.draw() solved it. Now the plot area remains stable and plots properly.

Related

Google Visualization Multiple Charts - Options Not Working

I have a multi-chart Google Visualization script (1 column chart and 2 line charts). The charts are working/displaying correctly except for the var Options code. The most important part of the Options section is being able to change the column/line color. So I tried changing it using the role: 'style'} alternative, but it didn't work either.
Please see below code for the 3 charts. I'm new to Google Visualization, so any feedback/help is much appreciated!
google.charts.load('current', {
packages: ['corechart', 'controls']
}).then(function () {
// Chart data
var data = [];
data[0] = google.visualization.arrayToDataTable ([["Date","Sessions", {role: 'style'}],
<?php
for($a = 0; $a < 7; $a++)
{
echo "['".$date[$a]."', ".$sessions[$a].", 'fill-color: #76A7FA'],";
}
?>
]);
data[1] = google.visualization.arrayToDataTable ([["Date","Sessions"],
<?php
for($a = 0; $a < 31; $a++)
{
echo "['".$date[$a]."', ".$sessions[$a]."],";
}
?>
]);
data[2] = google.visualization.arrayToDataTable ([["Date","Sessions"],
<?php
for($a = 0; $a < count($query); $a++)
{
echo "['".$date[$a]."', ".$sessions[$a]."],";
}
?>
]);
var current = 0;
var current_chart = 0;
// Create and draw the visualization
var chart = [];
chart[0] = new google.visualization.ColumnChart(document.getElementById('sessions_chart'));
chart[1] = new google.visualization.LineChart(document.getElementById('sessions_chart'));
function drawChart() {
// Disabling the buttons while the chart is drawing.
document.getElementById('week_btn').disabled = true;
document.getElementById('month_btn').disabled = true;
document.getElementById('all_btn').disabled = true;
google.visualization.events.addListener(chart, 'ready', function() {
// Enable the buttons after the chart has been drawn
document.getElementById('week_btn').disabled = false;
document.getElementById('month_btn').disabled = false;
document.getElementById('all_btn').disabled = false;
});
var view = new google.visualization.DataView(data[current]);
var options = {
title: 'Number of Sessions',
vAxis: {title: "# of Sessions", minValue:0},
hAxis: {format: 'MMM d, y'},
colors: 'lightgreen'
};
// Convert first column to date format
view.setColumns([{
calc: function (dt, row) {
return new Date(dt.getValue(row, 0));
},
label: data[current].getColumnLabel(0),
type: 'date'
}, 1]);
chart[current_chart].draw(view, data[current], options);
}
drawChart();
// google.charts.setOnLoadCallback(drawChart);
document.getElementById('week_btn').addEventListener("click", displayWeek);
function displayWeek() {
current = 0;
current_chart = 0;
drawChart();
}
document.getElementById('month_btn').addEventListener("click", displayMonth);
function displayMonth() {
current = 1;
current_chart = 1;
drawChart();
}
document.getElementById('all_btn').addEventListener("click", displayAll);
function displayAll() {
current = 2;
current_chart = 1;
drawChart();
}
});
the colors option should be an array...
colors: ['lightgreen']
as for the style role, try providing only the color...
echo "['".$date[$a]."', ".$sessions[$a].", '#76A7FA'],";
AND
highly recommend NOT building json manually in php from a string.
instead, separate the php from the html in two different files.
build the data in php and return the encoded json to the page.
then use ajax to call the php page and get the encoded json.
then draw the chart.
here are some examples...
How to automatically update Google Gauge
JSON $ajax problems

Draw more than one chart on loop and chart.js framework

I have a .json file that contains my charts, like this. So, using jQuery i get the data from json like:
/* myFunctionThatLoadCharts */
$.getJSON("myfilewithcharts.json", function(data){
var myCharts = [];
var ctx = [];
var typeofChart;
var dataofChart;
var optionsofChart;
var dashboard = document.getElementById("dashboard");
for (let chart in data.charts){
var content = "<div id='"+chart+"' class='square'>"+
"<canvas id='chart"+chart+"' width='400' height='400'></canvas>"+
"</div>";
dashboard.innerHTML = dashboard.innerHTML + content;
ctx.push(document.getElementById("chart"+chart).getContext('2d'));
typeofChart = data.charts[chart].type;
dataofChart = data.charts[chart].data;
optionsofChart = data.charts[chart].options;
myCharts.push(new Chart(ctx[chart], {
type: typeofChart,
data: dataofChart,
options: optionsofChart
}));
content = "";
typeofChart = "";
dataofChart = "";
optionsofChart = "";
}
}
Where
data
is the response from $.getJSON jQuery function. But problem is: the code only generates the last chart and not both.
This function is invoked on <body> tag with onload attribute.. so, <body onload=myFunctionThatLoadCharts()>
Got it!
Before finding the solution i noticed that although there is in the DOM the elements to draw the other graphics, the code only referenced the last one. So i needed to generate the entire DOM for the graphics first and then draw them.
The problem was happening because "innerHTML" command, rewrite all DOM elements which interact with him, so i was losting all references for charts.
Now i have two functions, one to generate the DOM e another for draw the charts, like this
/* myFunctionThatGeneratesDOMelements */
var typeofChart = [];
var dataofChart = [];
var optionsofChart = [];
var dashboard = document.getElementById("dashboard");
$.getJSON("myfilewithcharts.json", function(data){
for (let chart in data.charts){
var content = "<div id='"+chart+"' class='square'>"+
"<canvas id='chart"+chart+"' width='400' height='400'></canvas>"+
"</div>";
dashboard.innerHTML = dashboard.innerHTML + content;
typeofChart.push(data.charts[chart].type);
dataofChart.push(data.charts[chart].data);
optionsofChart.push(data.charts[chart].options);
}
drawCharts(typeofChart, dataofChart, optionsofChart);
});
/* myFunctionToDrawCharts */
function drawCharts (toc, doc, ooc) {
var ctx = [];
var myCharts = [];
for(let i = 0; i < toc.length; i++){
ctx.push($("#chart"+i).get(0).getContext('2d'));
myCharts.push(new Chart(ctx[i], {
type: toc[i],
data: doc[i],
options: ooc[i]
}));
}
}
Other solutions is insertAdjacentHTML() and appendChild()

Zingchart last element keeps changing color and not matching with legend

My zingchart's last element's color does not match with legend, and keeps on changing unlike the others. Any Ideas? Everything else works good. Though I'm parsing this data through MySQL database, this is how the JavaScript looks like.
My code:
<script>
var myData = ["12","15","7","20","2","22","10","7","7","10","8","15","9"];
var myData = myData.map(parseFloat);
var myLabels = ["General Verbal Insults","General Beatings\/Pushing","Terrorizing\/Threatening Remarks","False Gossip Inflation (Rumors)","Discrimination","Rough Fighting","Sexual Utterance\/Assaults","General Exclusion","Theft","Racist Utterance\/Assaults","Personal Property Damage","Internet Related (Cyber)","Other\/Unspecified"];
window.onload=function(){
var colorCharacters = "ACDEF0123456789";
var globalStylesArray = [];
var myConfig = {
type: "bar",
legend:{},
title: {
"text":"Showing Results For: Canada",
"color":"green"
},
subtitle: {
"text":"Total Bullying Incidents In Country: 144",
"color":"blue"
},
series : [{"values":[ myData[0] ],"text":"General Verbal Insults",},{"values":[ myData[1] ],"text":"General Beatings/Pushing",},{"values":[ myData[2] ],"text":"Terrorizing/Threatening Remarks",},{"values":[ myData[3] ],"text":"False Gossip Inflation (Rumors)",},{"values":[ myData[4] ],"text":"Discrimination",},{"values":[ myData[5] ],"text":"Rough Fighting",},{"values":[ myData[6] ],"text":"Sexual Utterance/Assaults",},{"values":[ myData[7] ],"text":"General Exclusion",},{"values":[ myData[8] ],"text":"Theft",},{"values":[ myData[9] ],"text":"Racist Utterance/Assaults",},{"values":[ myData[10] ],"text":"Personal Property Damage",},{"values":[ myData[11] ],"text":"Internet Related (Cyber)",},{"values":[ myData[12] ],"text":"Other/Unspecified",}]
};
zingchart.render({
id : 'myChart',
data : myConfig,
width:"100%",
height:500,
});
zingchart.gload = function(p) {
console.log(p);
var graphId = p.id;
var graphData = {};
graphData = zingchart.exec(graphId, 'getdata');
graphData = graphData.graphset[0] ? graphData.graphset[0] : graphData;
console.log(graphData);
createColors(graphData.series[0].values.length);
zingchart.exec(graphId, 'modifyplot', {
data: {
styles: globalStylesArray
}
});
}
function createColors(seriesLength) {
console.log('-------createColor seriesLength: ', seriesLength);
globalStylesArray = [];
for (var i = 0; i < seriesLength; i++) {
var colorString = '#';
for (var j = 0; j < 6; j++) {
colorString += colorCharacters.charAt(Math.floor(Math.random() * (colorCharacters.length - 4)));
}
globalStylesArray.push(colorString);
}
console.log('-----globalStylesArray-------', globalStylesArray);
}
};
</script>
Referring to the comment on the OP:
I just want all color to be different, since i dont know how many elements are in MyData - its generated through PHP & MYSQL
If you just want all of the colors to be different, remove the zingchart.gload function and the createColors function. ZingChart will create different colors for each series dynamically.
If you do want to specify each of those colors ahead of time since you do not know how many series your data will produce, you will need to apply a theme to your chart configuration: http://www.zingchart.com/docs/design-and-styling/javascript-chart-themes/

How to assign javascript variable to amcharts dataloader?

I need to assign a javascript variable to amcharts dataloader. but following code does not work (Graph does not draw)
AmCharts.ready(function () {
var data = [{"employee_no": "101","Salary": "1000"},{"employee_no": "102","Salary": "1500"},{"employee_no": "103","Salary": "1100"},{"employee_no": "104","Salary": "1900"},{"employee_no": "105","Salary": "1200"},
{"employee_no": "106","Salary": "1800"},{"employee_no": "107","Salary": "2000"},{"employee_no": "108","Salary": "1500"}];
var chart = new AmCharts.AmSerialChart();
chart.dataLoader = data;
chart.categoryField = "employee_no";
var graph = new AmCharts.AmGraph();
graph.valueField = "Salary";
graph.type = "line";
graph.bullet = "round";
graph.lineColor = "#8d1cc6";
chart.addGraph(graph);
chart.write('chartdiv');
});
but if I use below code it works fine.
chart.dataLoader = {
url: "MY_URL",
postProcess: function (data, options) {
if (data === null) {
data = [];
options.chart.addLabel("50%", "50%", "No Data Available");
}
return data;
}
};
What is the error of above code ? I cannot figure it out.
Thanks you
Thank you martynasma, You are right
I have to use chart.dataProvider instead of chart.dataLoader
That solved my problem. We have to use chart.dataLoader only with http request.

Need to make the following code dynamic

I am generating a highchart using json that is created by PHP. Everything is working perfectly fine. However I can't figure out how do I make the series dynamic in the following code? :
$.getJSON("myFile.php", function(json) {
options.xAxis.categories = json[0]['data'];
options.series[0] = json[1];
options.series[1] = json[2];
chart = new Highcharts.Chart(options);
});
In the above code, there are only 2 series. However I do not know how many series will be present as they will change according to user request. Can someone please tell me how to make this part dynamic:
options.series[0] = json[1];
options.series[1] = json[2];
Thanks in advance :)
$.each(json, function( index, value ) {
options.series[index-1] = value;
});
Be careful to start your json to 1 if you want series from 0 to n
Try this
$.getJSON("myFile.php", function(json) {
options.xAxis.categories = json[0]['data'];
for (var i = 0; i < options.series.length; i++) {
options.series[i] = json[i + 1];
}
chart = new Highcharts.Chart(options);
});

Categories