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
}]
});
} ;
Related
I have plotted a stacked bar chart for 4 data values that I have for every U.S. state. The CSV file I have been working off of looks like this:
Here's the JS code I wrote for the stacked bar chart:
// Read the data from CSV
d3.csv('https://raw.githubusercontent.com/krithikaragha/ResPy/master/Flask%20App/static/data/tobacco_use_by_state.csv', function(data) {
var chartData = []; // Array containing all the traces
function makeTrace(d) { // Function to make all 50 traces
return {
x: ["Smokes Everyday", "Smokes Somedays", "Former Smoker", "Never Smoked"],
y: [d.smokesEveryday, d.smokesSomedays, d.formerSmoker, d.neverSmoked],
name: d.state,
type: 'bar'
}
}
// Loop through all rows of the data
for(var i = 0; i < data.length; i++) {
// Call makeTrace to create a trace with index i
chartData.push(makeTrace(data[i]));
// Define a chart layout
var layout = {
barmode: 'stack',
width: 1200,
height: 800
};
// Plot the stacked bar chart
Plotly.newPlot('bar', chartData, layout);
}
});
The resulting stacked bar chart ended up looking like this:
The result I want to achieve is: I want each U.S. state to have its own bar which is stacked with respective 4 values (smokesEveryday, smokesSomedays, formerSmoker and neverSmoked)
Is there any way I can achieve this? Thanks in advance.
I figured it out myself.
Turns out, I had to make four separate traces for each of the 4 values I needed. So I looped through the data and created arrays for each column - smokedEveryday, smokesSomedays, formerSmoker and neverSmoked and a last array states to hold the state's abbreviations.
Then I created 4 individual traces with x-axis holding the states array and y-axis holding the respective smoking array.
Here's the modified code snippet:
// Read the data from CSV
d3.csv('https://raw.githubusercontent.com/krithikaragha/ResPy/master/Flask%20App/static/data/tobacco_use_by_state.csv', function(data) {
var states = [];
var smokesEveryday = [];
var smokesSomedays = [];
var formerSmoker = [];
var neverSmoked = [];
// Loop through all rows of the data
for(var i = 0; i < data.length; i++) {
states.push(data[i].abbr);
smokesEveryday.push(data[i].smokesEveryday);
smokesSomedays.push(data[i].smokesSomedays);
formerSmoker.push(data[i].formerSmoker);
neverSmoked.push(data[i].neverSmoked);
}
var smokesEverydayTrace = {
x: states,
y: smokesEveryday,
name: 'Smokes Everyday',
type: 'bar'
};
var smokesSomedaysTrace = {
x: states,
y: smokesSomedays,
name: 'Smokes Somedays',
type: 'bar'
};
var formerSmokerTrace = {
x: states,
y: formerSmoker,
name: 'Former Smoker',
type: 'bar'
};
var neverSmokedTrace = {
x: states,
y: neverSmoked,
name: 'Never Smoked',
type: 'bar'
};
var data = [neverSmokedTrace, formerSmokerTrace, smokesSomedaysTrace, smokesEverydayTrace];
var layout = {
barmode: 'stack',
title: "Percentage of Tobacoo Use by State",
xaxis: {
title: {
text: "Tobacco Use"
},
tickangle: 45
},
yaxis: {
title: {
text: "Percentage"
}
},
bargap: 0.4,
width: 1250,
height: 800
};
Plotly.newPlot('bar', data, layout);
});
Right now I have a simple column chart with following code using Highcharts:
$(document).ready(function() {
var options = {
chart: {
renderTo: 'container',
type: 'column'
},
title: {
//some code
},
xAxis: {
categories: []
},
yAxis: {
//some code
},
plotOptions: {
series: {
borderWidth: 0,
dataLabels: {
enabled: true,
format: '{point.y}'
}
}
},
legend: {
//some code
},
series: []
};
$.getJSON("data/column.php", function(json) {
options.xAxis.categories = json[0]['data'];
options.series[0] = json[1];
chart = new Highcharts.Chart(options);
});
});
I now want to add a line chart to the same container, using exactly the same options (despite of the chart type). The date is also served via JSON.
How can I achieve this?
What I did so far:
I created a second variable "options2" with values chart and series.
Then I called
$.getJSON("data/line.php", function(json) {
options.xAxis.categories = json[0]['data'];
options2.series[1] = json[1];
chart = new Highcharts.Chart(options2);
});
But that only shows the first column chart.
Probably you should try use $.merge to prevent object edition.
Try this
$.getJSON("data/column.php", function(json) {
// Merge objects
var newOptions = $.extend({}, options);
// Edit new object instead of old
newOptions.xAxis.categories = json[0]['data'];
newOptions.series[0] = json[1];
chart = new Highcharts.Chart( newOptions );
});
Solved it by passing the series option (chart type) directly via JSON.
I added the "type:line" to the data array, which then overrides previously set options within the script tag.
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
I'm trying to show a Chart with Highcharts, using javascript.
I've read the csv file using Highcharts modules/data.js and the Chart is showing without problems inside my container.
mychart = Highcharts.chart('container', {
chart: {
type: 'scatter',
zoomType: 'xy'
},
data: {
csv: csv,
startColumn:0,
endColumn:2
},
title: {
text: 'DATA'
},
xAxis: {
title: {
text: 'X'
},
},
yAxis: {
title: {
text: 'Y'
}
}
});
Basically the csv have 3 columns, with commas separating attributes and break lines for each row.
x, y, category
data1, data2, data3
data1, data2, data3
data1, data2, data3
data1, data2, data3
data1, data2, data3
...
The first and the seconds columns are the points coordinates and the third is the category. I want to display points based on one of the categories in the third row.
I don't know how to show all x & y points categorized by category column.
You can think of a category as a series in Highcharts. So you need to create an array like this
series: [{
name: 'Series ' + categoryNumber,
data: [] // array with x and y coordinates
}, {
name: ''
data: []
}]
Then you can parse your csv file, it would be easier without data module.
var rows = csv.split('\n');
var series = [];
rows.forEach(row => {
var cells = row.split(',').map(Number);
var serie = series[cells[2]];
if (!serie) {
serie = series[cells[2]] = {data: []};
}
serie.data.push([cells[0], cells[1]]);
})
Highcharts.chart('container', {
chart: {
type: 'scatter'
},
series: series
});
example: http://jsfiddle.net/w7ug4dbw/
There is important for the chart series that you will not have gaps in your category - so if you have categories 0 - 2, you need to have data for all 0,1,2 category - if you don't, then you can receive the errors while using the chart. To overcome that, you would need to loop through the series array and delete all the gaps.
I am trying to create a highchart line graph using data from a .csv file. But my webpage is just showing the titles of x and y axis, but no data. The code is as follows:
$(document).ready(function() {
var c = [];
var d = [];
$.get('data.csv', function(data) {
alert("data in the file: " + data);
var lines = data.split('\n');
$.each(lines, function(lineNo, line) {
var items = line.split(',');
c.push(items[0]);
d.push(parseInt(items[1]));
});
});
var options = {
chart: {
renderTo: 'chart',
defaultSeriesType: 'line'
},
title: {
text: 'Weight Monitor'
},
xAxis: {
title: {
text: 'Date Measured'
},
categories: c
},
yAxis: {
title: {
text: 'Weight (in Lbs)'
}
},
series: [{
data: d
}]
};
var chart = new Highcharts.Chart(options);
});
i tried to print the data read from file on screen just to check if the file was read properly and i got the proper data, but still my graph is not showing anything.
following is the data in my csv file:
2011-08-01 00:00:00,155
2011-08-02 00:00:00,156
2011-08-03 00:00:00,157
2011-08-03 00:00:00,160
where left value is date to be shown in x axis and right value is reading points for graph.
any help will be thankful.
Your code works perfect.
<script type="text/javascript">
$(document).ready(function() {
var c = [];
var d = [];
$.get('data.csv', function(data) {
var lines = data.split('\n');
$.each(lines, function(lineNo, line) {
var items = line.split(',');
c.push(items[0]);
d.push(parseInt(items[1]));
});
});
var options = {
chart: {
renderTo: 'chart',
defaultSeriesType: 'line'
},
title: {
text: 'reading'
},
xAxis: {
title: {
text: 'Date Measurement'
},
categories: c
},
yAxis: {
title: {
text: 'reading'
}
},
series: [{
data: d
}]
};
var chart = new Highcharts.Chart(options);
});
</script>
Copy this whole code and save it as .html file in a directory and create the data.csv file in the same directory and make sure that there no empty lines, no spaces where they are not needed and no line-break at the end.
And then open the .html file, the chart should show up with the right data.
Add the chart within $.get.
Note that we can't create the chart outside the Ajax callback, as we have to wait for the data to be returned from the server. See this.
$.get('data.csv', function(data) {
var lines = data.split('\n');
$.each(lines, function(lineNo, line) {
var items = line.split(',');
c.push(items[0]);
d.push(parseInt(items[1]));
});
var chart = new Highcharts.Chart(options);
},'Text');
Also mention explicitly the data return type to "Text" which might be a problem some time.
You must read the documentation properly. See http://www.highcharts.com/documentation/how-to-use#preprocessing
They already have a demo of the csv http://highcharts.com/studies/data-from-csv.htm .
Please go through the docs and familiarise yourself ! .