jQuery.ajax and Rickshaw - Callback functions? - javascript

I wrote the following code. I have a json file on my server that is valid and looks like:
[
{
"data": [
{
"y": 1.0,
"x": 1451936340.0
},
{
"y": 1.0,
"x": 1451936400.0
},
{
"y": 1.0,
"x": 1451936460.0
}
]
}
]
I have the following code. I am trying to draw a line chart and overlay points on the line chart using renderer: 'multi' but I am hitting a lot of snags. I am a novice with JS and I do not understand where I am messing up. I think I need a callback function in my jQuery.ajax function but I am unsure. I appreciate any help.
<html>
<head>
<!-- css -->
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/rickshaw/1.5.1/rickshaw.min.css">
<!-- js -->
<script src="https://code.jquery.com/jquery-1.11.3.min.js"></script>
<script src="https://code.jquery.com/ui/1.11.4/jquery-ui.min.js"></script>
<script>
jQuery.noConflict();
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.10/d3.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/rickshaw/1.5.1/rickshaw.min.js"></script>
</head>
<body>
<div style="margin:10px auto;width:auto;" id="chart_container">
<div id="chart"></div>
<div id="slider"></div>
<script>
var json = jQuery.ajax({
'url': "/assets/json/data.json",
'success': function(json) {
console.log(json[0].data);
}
});
var graph = new Rickshaw.Graph( {
element: document.getElementById("chart"),
renderer: 'multi',
height: 200,
width: 400,
series: [
{
name: "series 1",
data: json[0].data,
color: "rgba(255, 0, 0, 0.4)",
renderer: "line"
}, {
name: "series 2",
data: json[0].data,
color: "rgba(255, 0, 0, 0.4)",
renderer: "scatterplot"
}
]
} );
graph.render();
var slider = new Rickshaw.Graph.RangeSlider.Preview( {
graph: graph,
element: document.querySelector('#slider')
} );
var detail = new Rickshaw.Graph.HoverDetail( {
graph: graph
} );
graph.render();
</script>
</div>
</body>

There are a few things I would change here.
1.) jQuery.ajax returns a promise, not the raw data itself, so var json = jQuery.ajax(...) will not assign the json value you are expecting.
2.) pass a success callback function to properly access the JSON returned by the server
3.) Only call graph.render() once.
Javascript
jQuery.ajax({
'url': "/assets/json/data.json",
'success': renderGraph // callback for ajax success
});
// wrap graph creation logic in a function to be used as a callback
function renderGraph(json) {
var graph = new Rickshaw.Graph({
element: document.getElementById("chart"),
renderer: 'multi',
height: 200,
width: 400,
series: [{
name: "series 1",
data: json[0].data,
color: "rgba(255, 0, 0, 0.4)",
renderer: "line"
}, {
name: "series 2",
data: json[0].data,
color: "rgba(255, 0, 0, 0.4)",
renderer: "scatterplot"
}]
});
// remove this, only render once at the end
// graph.render();
var slider = new Rickshaw.Graph.RangeSlider.Preview({
graph: graph,
element: document.querySelector('#slider')
});
var detail = new Rickshaw.Graph.HoverDetail({
graph: graph
});
graph.render();
}

Related

Plotting data using highcharts piechart in flask web application

