Use d3 library to read from json file? - javascript

I have two different charts that use the same exact data. One uses json embedded in the html while the other reads a file.
I've been googling to see if I find examples where anychart reads from a json file or a web service. I have found nothing.
Since the 2nd chart reads json data using the d3.json call, I'm thinking that maybe it's possible to use that same function to read the data in the anychart chart.
So I'm including the javascript for both charts.
anychart javascript:
<script type="text/javascript">
anychart.onDocumentReady(function() {
chart = anychart.fromJson(
{chart: {type: "line",
series:[{seriesType: "spline",
data: [{x: "January", value: 10000},{x: "February", value: 12000},{x: "March", value: 18000}]}],
container: "container"}}
).draw();
});
</script>
d3 that reads that from a json file. Maybe I can use this call to populate the report in the previous code?:
d3.json("data.json", function(error, data) {
var nest = d3.nest()
.key(function(d) {
return d.date;
})
.map(data);
rect.filter(function(d) {
return ("$" + d) in nest;
})
.attr("fill", function(d) {
return color(nest[("$" + d)][0].open);
})
});
Any help is appreciated. I just want to know if this is possible.

There are https://api.anychart.com/7.13.1/anychart.data#loadJsonFile and https://api.anychart.com/7.13.1/anychart#fromJsonFile methods, they are a part of data adapter script.
Here are samples:
<!doctype html>
<html>
<head>
<script src="https://cdn.anychart.com/js/7.13.1/anychart-bundle.min.js"></script>
<script src="https://cdn.anychart.com/js/latest/data-adapter.min.js"></script>
<link rel="stylesheet" href="https://cdn.anychart.com/css/7.13.1/anychart-ui.min.css" />
<style>
html, body, #container {
width: 100%;
height: 100%;
margin: 0;
padding: 0;
}
</style>
</head>
<body>
<div id="container"></div>
<script>
anychart.onDocumentReady(function () {
// To work with the data adapter you need to reference the data adapter script file from AnyChart CDN
// (https://cdn.anychart.com/js/latest/data-adapter.min.js for latest or https://cdn.anychart.com/js/7.11.1/data-adapter.min.js for the versioned file)
// Load JSON data and create a chart by JSON data.
anychart.data.loadJsonFile("https://cdn.anychart.com/charts-data/data_json.json", function (data) {
chart = anychart.bar(data);
chart.title("Load JSON data and create a chart");
chart.container("container");
chart.draw();
});
});
</script>
</body>
</html>
https://playground.anychart.com/api/7.13.1/modules/anychart.data.loadJsonFile-plain
<!doctype html>
<html>
<head>
<script src="https://cdn.anychart.com/js/7.13.1/anychart-bundle.min.js"></script>
<script src="https://cdn.anychart.com/js/latest/data-adapter.min.js"></script>
<link rel="stylesheet" href="https://cdn.anychart.com/css/7.13.1/anychart-ui.min.css" />
<style>
html, body, #container {
width: 100%;
height: 100%;
margin: 0;
padding: 0;
}
</style>
</head>
<body>
<div id="container"></div>
<script>
anychart.onDocumentReady(function () {
// To work with the data adapter you need to reference the data adapter script file from AnyChart CDN
// (https://cdn.anychart.com/js/latest/data-adapter.min.js for latest or https://cdn.anychart.com/js/7.11.1/data-adapter.min.js for the versioned file)
// Create a chart by JSON config.
anychart.fromJsonFile("https://cdn.anychart.com/config-samples/line-chart.json", function (chart) {
chart.title("Create a chart by JSON config");
chart.container("container");
chart.draw();
});
});
</script>
</body>
</html>
https://playground.anychart.com/api/7.13.1/modules/anychart.fromJsonFile-plain

Related

Javascript framework not working properly same code as jsfiddle?

