Duplicated Series of Data in Google Area Chart - javascript

I'm trying to plot a Chart using Google's Visualization API using some data returned from a database by a PHP script. My data is a JSON object in the format:
jsonObject = {
"routes":[{
"name":"Route 0",
"chart":{
"x":[ /* array of x values */ ],
"y":[ /* array of y values */ ]
}
},{
"name":"Route 1",
"chart":{
"x":[ /* array of x values */ ],
"y":[ /* array of y values */ ]
}
}]};
I'm trying to plot a chart of each member of jsonObject.routes individually using the following code:
function drawChart() {
var baseChart = jsonObject.routes[1].chart; // Want to manipulate this value to plot different sets of data
var chartData = [];
for (var g = 0; g < baseChart.x.length; g++) {
var dataPoint = {
c: [
{ v: baseChart.x[g] },
{ v: baseChart.y[g] },
]
};
chartData.push(dataPoint);
}
var dataJson = {
cols: [
{ role: "domain", type: "number", label: "Distance" },
{ role: "data", type: "number", label: "Main Route" },
],
rows: chartData
};
var dataTable = new google.visualization.DataTable(dataJson);
var chart = new google.visualization.AreaChart(document.getElementById('chart'));
var options = {};
chart.draw(dataTable, options);
}
However, whenever I try to access the latter objects of the jsonObject.route array, it seems to be pulling data for every object in the jsonObject.route array prior to it as well.
I've included a link to a Fiddle with a sample dataset at the bottom; the chart is fine when only plotting jsonObject.routes[0], but when trying to plot jsonObject.routes[1] it will plot the data from jsonObject.routes[0] too.
I suspect this is more of an issue with my Javascript code rather than with the Google Visualization API, but I've been pulling my hair out with it and can figure out why it's pulling data from all the elements in that array. Many thanks for any help!
Link to Fiddle

not sure i completely follow the question...
looking at the fiddle, the one chart seems to draw fine,
just need to sort the data to fix funny looking area
dataTable.sort([{column: 0}]);
see following snippet in order to draw separate charts for each --> jsonObject.routes
google.charts.load('current', {
callback: function () {
jsonObject.routes.forEach(function (route) {
var chartData = [];
route.chart.dist.forEach(function (x, index) {
chartData.push({
c: [
{v: x},
{v: route.chart.ele[index]}
]
});
});
var dataJson = {
cols: [
{ role: "domain", type: "number", label: "Distance" },
{ role: "data", type: "number", label: "Main Route" },
],
rows: chartData
};
var dataTable = new google.visualization.DataTable(dataJson);
dataTable.sort([{column: 0}]);
var options = {};
var container = document.getElementById('chart_div').appendChild(document.createElement('div'));
var chart = new google.visualization.AreaChart(container);
chart.draw(dataTable, options);
});
},
packages:['corechart']
});
note: definition of jsonObject is excluded above
AND
when building a working fiddle, i noticed that since jsonObject is so large,
once you leave the page and comeback,
the fiddle breaks it up into chunks, which then breaks the code
and only one chart is drawn
here is a working fiddle with far less data

Related

How to update a echart with a js function and 2D array

Good morning.
I need to do the following: Update a stacked line chart using a function in javascript that takes a 2d array ([[0,1],[0,2],...]).
My page is running in a Java fx webview so I can dynamically update my data. All the examples I've seen so far create a predefined X axis and pass the y values ​​accordingly, I wanted to pass the two values ​​together to plot a line on the chart.
How could I make this function? It's the first time I use echarts so I'm lost.
I even managed to do something similar but when plotting the chart it was all wrong.
Char Image
var option = {
xAxis: {
type: "value",
},
yAxis: {
type: "value",
},
series: [
{
type: "line",
data: [],
},
],
};
vibrationStackedLineChart.setOption(option);
function updateEchart(dataArray) {
// Parse the JSON string back into a 2D int array
var data = JSON.parse("[" + dataArray + "]");
// Update the chart with the new data
vibrationStackedLineChart.setOption({
series: [
{
data: data,
},
],
});
}
Java function with array 2d