I am trying to plot pandas dataframe from a python function and display it on a web server using Highcharts pie chart. I can get the data from the function to the web server as json data through flask. but when I want to display it the chart is empty. Through the web console I also made sure that the data format going into the Highcharts is correct but still nothing.
Here I am retrieving the panda dataframe and sending it to the web server through flask:
actype_json = actype.to_json(orient = 'records')
#app.route('/data/airport', methods = ['GET'])
def broadcast_data():
return eval(json.dumps(actype_json))
#app.route('/')
def plotgraph():
return render_template('airport.html')
On my HTML file, I tried to use AJAX to call for the data and plot it in a Highcharts Pie Chart:
<!DOCTYPE html>
<html>
<head>
<script src="https://code.highcharts.com/highcharts.js"></script>
<script src="https://code.highcharts.com/modules/exporting.js"></script>
<script src="https://code.highcharts.com/modules/export-data.js"></script>
<script
src="https://code.jquery.com/jquery-3.3.1.js"
integrity="sha256-2Kok7MbOyxpgUVvAk/HJ2jigOSYS2auK4Pfzbm7uH60="
crossorigin="anonymous">
</script>
</head>
<body>
<div id="container" style="min-width: 310px; height: 400px; max-width: 600px; margin: 0 auto"></div>
<script>
function GetUpdatedData(){
$.ajax({
url: "/data/airport",
})
.done(function( data ) {
console.log( data );
DrawGraph(data);
});
}
function DrawGraph(dataset) {
// Radialize the colors
Highcharts.setOptions({
colors: Highcharts.map(Highcharts.getOptions().colors, function (color) {
return {
radialGradient: {
cx: 0.5,
cy: 0.3,
r: 0.7
},
stops: [
[0, color],
[1, Highcharts.Color(color).brighten(-0.3).get('rgb')] // darken
]
};
})
});
// Build the chart
Highcharts.chart('container', {
chart: {
plotBackgroundColor: null,
plotBorderWidth: null,
plotShadow: false,
type: 'pie'
},
title: {
text: 'Browser market shares in January, 2018'
},
tooltip: {
pointFormat: '{series.name}: <b>{point.percentage:.1f}%</b>'
},
plotOptions: {
pie: {
allowPointSelect: true,
cursor: 'pointer',
dataLabels: {
enabled: true,
format: '<b>{point.name}</b>: {point.percentage:.1f} %',
style: {
color: (Highcharts.theme && Highcharts.theme.contrastTextColor) || 'black'
},
connectorColor: 'silver'
}
}
},
series: [{
name: 'Aircraft',
data: [dataset]
}]
});
setTimeout(GetUpdatedData, 1500);
}
</script>
</body>
</html>
This is the screenshot of the Highcharts Pie Chart that I am seeing:
The response tab is showing the format of the data trying to be plotted on Highchart. Any advice will be very helpful. Thanks!
You've made a simple mistake when adding data to series.data array. Note that your data is actually a correct Highcharts data array with point objects inside:
data:
[{
"AC TYPE": "B773",
"y": 35
}, {
"AC TYPE": "B77W",
"y": 16
}]
However, you've added this array inside another one like that:
series: [{
name: 'Aircraft',
data: [dataset]
}]
This gives you an invalid data format with two nested arrays:
series: [{
name: 'Aircraft',
data: [[{
"AC TYPE": "B773",
"y": 35
}, {
"AC TYPE": "B77W",
"y": 16
}]]
}]
Remove the wrapping array and the chart should be rendered correctly.
Demo:
https://jsfiddle.net/BlackLabel/49rhpmyg/

How to load donut chart data from angular scope object

This is my code format:How can I load data from angular scope object.
static data is working fine.But getting from scope object is displays nothing.
var app=angular.module('myApp',[])
app.controller('myController',function($scope){
$scope.init = function(){
$scope.loadData()
var ctx = document.getElementById('mycanvas').getContext('2d');
var chart = new Chart(ctx, {
type: 'doughnut',
data: {
labels: ["EL", "AL", "PL", "CL"],
datasets: [{
backgroundColor: ['green', 'red', 'pink', 'blue'],
data: $scope.datas,
}]
},
options: {
legend: {
position: 'right',
labels: {
boxWidth: 12
}
},
tooltips: { bodyFontSize: 12 }
}
});
}
$scope.loadData = function(){
$scope.datas=[
{
'EL':2
},
{
'AL':2
},
{
'PL':2
},
{
'CL':2
}
]
}
})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/1.0.2/Chart.min.js"></script>
<div ng-app="myApp" ng-controller="myController" ng-init="init()">
<canvas id="mycanvas"></canvas>
</div>
How can I load data from angular scope object for chart.
You almost did it right!
The point here is your data format.
You can't pass objects like this.
$scope.requestedLeaveTypeCount=[{'EL': 2}, {'AL': 2}, {'PL': 2}, {'CL': 2}];
This kind of data format is working.
$scope.requestedLeaveTypeCount=[2,2,2,2]
DEMO

import json file to create a network in vis.js