<html>
<head>
<meta charset="UTF-8">
<title>Simple globe with iTowns</title>
<style>
html { height: 100%; }
body { margin: 0; overflow: hidden; height: 100%; }
#viewerDiv { margin: auto; height: 100%; width: 100%; padding: 0; }
canvas { display: block }
</style>
</head>
<body>
<div id="viewerDiv"></div>
<script src="https://cdn.jsdelivr.net/npm/itowns#2.32.0/dist/itowns.js </script>
<script type="text/javascript">
var viewerDiv = document.getElementById('viewerDiv');
var placement = {
coord: new itowns.Coordinates('EPSG:4326', 2.351323, 48.856712),
range: 25000000
};
var view = new itowns.GlobeView(viewerDiv, placement);
var orthoSource = new itowns.WMTSSource({
url: 'https://wxs.ign.fr/3ht7xcw6f7nciopo16etuqp2/geoportail/wmts',
crs: "EPSG:3857",
name: 'ORTHOIMAGERY.ORTHOPHOTOS',
tileMatrixSet: 'PM',
format: 'image/jpeg',
})
var orthoLayer = new itowns.ColorLayer('Ortho', {
source: orthoSource,
});
view.addLayer(orthoLayer);
var elevationSource = new itowns.WMTSSource({
url: 'https://wxs.ign.fr/3ht7xcw6f7nciopo16etuqp2/geoportail/wmts',
crs: 'EPSG:4326',
name: 'ELEVATION.ELEVATIONGRIDCOVERAGE.SRTM3',
tileMatrixSet: 'WGS84G',
format: 'image/x-bil;bits=32',
zoom: {min: 3, max: 10},
});
var elevationLayer = new itowns.ElevationLayer('MNT_WORLD', {
source: elevationSource,
});
view.addLayer(elevationLayer);
</script>
</body>
</html>
I am using a framework called iTowns and I have copied the code exactly from a jsfiddle they provided as an example. The jsfiddle loads Earth fine but my code does not properly load the land layer and instead I get a blue sphere. I get this error in the console,
"Failed to load resource: the server responded with a status of 403 (Forbidden)"
I am running the website on a live local server. What am I missing here?
http://jsfiddle.net/q70umk6r/
Hard to tell if your resources are available, but given that you're getting a 403, I'm guessing not.
you could try using cdn package instead though
<script src="https://cdn.jsdelivr.net/npm/itowns#2.32.0/dist/itowns.js"></script>
just because "https://wxs.ign.fr/3ht7xcw6f7nciopo16etuqp2/geoportail/wmts" server dont allow GET request that its request headers' Referer not "localhost:xx/xxx" or other Registered urls;

Who knows why I can't plot my chart properly?

The chart appears but it'completely empty when I change the type to bar, and completely black when I keep horizontalBar.
If I try to cut my data leaving jest few rows the horizontalBar chart appears empty too
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.8.0/Chart.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>
</head>
<style>
#wrapper {
height: 1000px;
}
</style>
<body>
<div id="wrapper">
<canvas id="chart"></canvas>
</div>
<SCRIPT LANGUAGE=javascript>
function makeChart(products)
var Counter = products.map(function(d) {
return d.Counter;
});
var CumVol = products.map(function(d) {
return +d.CumVol;
});
var chart = new Chart('chart', {
type: "horizontalBar",
options: {
maintainAspectRatio: true,
legend: {
display: false
}
},
data: {
labels: Counter,
datasets: [
{
data: CumVol
}
]
}
});
}
// Request data using D3
d3
.csv("http://localhost:8080/cumvol.csv")
.then(makeChart);
</SCRIPT>
</body></html>
Counter;CumVol
1;0.009999999776482582
2;0.029999999329447746
3;0.06999999843537807
4;0.12999999709427357
5;0.13999999687075615
6;0.14999999664723873
7;0.1599999964237213
Here few rows of my csv file cumvol
Trying with another file everything is showed properly (I mean changing the name of the columns):
Name,Weeks,Gender
Steffi Graf,377,Female
Martina Navratilova,332,Female
Serena Williams,319,Female
Roger Federer,308,Male
Pete Sampras,286,Male
Ivan Lendl,270,Male
Jimmy Connors,268,Male
Chris Evert,260,Female
Novak Djokovic,223,Male
The reason is that in the two CSV files, the fields are not separated by the same character (comma vs. semicolon).
You may consider using d3-csv instead of d3.csv.
Please also take a look at this answer: https://stackoverflow.com/a/27432751/2358409

Not displaying the table in web page using flask