Chartjs bar chart appears empty when page loads

I am using the ChartJS library to display a bar chart on my HTML page. The issue I am facing is when the page loads, it displays an empty bar chart without the data I have passed into it and without rendering the bars. After one click to the legend, the chart resizes and my labels appear on the x-axis, on the second click the bars are rendered and the y-axis populates to my passed in data. I am not sure why the chart is behaving this way.
I tested the chart with the code provided in the chart.js documentation and it appears instantly. I think the issue has to do with how I am calling my express backend to retrieve data from my endpoint.
Not sure how to resolve this issue. Any help is appreciated.
index.html:
<canvas
id="patents-per-category-bar-chart"
width="400"
height="400"
></canvas>
<script type="text/javascript">
var categoryLabels = [];
var categoryValues = [];
var centerLabels = [];
var centerValues = [];
$.getJSON("http://localhost:5000/api").done((data) => {
for (let item in data.patentsPerCategory) {
if (!data.patentsPerCategory.hasOwnProperty(item)) {
continue;
}
categoryLabels.push(item);
categoryValues.push(data.patentsPerCategory[item]);
}
for (let item in data.patentsPerCenter) {
if (!data.patentsPerCenter.hasOwnProperty(item)) {
continue;
}
centerLabels.push(item);
centerValues.push(data.patentsPerCenter[item]);
}
});
var ctx = document
.getElementById("patents-per-category-bar-chart")
.getContext("2d");
var barChartConfig = {
type: "bar",
data: {
labels: categoryLabels,
datasets: [
{
backgroundColor: "blue",
label: "# Patents Per Category",
data: categoryValues,
},
],
},
options: {
legend: {
onClick: null,
},
responsive: true,
scales: {
yAxes: [
{
ticks: {
beginAtZero: true,
},
},
],
},
},
};
var categoryBarChart = new Chart(ctx, barChartConfig);
</script>
mock data returned from the api:
{
"category": {
"health medicine and biotechnology": 37,
"instrumentation": 38,
"storage": 30,
"systems": 71,
"aeronautics": 1,
"electronics": 47,
"optics": 60,
"materials": 119,
"undefined": 3,
"communications": 32,
"sensors": 102,
"robotics": 37,
"software": 49,
"propulsion": 9,
"manufacturing": 40,
"environment": 24,
"aerospace": 79
}
}
After returning this data from the api, I iterate over it and push the keys and values into separate arrays which are categoryLabels, categoryValues. Then pass these arrays directly into the labels and data for the chart
Created a jsFiddle:
https://jsfiddle.net/tkdamxr5/2/
It works fine in the jsFiddle enviornment so the issue must be in the way I am calling my data using jQuery. Can anyone clarify how I need to call my express backend to get the data and pass it into the chart so it works correctly?
Figured it out. In my original code I was using
$.getJSON('http://localhost:5000/api').done((data) => {}
to call my expressjs backend.
I changed it to use
$.ajax({
url: "http://localhost:5000/api",
success: function (result) {
let labels = [];
let data = [];
for (let item in result.category) {
if (!result.category.hasOwnProperty(item)) {
continue;
}
labels.push(item);
data.push(result.category[item]);
}
},
error: function(err) { console.log(err); }
})
and was able to display my bar chart successfully and as expected.

how to solve Highcharts error #15?

Hello friends I'm trying to draw the chart using javascript function the data comes into JSON array format like
[[1432116687000,5100],[1432116991000,5100],[1432117291000,5100],[1432117591000,5100],[1432117894000,5100],[1432118199000,5100],[1432118499000,5100],[1432118800000,5100],[1432119100000,5100],[1432119404000,5100],[1432119648000,5100],[1432119950000,5100],[1432120250000,5100],[1432120550000,5100],[1432120850000,5100],[1432121154000,5100],[1432121154000,5100]]
But I'm getting an error
Highcharts Error #15
Highcharts expects data to be sorted
This happens when you are trying to create a line series or a stock chart where the data is not sorted in ascending X order. For performance reasons, Highcharts does not sort the data, instead it is required that the implementer pre-sorts the data.
please help me to fix it
function drawChart(data){
console.log(data);
var date = [];
var ttc = [];
var series = [];
for(var i=0; i<data.length; i++){
//date.push(data[i][0]);
//console.log(date);
//ttc.push(parseInt(data[i][1]));
//console.log(ttc);
series.push([data[i][0],parseInt(data[i][1])]);
}
//console.log(data[i][1]);
//var series = (series);
$('#container').highcharts('StockChart', {
rangeSelector: {
selected: 1
},
title: {
text: 'Area Per TCC'
},
yAxis: {
title: {
text: 'TTC'
}
},
series: [{
name: 'TCC',
data: series
}]
});
} ;

How can I use 'timeofday' data type in a Google Charts Histogram?

I'm trying to create a histogram using Google's timeofday data type, but keep getting the error "Invalid Row Index NaN. Should be in the range [0-0]." when the chart loads. If I use number as the data type and change the arrays to integers it works, but that won't let me format as HH:MM:SS. Something tells me that timeofday might not be supported for a histogram, but I can't find anything in the docs to support that. Any thoughts on what I might be doing wrong?
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);
function drawChart() {
var jsonData = {
cols: [
{
type: 'timeofday',
label: 'Clock-in'
}
],
rows: [
{ c: [{v: [8, 15, 0]}] },
{ c: [{v: [8, 30, 0]}] },
{ c: [{v: [8, 45, 0]}] }
]
};
var data = new google.visualization.DataTable(jsonData);
var options = {
title: 'Clock-in times',
legend: { position: 'none' }
};
var chart = new google.visualization.Histogram(document.getElementById('chart_div'));
chart.draw(data, options);
};
This is a bug in the Google histogram implementation (issue #2025).
In the meantime, the only way to get a histogram of timeofday values will be to put things into bins on the server side and render a bar chart.

Flot line graph and a large JSON data blob not formatted to Flot API specs

I'm using Flot to plot a line graph and my data set is a rather large JSON blob array that looks something like (truncated for brevity purposes):
[{"load_data": 5047, "url": "http://this.com", "timestamp": "2010-12-03 17:06:45", "formatted_timestamp": 1291396005000, "load_time": 4359},
{"load_data": 8658, "url": "https://that.com", "timestamp": "2010-12-03 17:06:24", "formatted_timestamp": 1291395984000, "load_time": 7516},
{"load_data": 7372, "url": "https://theother.com, "timestamp": "2010-12-03 17:06:22", "formatted_timestamp": 1291395982000, "load_time": 7372}]
So Flot according to their example in the API doc likes their JSON formatted like:
{
label: "y = 3",
data: [[0, 3], [10, 3]]
}
Where they want the data into tuples to plot against the x,y axis which is understandable.
My question is how would I parse through the forementioned JSON blob to get "formatted_timestamp" to represent the x axis and then "load_data" to represent the y? Meaning create a series similar to the FLOT json structure and the series of values into the graph?
This function would do the trick when given an array like you described:
function format(source) {
var i, l,
dest = [],
row;
for(i = 0, l = source.length; i < l; i++) {
row = source[i];
dest.push([row.formatted_timestamp, row.load_data]);
}
return dest;
}
Not sure whether I got the question correctly, but this is how I create a flot x-y graph:
data:[[1, 0],[2, 0] .... ] -> 1 and 2 are the values of the x axis..
<script language="javascript" type="text/javascript">
$(function () {
var data = [{label:'my funky label',data:[[1, 0],[2, 0],[3, 0],[4, 0],[5, 18.125],[6, 20.625],[7, 15.4375],[8, 18.5625],[9, 22.375],[10, 13.5625],[11, 20.1875],[12, 5.5]]}];
var options = {
legend: {
show: true,
margin: 10,
backgroundOpacity: 0.5
},
points: {
show: true,
radius: 4
},
lines: {
show: true
},
grid: { hoverable: true, clickable: true , color: "#999"}
};
var plotarea = $("#plotarea");
plotarea.css("height", "450px");
plotarea.css("width", "600px");
$.plot( plotarea , data, options );
});
</script>

Categories

Resources