I am using vis.js to create a mapping, I using file saveAndLoad.html in the example code. The save function is good, I can export json file. But when I load the json file in import function it doesn't create a mapping for me. I don't know what is my misunderstanding please help. this is the import function.
function importNetwork() {
/*var inputValue = exportArea.value;
var inputData = JSON.parse(inputValue);
var data = {
nodes: getNodeData(inputData),
edges: getEdgeData(inputData)
}
network = new vis.Network(container, data, {});*/
var gephiJSON = loadJSON("./1.json"); // code in importing_from_gephi.
// you can customize the result like with these options. These are explained below.
// These are the default options.
var parserOptions = {
edges: {
inheritColors: false
},
nodes: {
fixed: true,
parseColor: false
}
}
// parse the gephi file to receive an object
// containing nodes and edges in vis format.
var parsed = vis.network.convertGephi(gephiJSON, parserOptions);
// provide data in the normal fashion
var data = {
nodes: parsed.nodes,
edged: parsed.edges
};
// create a network
var network = new vis.Network(container, data);
resizeExportArea();
}
I searched quite a bit for a solution to the obstensively simple task of loading an external JSON datafile into a vis.js Network. Here is a working solution.
Read my comments in the HTML file (below), for more information:
I installed vis.js via NPM, but you can also just download / source the vis.min.js file;
The code provided by visjs.org in the "full options" tab for the Network module edge options was buggy, due to extra commas, etc. I included a working copy in my HTML code (ditto re: the "physics" options).
As noted in the comments in my HTML file, the formatting of the JSON datafile is very particular: use double quotation marks; curly braces { } are not quoted (e.g., if you want to define per-edge attributes, in that file); ....
json_test.html
<!doctype html>
<HTML>
<HEAD>
<meta charset="utf-8" />
<TITLE>[vis.js] Network | Basic Usage | TEST: Load External JSON Datafile</TITLE>
<!-- NPM (http://visjs.org/index.html#download_install): -->
<!-- <script type="text/javascript" src="node_modules/vis/dist/vis.min.js"></script> -->
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/vis/4.21.0/vis.min.js"></script>
<!-- Needed for JSON file import (https://stackoverflow.com/questions/33392557/vis-js-simple-example-edges-do-not-show): -->
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<!-- http://visjs.org/index.html#download_install -->
<!-- <link rel="stylesheet" type="text/css" href="node_modules/vis/dist/vis.css"> -->
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/vis/4.21.0/vis.min.css">
<style type="text/css">
#mynetwork {
/* width: 600px; */
width: 100%;
height: 800px;
border: 2px solid lightgray;
}
</style>
</HEAD>
<BODY>
<div id="mynetwork"></div>
<!-- Add an invisible <div> element to the document, to hold the JSON data: -->
<div id="networkJSON-results" class="results" style="display:none"></div>
<script type="text/javascript">
// -------------------------------------------------------------------------
// OPTIONS:
// http://visjs.org/docs/network/#modules
// http://visjs.org/docs/network/edges.html#
// http://visjs.org/docs/network/physics.html#
var options = {
edges: {
arrows: {
to: {enabled: true, scaleFactor:0.75, type:'arrow'},
// to: {enabled: false, scaleFactor:0.5, type:'bar'},
middle: {enabled: false, scalefactor:1, type:'arrow'},
from: {enabled: true, scaleFactor:0.3, type:'arrow'}
// from: {enabled: false, scaleFactor:0.5, type:'arrow'}
},
arrowStrikethrough: true,
chosen: true,
color: {
// color:'#848484',
color:'red',
highlight:'#848484',
hover: '#848484',
inherit: 'from',
opacity:1.0
},
dashes: false,
font: {
color: '#343434',
size: 14, // px
face: 'arial',
background: 'none',
strokeWidth: 2, // px
strokeColor: '#ffffff',
align: 'horizontal',
multi: false,
vadjust: 0,
bold: {
color: '#343434',
size: 14, // px
face: 'arial',
vadjust: 0,
mod: 'bold'
},
ital: {
color: '#343434',
size: 14, // px
face: 'arial',
vadjust: 0,
mod: 'italic'
},
boldital: {
color: '#343434',
size: 14, // px
face: 'arial',
vadjust: 0,
mod: 'bold italic'
},
mono: {
color: '#343434',
size: 15, // px
face: 'courier new',
vadjust: 2,
mod: ''
}
}
},
// http://visjs.org/docs/network/physics.html#
physics: {
enabled: true,
barnesHut: {
gravitationalConstant: -2000,
centralGravity: 0.3,
// springLength: 95,
springLength: 175,
springConstant: 0.04,
damping: 0.09,
avoidOverlap: 0
},
forceAtlas2Based: {
gravitationalConstant: -50,
centralGravity: 0.01,
springConstant: 0.08,
springLength: 100,
damping: 0.4,
avoidOverlap: 0
},
repulsion: {
centralGravity: 0.2,
springLength: 200,
springConstant: 0.05,
nodeDistance: 100,
damping: 0.09
},
hierarchicalRepulsion: {
centralGravity: 0.0,
springLength: 100,
springConstant: 0.01,
nodeDistance: 120,
damping: 0.09
},
maxVelocity: 50,
minVelocity: 0.1,
solver: 'barnesHut',
stabilization: {
enabled: true,
iterations: 1000,
updateInterval: 100,
onlyDynamicEdges: false,
fit: true
},
timestep: 0.5,
adaptiveTimestep: true
},
};
// -------------------------------------------------------------------------
// IMPORT DATA FROM EXTERNAL JSON FILE:
// Per: https://github.com/ikwattro/blog/blob/master/sources/easy-graph-visualization-with-vis-dot-js.adoc:
// NOTES:
// 1. Must use double quotes ("; not ') in that JSON file;
// 2. Cannot have comments in that file, only data! See:
// https://stackoverflow.com/questions/244777/can-comments-be-used-in-json
// 3. Per the path below, place the "test.json" file in a "data" subdirectory.
var json = $.getJSON("data/test.json")
.done(function(data){
var data = {
nodes: data.nodes,
edges: data.edges
};
var network = new vis.Network(container, data, options);
});
var container = document.getElementById('mynetwork');
</script>
</BODY>
</HTML>
test.json
{"nodes":[
{"id":"1", "label":"Node 1"}
,{"id":"2", "label":"Node 2\nline 2"}
,{"id":"3", "label":"Node 3"}
,{"id":"4", "label":"Node 4"}
,{"id":"5", "label":"Node 5"}
],
"edges":[
{"from":"1", "to":"2", "label":"apples"}
,{"from":"1", "to":"3", "label":"bananas"}
,{"from":"2", "to":"4", "label":"cherries"}
,{"from":"2", "to":"5", "label":"dates"}
,{"from":"2", "to":"3", "label":"EAGLES!", "color":{"color":"green", "highlight":"blue"}, "arrows":{"to":{"scaleFactor":"1.25", "type":"circle"}}}
]
}
Output

i cant link local json file to the webpage

i am doing a school proget where i have to link a json data local file to a http webpage to get the data but i can't get the results.
the code below is the json local code which i want to put in the webpage instead of this code $.getJSON('https://www.highcharts.com/samples/data/jsonp.php?filename=activity.json&callback=?', function (activity)
?({
"xData": [0.001567,0.011765,0.022194,0.032316,0.04266,0.063668,0.074477,0.085323,0.09576,0.106078,0.116096,0.137524,0.148342,0.159059,0.170005,0.180716,0.191407,0.212538,0.222819,0.233929,0.244239,0.255301,0.266081,0.287527,0.298115,0.309392,0.320217,0.330928,0.341401,0.361717,0.372173,0.382337,0.39294,0.403072,0.413454,0.434618,0.444845,0.455745,0.465785,0.475987,0.486064,0.507086,0.517517,0.527961,0.538242,0.548414,0.558444,0.578941,0.589212,0.599472,0.60977,0.620178,0.630189,0.650782,0.661001,0.671137,0.681175,0.691235,0.702012,0.722644,0.733166,0.743824,0.754059,0.764109,0.774519,0.795597,0.805721,0.81592,0.826139,0.836369,0.846826,0.86771,0.87803,0.888342,0.898695,0.908723,0.91922,0.939802,0.950378,0.960776,0.971377,0.981843,0.992312,1.013125,1.023302,1.033488,1.043822,1.054203,1.065019,1.086078,1.09635,1.106421,1.117028,1.127541,1.138599,1.159588,1.170167,1.180741,1.190794,1.201112,1.211355,1.233278,1.243477,1.254957,1.265227,1.276378,1.285656,1.297311,1.308367,1.318715,1.329589,1.340834,1.352388,1.375063,1.385369,1.396291,1.408156,1.418989,1.429535,1.451141,1.462205,1.473011,1.483844,1.494311,1.514761,1.525336,1.535858,1.546476,1.557325,1.567512,1.590091,1.600925,1.612303,1.622558,1.633071,1.643555,1.66484,1.675722,1.685986,1.696733,1.706895,1.719102,1.741295,1.752144,1.762688,1.773713,1.784052,1.795705,1.817305,1.827465,1.838408,1.849369,1.860023,1.871438,1.89257,1.90323,1.914398,1.924634,1.934642,1.945212,1.966275,1.976294,1.986422,1.996652,2.008005,2.018309,2.041139,2.051221,2.0613,2.072507,2.08342,2.094075,2.114574,2.125286,2.135765,2.146845,2.157966,2.169391,2.190921,2.200899,2.212709,2.222671,2.232908,2.244001,2.264898,2.275703,2.286885,2.298115,2.310186,2.32059,2.344695,2.354843,2.366387,2.379001,2.390328,2.402215,2.423134,2.433156,2.444912,2.457061,2.468253,2.478978,2.499832,2.513223,2.52561,2.538429,2.548659,2.560809,2.581308,2.592816,2.603963,2.615992,2.626242,2.638223,2.660346,2.671583,2.681938,2.69265,2.70588,2.716296,2.740081,2.75085,2.761319,2.772027,2.782659,2.793531,2.816194,2.828031,2.839243,2.851443,2.863884,2.874359,2.895246,2.906506,2.91761,2.92786,2.938937,2.950218,2.973357,2.98366,2.994639,3.005213,3.01666,3.02761,3.050025,3.061713,3.071828,3.082787,3.093422,3.105289,3.127231,3.138982,3.149755,3.160217,3.171299,3.191571,3.202226,3.213225,3.223987,3.234092,3.244644,3.265939,3.276411,3.286489,3.297156,3.307909,3.319018,3.34064,3.351107,3.361683,3.373136,3.384768,3.395457,3.417722,3.429096,3.439122,3.449679,3.459868,3.469997,3.492679,3.503647,3.514941,3.525858,3.538746,3.550422,3.572255,3.58452,3.595367,3.605736,3.617401,3.628324,3.652523,3.663679,3.67378,3.684605,3.695595,3.705843,3.728706,3.739169,3.750205,3.761258,3.771771,3.781911,3.804724,3.81631,3.826313,3.837847,3.85049,3.860999,3.88262,3.892937,3.903053,3.913656,3.924698,3.935126,3.956362,3.966543,3.976899,3.98752,3.997644,4.008721,4.029852,4.040633,4.051006,4.06126,4.071761,4.083526,4.10749,4.117855,4.128661,4.13934,4.151117,4.1624,4.184736,4.194826,4.205098,4.215261,4.225325,4.236367,4.262012,4.273794,4.285743,4.297226,4.308086,4.318245,4.340246,4.351486,4.363196,4.374465,4.387109,4.398635,4.421101,4.432135,4.444666,4.456226,4.467413,4.477804,4.498505,4.510413,4.522595,4.534044,4.545944,4.558048,4.580379,4.59312,4.605616,4.618065,4.631266,4.644086,4.667943,4.67948,4.691266,4.703019,4.715923,4.725932,4.752312,4.765224,4.777128,4.787361,4.800435,4.823353,4.836044,4.848602,4.860302,4.871112,4.882779,4.904695,4.914823,4.927074,4.938111,4.949586,4.960761,4.982911,4.9942,5.004246,5.016296,5.027215,5.038043,5.058885,5.070303,5.080649,5.093865,5.104424,5.114903,5.134965,5.146346,5.15634,5.168547,5.179066,5.191167,5.214242,5.224914,5.237573,5.249537,5.261586,5.272517,5.296154,5.306348,5.316773,5.327153,5.339961,5.350638,5.376502,5.389277,5.402142,5.412197,5.42399,5.434873,5.458466,5.470907,5.482679,5.493339,5.50574,5.516349,5.538897,5.549552,5.56083,5.571879,5.583764,5.59509,5.619028,5.629925,5.640716,5.650957,5.661787,5.671957,5.693974,5.704919,5.717491,5.731152,5.744728,5.755687,5.778668,5.791951,5.80409,5.815697,5.828482,5.840501,5.864145,5.875704,5.887893,5.900147,5.912517,5.924894,5.948897,5.959155,5.970262,5.981632,5.992996,6.00356,6.027256,6.038776,6.050959,6.061351,6.071864,6.082436,6.104054,6.115602,6.127623,6.139058,6.150639,6.161323,6.183013,6.194359,6.206269,6.218033,6.2281,6.240494,6.262584,6.275326,6.287166,6.298953,6.310644,6.321583,6.345676,6.356738,6.366782,6.377931,6.388519,6.397159],
"datasets": [{
"name": "Speed",
"data": [10,20,30,40,50,60,70,80,90,100],
"unit": "km/h",
"type": "line",
"valueDecimals": 1
}, {
"name": "Elevation",
"data": [10,20,30,40,50,60,70,80,90,100],
"unit": "m",
"type": "area",
"valueDecimals": 0
}, {
"name": "Consumo Carburante",
"data": [10,20,30,40,50,60,70,80,90,100],
"unit": "l",
"type": "area",
"valueDecimals": 0
}]
});
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Highcharts Example</title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<style type="text/css">
.chart {
min-width: 320px;
max-width: 800px;
height: 220px;
margin: 0 auto;
}
</style>
<!-- http://doc.jsfiddle.net/use/hacks.html#css-panel-hack -->
<meta name="viewport" content="width=device-width, initial-scale=1" />
<style>
</style>
<script type="text/javascript">
/*
The purpose of this demo is to demonstrate how multiple charts on the same page can be linked
through DOM and Highcharts events and API methods. It takes a standard Highcharts config with a
small variation for each data set, and a mouse/touch event handler to bind the charts together.
*/
$(function () {
/**
* In order to synchronize tooltips and crosshairs, override the
* built-in events with handlers defined on the parent element.
*/
$('#container').bind('mousemove touchmove', function (e) {
var chart,
point,
i;
for (i = 0; i < Highcharts.charts.length; i = i + 1) {
chart = Highcharts.charts[i];
e = chart.pointer.normalize(e); // Find coordinates within the chart
point = chart.series[0].searchPoint(e, true); // Get the hovered point
if (point) {
point.onMouseOver(); // Show the hover marker
chart.tooltip.refresh(point); // Show the tooltip
chart.xAxis[0].drawCrosshair(e, point); // Show the crosshair
}
}
});
/**
* Override the reset function, we don't need to hide the tooltips and crosshairs.
*/
Highcharts.Pointer.prototype.reset = function () {
return undefined;
};
/**
* Synchronize zooming through the setExtremes event handler.
*/
function syncExtremes(e) {
var thisChart = this.chart;
if (e.trigger !== 'syncExtremes') { // Prevent feedback loop
Highcharts.each(Highcharts.charts, function (chart) {
if (chart !== thisChart) {
if (chart.xAxis[0].setExtremes) { // It is null while updating
chart.xAxis[0].setExtremes(e.min, e.max, undefined, false, { trigger: 'syncExtremes' });
}
}
});
}
}
// Get the data. The contents of the data file can be viewed at
// https://github.com/highcharts/highcharts/blob/master/samples/data/activity.json
// here i want to add my own json file which is local but i cant add it..
//********************** Problem **************************************
$.getJSON('https://www.highcharts.com/samples/data/jsonp.php?filename=activity.json&callback=?', function (activity) {
$.each(activity.datasets, function (i, dataset) {
// Add X values
dataset.data = Highcharts.map(dataset.data, function (val, j) {
return [activity.xData[j], val];
});
$('<div class="chart">')
.appendTo('#container')
.highcharts({
chart: {
marginLeft: 40, // Keep all charts left aligned
spacingTop: 20,
spacingBottom: 20,
zoomType: 'x'
},
title: {
text: dataset.name,
align: 'left',
margin: 0,
x: 30
},
credits: {
enabled: false
},
legend: {
enabled: false
},
xAxis: {
crosshair: true,
events: {
setExtremes: syncExtremes
},
labels: {
format: '{value} km'
}
},
yAxis: {
title: {
text: null
}
},
tooltip: {
positioner: function () {
return {
x: this.chart.chartWidth - this.label.width, // right aligned
y: -1 // align to title
};
},
borderWidth: 0,
backgroundColor: 'none',
pointFormat: '{point.y}',
headerFormat: '',
shadow: false,
style: {
fontSize: '18px'
},
valueDecimals: dataset.valueDecimals
},
series: [{
data: dataset.data,
name: dataset.name,
type: dataset.type,
color: Highcharts.getOptions().colors[i],
fillOpacity: 0.3,
tooltip: {
valueSuffix: ' ' + dataset.unit
}
}]
});
});
});
});
</script>
<body>
<script src="https://code.highcharts.com/highcharts.js"></script>
<div id="container"></div>
<!-- ******************************************************************************************** -->
</body>
</html>
save the below structure into local json file:
{
"xData": [0.001567,0.011765,0.022194,0.032316,0.04266,0.063668,0.074477,0.085323,0.09576,0.106078,0.116096,0.137524,0.148342,0.159059,0.170005,0.180716,0.191407,0.212538,0.222819,0.233929,0.244239,0.255301,0.266081,0.287527,0.298115,0.309392,0.320217,0.330928,0.341401,0.361717,0.372173,0.382337,0.39294,0.403072,0.413454,0.434618,0.444845,0.455745,0.465785,0.475987,0.486064,0.507086,0.517517,0.527961,0.538242,0.548414,0.558444,0.578941,0.589212,0.599472,0.60977,0.620178,0.630189,0.650782,0.661001,0.671137,0.681175,0.691235,0.702012,0.722644,0.733166,0.743824,0.754059,0.764109,0.774519,0.795597,0.805721,0.81592,0.826139,0.836369,0.846826,0.86771,0.87803,0.888342,0.898695,0.908723,0.91922,0.939802,0.950378,0.960776,0.971377,0.981843,0.992312,1.013125,1.023302,1.033488,1.043822,1.054203,1.065019,1.086078,1.09635,1.106421,1.117028,1.127541,1.138599,1.159588,1.170167,1.180741,1.190794,1.201112,1.211355,1.233278,1.243477,1.254957,1.265227,1.276378,1.285656,1.297311,1.308367,1.318715,1.329589,1.340834,1.352388,1.375063,1.385369,1.396291,1.408156,1.418989,1.429535,1.451141,1.462205,1.473011,1.483844,1.494311,1.514761,1.525336,1.535858,1.546476,1.557325,1.567512,1.590091,1.600925,1.612303,1.622558,1.633071,1.643555,1.66484,1.675722,1.685986,1.696733,1.706895,1.719102,1.741295,1.752144,1.762688,1.773713,1.784052,1.795705,1.817305,1.827465,1.838408,1.849369,1.860023,1.871438,1.89257,1.90323,1.914398,1.924634,1.934642,1.945212,1.966275,1.976294,1.986422,1.996652,2.008005,2.018309,2.041139,2.051221,2.0613,2.072507,2.08342,2.094075,2.114574,2.125286,2.135765,2.146845,2.157966,2.169391,2.190921,2.200899,2.212709,2.222671,2.232908,2.244001,2.264898,2.275703,2.286885,2.298115,2.310186,2.32059,2.344695,2.354843,2.366387,2.379001,2.390328,2.402215,2.423134,2.433156,2.444912,2.457061,2.468253,2.478978,2.499832,2.513223,2.52561,2.538429,2.548659,2.560809,2.581308,2.592816,2.603963,2.615992,2.626242,2.638223,2.660346,2.671583,2.681938,2.69265,2.70588,2.716296,2.740081,2.75085,2.761319,2.772027,2.782659,2.793531,2.816194,2.828031,2.839243,2.851443,2.863884,2.874359,2.895246,2.906506,2.91761,2.92786,2.938937,2.950218,2.973357,2.98366,2.994639,3.005213,3.01666,3.02761,3.050025,3.061713,3.071828,3.082787,3.093422,3.105289,3.127231,3.138982,3.149755,3.160217,3.171299,3.191571,3.202226,3.213225,3.223987,3.234092,3.244644,3.265939,3.276411,3.286489,3.297156,3.307909,3.319018,3.34064,3.351107,3.361683,3.373136,3.384768,3.395457,3.417722,3.429096,3.439122,3.449679,3.459868,3.469997,3.492679,3.503647,3.514941,3.525858,3.538746,3.550422,3.572255,3.58452,3.595367,3.605736,3.617401,3.628324,3.652523,3.663679,3.67378,3.684605,3.695595,3.705843,3.728706,3.739169,3.750205,3.761258,3.771771,3.781911,3.804724,3.81631,3.826313,3.837847,3.85049,3.860999,3.88262,3.892937,3.903053,3.913656,3.924698,3.935126,3.956362,3.966543,3.976899,3.98752,3.997644,4.008721,4.029852,4.040633,4.051006,4.06126,4.071761,4.083526,4.10749,4.117855,4.128661,4.13934,4.151117,4.1624,4.184736,4.194826,4.205098,4.215261,4.225325,4.236367,4.262012,4.273794,4.285743,4.297226,4.308086,4.318245,4.340246,4.351486,4.363196,4.374465,4.387109,4.398635,4.421101,4.432135,4.444666,4.456226,4.467413,4.477804,4.498505,4.510413,4.522595,4.534044,4.545944,4.558048,4.580379,4.59312,4.605616,4.618065,4.631266,4.644086,4.667943,4.67948,4.691266,4.703019,4.715923,4.725932,4.752312,4.765224,4.777128,4.787361,4.800435,4.823353,4.836044,4.848602,4.860302,4.871112,4.882779,4.904695,4.914823,4.927074,4.938111,4.949586,4.960761,4.982911,4.9942,5.004246,5.016296,5.027215,5.038043,5.058885,5.070303,5.080649,5.093865,5.104424,5.114903,5.134965,5.146346,5.15634,5.168547,5.179066,5.191167,5.214242,5.224914,5.237573,5.249537,5.261586,5.272517,5.296154,5.306348,5.316773,5.327153,5.339961,5.350638,5.376502,5.389277,5.402142,5.412197,5.42399,5.434873,5.458466,5.470907,5.482679,5.493339,5.50574,5.516349,5.538897,5.549552,5.56083,5.571879,5.583764,5.59509,5.619028,5.629925,5.640716,5.650957,5.661787,5.671957,5.693974,5.704919,5.717491,5.731152,5.744728,5.755687,5.778668,5.791951,5.80409,5.815697,5.828482,5.840501,5.864145,5.875704,5.887893,5.900147,5.912517,5.924894,5.948897,5.959155,5.970262,5.981632,5.992996,6.00356,6.027256,6.038776,6.050959,6.061351,6.071864,6.082436,6.104054,6.115602,6.127623,6.139058,6.150639,6.161323,6.183013,6.194359,6.206269,6.218033,6.2281,6.240494,6.262584,6.275326,6.287166,6.298953,6.310644,6.321583,6.345676,6.356738,6.366782,6.377931,6.388519,6.397159],
"datasets": [{
"name": "Speed",
"data": [10,20,30,40,50,60,70,80,90,100],
"unit": "km/h",
"type": "line",
"valueDecimals": 1
}, {
"name": "Elevation",
"data": [10,20,30,40,50,60,70,80,90,100],
"unit": "m",
"type": "area",
"valueDecimals": 0
}, {
"name": "Consumo Carburante",
"data": [10,20,30,40,50,60,70,80,90,100],
"unit": "l",
"type": "area",
"valueDecimals": 0
}]
}
Anyway, the most preferable way is to use getJson method:
$.getJSON( "test.json", function( data ) {
var items = [];
$.each( data, function( key, val ) {
... process data
});
...
});

Why isn't the C3 Chart appearing?

I am trying to create a simple chart and it just doesn't work. Any help would be great. I followed the instructions found on the C3.js documentation website, but I still get a blank page.
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="https://rawgit.com/masayuki0812/c3/master/c3.css">
<script src="http://d3js.org/d3.v3.min.js" charset="utf-8"></script>
<script src="https://rawgit.com/masayuki0812/c3/master/c3.js"></script>
<script>
var chart = c3.generate({
bindto: '#chart',
data: {
columns: [
['data1', 30, 200, 100, 400, 150, 250],
['data2', 50, 20, 10, 40, 15, 25]
]
}
});
</script>
</head>
<body>
<div id="chart"></div>
</body>
</html>
First, I would check for cross-origin exceptions. This is usually cause by using scripts that are hosted on other websites. If you are having issues such as this, look for a Content Delivery Network (CDN). These sites host scripts that can be run on any website.
But I believe your problem is that you are running JavaScript code before the document has finished loading. There are two ways to ensure that an element is loaded before you start performing JavaScript on the DOM.
Script in the HEAD (Using Timeout)
Your HTML page's source should look like this. You will need to wait for the element to be loaded first. This utilized pure JavaScript and does not need jQuery.
<!DOCTYPE html>
<html>
<head>
<link href="https://cdnjs.cloudflare.com/ajax/libs/c3/0.4.10/c3.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.5/d3.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/c3/0.4.10/c3.min.js"></script>
<script type="text/javascript">
onReady('#chart', function() {
var chart = c3.generate({
data: {
columns: [
['data1', 300, 350, 300, 0, 0, 0],
['data2', 130, 100, 140, 200, 150, 50]
],
types: {
data1: 'area',
data2: 'area-spline'
}
},
axis: {
y: {
padding: {
bottom: 0
},
min: 0
},
x: {
padding: {
left: 0
},
min: 0,
show: false
}
}
});
});
// Set a timeout so that we can ensure that the `chart` element is created.
function onReady(selector, callback) {
var intervalID = window.setInterval(function() {
if (document.querySelector(selector) !== undefined) {
window.clearInterval(intervalID);
callback.call(this);
}
}, 500);
}
</script>
</head>
<body>
<div id="chart"></div>
</body>
</html>
Script at DOM End (Without Timeout)
You could also run the script following the chart element. This script will be guaranteed to run, because the target object #chart has already been parsed by the browser and loaded.
<!DOCTYPE html>
<html>
<head>
<link href="https://cdnjs.cloudflare.com/ajax/libs/c3/0.4.10/c3.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.5/d3.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/c3/0.4.10/c3.min.js"></script>
</head>
<body>
<div id="chart"></div>
<script type="text/javascript">
var chart = c3.generate({
data: {
columns: [
['data1', 300, 350, 300, 0, 0, 0],
['data2', 130, 100, 140, 200, 150, 50]
],
types: {
data1: 'area',
data2: 'area-spline'
}
},
axis: {
y: {
padding: {
bottom: 0
},
min: 0
},
x: {
padding: {
left: 0
},
min: 0,
show: false
}
}
});
</script>
</body>
</html>
Stack Overflow Snippet
Here is a working example. Make sure your paths are correct to your D3 and C3 files.
var chart = c3.generate({
data: {
columns: [
['data1', 300, 350, 300, 0, 0, 0],
['data2', 130, 100, 140, 200, 150, 50]
],
types: {
data1: 'area',
data2: 'area-spline'
}
},
axis: {
y: {
padding: {
bottom: 0
},
min: 0
},
x: {
padding: {
left: 0
},
min: 0,
show: false
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.5/d3.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/c3/0.4.10/c3.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/c3/0.4.10/c3.min.css" rel="stylesheet" />
<div id="chart"></div>

Categories