Hi I am using flask to create a web app in python.
In my profile.html page in template direcotiry I have profile.html as shown below.
<!DOCTYPE html>
<html lang="en">
<head>
<title>App</title>
<link href="http://getbootstrap.com/dist/css/bootstrap.min.css" rel="stylesheet">
<link href="http://getbootstrap.com/examples/jumbotron-narrow/jumbotron-narrow.css" rel="stylesheet">
<script src="../static/js/jquery-1.11.2.js"></script>
<script src="../static/js/getAcademic.js"></script>
</head>
<body>
<div class="jumbotron">
</div>
</body>
</html>
In the app.py,
#app.route('/getDetails')
def getDetails():
try:
#get data from mysql database and convert to a json and return
return json.dumps(academic_dict)
except Exception as e:
return render_template('error.html', error=str(e))
The returned json object is as follows,
In my js file,
$(function() {
$.ajax({
url: '/getDetails',
type: 'GET',
success: function(res) {
var div = $('<table>')
.attr('class', 'list-group')
.append($('<tr>')
.attr('class', 'list-group-item active')
.append($('<td>')
.attr('class', 'list-group-item-text'),
$('<td>')
.attr('class', 'list-group-item-text')));
var wishObj = JSON.parse(res);
var wish = '';
$.each(wishObj,function(index, value){
wish = $(table).clone();
$(wish).find('td').text(value.Title);
$(wish).find('td').text(value.Data);
$('.jumbotron').append(wish);
});
},
error: function(error) {
console.log(error);
}
});
});
json is converted and returned correctly but the data is not displaying in the profile.html page. I checked the console and it is displaying the error Uncaught ReferenceError: table is not defined in the .js file.
I want to display a table with the data returned as the json object but the table is not displaying when the profile.html page is loading. Please help me with this.
You've got one simple mistake (but don't worry, that happens to everyone...) on the line wish = $(table).clone(); – you use table to reference <table> you saved in variable div .
Either replace $(table) with $(div) there or (I would suggest this solution for readability) rename var div = $('<table>') in the beginning to var table = ...
(Sorry for reviving such an old post, but I'm on badge hunt :])
Oh, and one more point: please don't use screenshots of code, but the code itself (even just shortened) for us to test your problem and our solution:
[{'Title': 'Name', 'Data': 'john mark'},
{'Title': 'Faculty', 'Data': 'cs'}]`

How to get the data attribute of the canvas chart created using chartjs

Hi all i am using ChartJs to create charts.i am setting some data attribute on the canvas.on clicking on the chart i need to get the data attribute assigned in the canvas.i have found a method in the documentation which i used to get the label and values of the region of the chart clicked,but i don't know how to get the data attributes.
<!DOCTYPE html>
<html>
<head>
<title> Pie Chart </title>
<style>
.pie-chart-canvas-wrapper{
box-sizing:border-box;
width:500px;
height:300px;
float:left;
}
</style>
</head>
<body>
<div id="pie-charts-whole-wrapper" >
<div class="pie-chart-canvas-wrapper">
<canvas data-region="RO1" data-role="sales" width="500px" height="300px" id="pie1" ></canvas>
</div>
</div> <!--/ Pie Charts whole Wrapper -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.min.js"></script>
<script>
var ctx1 = document.getElementById("pie1");
var pieChart1 = new Chart(ctx1, {
type: 'pie',
data: {
labels: ["signed", "Not Signed"],
datasets: [
{
data: [20, 50],
backgroundColor:['#2ecc71','#34495e']
}
]
}
});
ctx1.onclick = function(evt) {
var activePoints = pieChart1.getElementsAtEvent(evt);
if (activePoints[0]) {
var chartData = activePoints[0]['_chart'].config.data;
var idx = activePoints[0]['_index'];
var label = chartData.labels[idx];
var value = chartData.datasets[0].data[idx];
console.log(label);
console.log(value);
}
};
</script>
</body>
</html>
If you want to get the attribute data-role, .getAttribute() is doing the job.
console.log(this.getAttribute("data-role"));
CodePen

How to update a value in a cvs file through a mouse click on highcharts graphs

I want to update my cvs file through a mouse click on a graph, like I create a graph by reading a data from the same cvs file and when I get a graph what I want is that whenever I click on a point it make that point equal to zero on y-axis and update the corresponding value in a cvs file equal to 0.
Please can someone help. Here is my code which can take values from cvs file but is not updating but the same code works fine if I take hard coded series of an array.
Don't understand why isn't these plot options working.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Highcharts Example</title>
<!-- 1. Add these JavaScript inclusions in the head of your page -->
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript" src="../js/highcharts.js"></script>
<!--[if IE]>
<script type="text/javascript" src="../js/excanvas.compiled.js"></script>
<![endif]-->
<!-- 2. Add the JavaScript to initialize the chart on document ready -->
<script type="text/javascript">
$(document).ready(function() {
var options = {
chart: {
renderTo: 'container',
defaultSeriesType: 'line'},
title: { text: 'Output'},
xAxis: { categories: []},
yAxis: {
title: { text: 'Units'} },
plotOptions: {
series: { cursor: 'pointer',
point: {
events: { click: function() {
var y = this.item(y);
var x = this.x;
chart.series[0].data[x].update(y -= y);} } } },
series: []
};
$.get('testFile.csv', function(data) {
// Split the lines
var lines = data.split('\n');
$.each(lines, function(lineNo, line) {
var items = line.split(',');
var series = {
data: []
};
$.each(items, function(itemNo, item) {
series.data.push(parseFloat(item));
});
options.series.push(series); });
var chart = new Highcharts.Chart(options);
});
});
</script>
</head>
<body>
<script src="http://code.highcharts.com/highcharts.js"></script>
<script src="http://code.highcharts.com/modules/data.js"></script>
<script src="http://code.highcharts.com/modules/exporting.js"></script>
<div id="container" style="width: 1400px; height: 400px; margin: 0 auto"></div>
</body>
</html>
You can catch click point action http://api.highcharts.com/highcharts#plotOptions.series.point.events.click and then use get new value from csv by ajax and use update() function http://api.highcharts.com/highcharts#Point.update()

Categories