Multiple automatic updating series from JSON - json

I try to plot 3 temperature series into a single highcharts chart.
The data comes from 3 seperate JSON files in the format:
[
[1567529940953,43.4],
[1567530001644,43.3],
[1567530062503,43.4],
[1567530123220,43.4],
[1567530184116,43.4]
]
Additionally the JSON file is periodically updated so I want the chart to update itself every time the JSON files change or every minute or so.
I looked into enablePolling and that works perfect.
I have tried a lot but or I have multiple series and no polling or I have a single series and polling....
The best I could do was:
<script type="text/javascript">
Highcharts.stockChart('container', {
chart: {
type: 'spline'
},
rangeSelector: {
selected: 2,
buttons: [{
type: 'hour',
count: 1,
text: '1h'
}, {
type: 'hour',
count: 12,
text: '12h'
}, {
type: 'all',
text: 'All'
}]
},
title: {
text: 'Live Data (Rows JSON)'
},
yAxis: {
min: 15,
max: 50,
startOnTick: false,
endOnTick: false
},
subtitle: {
text: 'Data input from a remote JSON file'
},
data: {
rowsURL: window.location.origin + '/chart/terrarium_basking.json',
firstRowAsNames: false,
enablePolling: true
}
});
</script>
I needed to use window.location.origin in order to get it to work on my website. Not sure why www.reptile-addict.nl/chart/terrarium_basking.json didn't work!?
If it helps the other JSON streams are terrarium_ambient.json and terrarium_ceiling.json
EDIT: Think I got it to work.. :)
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Highstock Example</title>
<style type="text/css">
</style>
</head>
<body>
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script src="https://code.highcharts.com/stock/highstock.js"></script>
<script src="https://code.highcharts.com/stock/modules/exporting.js"></script>
<script src="https://code.highcharts.com/stock/modules/export-data.js"></script>
<div id="container" style="height: 400px; min-width: 310px"></div>
<script type="text/javascript">
var seriesOptions = [],
seriesCounter = 0,
names = ['basking','ambient','ceiling'];
/**
* Create the chart when all data is loaded
* #returns {undefined}
*/
function createChart() {
Highcharts.stockChart('container', {
series: seriesOptions
});
}
function getJsonData() {
$.each(names, function (i, name) {
path = window.location.origin + '/chart/terrarium_' + name + '.json';
$.getJSON(path, function (data) {
seriesOptions[i] = {
name: name,
data: data
};
// As we're loading the data asynchronously, we don't know what order it will arrive. So
// we keep a counter and create the chart when all the data is loaded.
seriesCounter += 1;
if (seriesCounter === names.length) {
createChart();
seriesCounter = 0;
}
});
});
}
getJsonData();
setInterval( function(){ getJsonData(); }, 60000);
</script>
</body>
</html>

Related

Uncaught TypeError: $(...).fullCalendar is not a function despite adding alll the library

I am trying to render a calender using fullcalendar library. Below is the code that has alll the script declare
This is my code
<script src="https://cdn.jsdelivr.net/npm/fullcalendar#5.10.1/main.min.js"></script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/fullcalendar#5.10.1/main.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js" integrity="sha512-qTXRIMyZIFb8iQcfjXWCO8+M5Tbc38Qi5WzdPOYZHIlZpzBHG3L3by84BBBOiRGiEb7KKtAOAs5qYdUiZiQNNQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js" integrity="sha512-894YE6QWD5I59HgZOGReFYm4dnWc1Qt5NtvYSaNcOP+u1T9qYdvdihz0PPSiiqn/+/3e7Jo4EaG7TubfWGUrMQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<script>
$(document).ready(function () {
var eventList = [];
$.ajax({
type: "GET",
url: "/home/GetEvents",
success: function (data) {
#*console.log("data ", data);*#
$.each(data, function (i, content) {
eventList.push({
title: content.Subject,
description: content.Description,
creationDate: moment(content.CreationDate),
modifiedDate: content.ModifiedDate != null ? moment(content.ModifiedDate) : "",
color: content.Color,
isFullday: content.isFullday
});
})
GenerateCalendar(eventList);
},
error: function (error) {
console.log("unable to generate calendar, the error is: ", error);
}
})
function GenerateCalendar(events) {
// do not create another calendar if one exist
$('#calender').fullCalendar('destroy');
$("#calender").fullCalendar({
contentHeight: 400,
defaultDate: new Date(),
timeFormat: "h(:mm)a",
header: {
left: "previous, next today",
center: "title",
right: "month, basicWeek, basicDay, agenda"
},
eventLimit: true,
eventColor: "#378006",
events: events
})
}
})
</script>
I have add all the necessary scripts from this link, but when I try to use the function from the library, it has error.
any advice is appreciated
This is the solution from this link, I hope this help someone in the future
function GenerateCalendar(events) {
var calendarEl = document.getElementById('calender');
var calendar = new FullCalendar.Calendar(calendarEl, {
initialView: 'dayGridMonth'
});
calendar.render();
}

Unable to visualize points as clusters in the Mapbox GL JS Geojson example from their website

When I tried out this example from the mapbox website I was able to see only the base map. Whereas the Geojson data which I want to visualize as stylized clusters on the map is not being rendered on mapbox gl js. I used the same code example that is on their website but it was unsuccessful.
(url: https://www.mapbox.com/mapbox-gl-js/example/cluster/).
I don't know what's going wrong. Any help will be greatly appreciated. Thank you.
Here's the code....
<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8' />
<title></title>
<meta name='viewport' content='initial-scale=1,maximum-scale=1,user-scalable=no' />
<script src='https://api.tiles.mapbox.com/mapbox-gl-js/v0.35.1/mapbox-gl.js'></script>
<link href='https://api.tiles.mapbox.com/mapbox-gl-js/v0.35.1/mapbox-gl.css' rel='stylesheet' />
<style>
body { margin:0; padding:0; }
#map { position:absolute; top:0; bottom:0; width:100%; }
</style>
</head>
<body>
<div id='map'></div>
<script>
mapboxgl.accessToken = 'pk.eyJ1IjoiYW5pcnVkaDIwMjAiLCJhIjoiY2oxMzljM3EwMDAwYTJ3czhtd2dsMmRxZiJ9._9BAosMxlmvnT8FXh7JXYw';
var map = new mapboxgl.Map({
container: 'map',
style: 'mapbox://styles/mapbox/dark-v9',
center: [-103.59179687498357, 40.66995747013945],
zoom: 3
});
map.on('load', function() {
// Add a new source from our GeoJSON data and set the
// 'cluster' option to true. GL-JS will add the point_count property to your source data.
map.addSource("earthquakes", {
type: "geojson",
// Point to GeoJSON data. This example visualizes all M1.0+ earthquakes
// from 12/22/15 to 1/21/16 as logged by USGS' Earthquake hazards program.
data: "https://www.mapbox.com/mapbox-gl-js/assets/earthquakes.geojson",
cluster: true,
clusterMaxZoom: 14, // Max zoom to cluster points on
clusterRadius: 50 // Radius of each cluster when clustering points (defaults to 50)
});
map.addLayer({
id: "clusters",
type: "circle",
source: "earthquakes",
filter: ["has", "point_count"],
paint: {
"circle-color": {
property: "point_count",
type: "interval",
stops: [
[0, "#51bbd6"],
[100, "#f1f075"],
[750, "#f28cb1"],
]
},
"circle-radius": {
property: "point_count",
type: "interval",
stops: [
[0, 20],
[100, 30],
[750, 40]
]
}
}
});
map.addLayer({
id: "cluster-count",
type: "symbol",
source: "earthquakes",
filter: ["has", "point_count"],
layout: {
"text-field": "{point_count_abbreviated}",
"text-font": ["DIN Offc Pro Medium", "Arial Unicode MS Bold"],
"text-size": 12
}
});
map.addLayer({
id: "unclustered-point",
type: "circle",
source: "earthquakes",
filter: ["!has", "point_count"],
paint: {
"circle-color": "#11b4da",
"circle-radius": 4,
"circle-stroke-width": 1,
"circle-stroke-color": "#fff"
}
});
});
</script>
</body>
</html>
If you look into the browser inspector, you will see
XMLHttpRequest cannot load https://www.mapbox.com/mapbox-gl-js/assets/earthquakes.geojson. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'https://s.codepen.io' is therefore not allowed access.
You need to download the JSON file and load it from local server, then it will work.

How do I import a csv into chart.js?

I have been looking for this solution but can't seem to find it . Does chart.js support this ?
I have attempted to parse in the data with papaparse, but due to my limited knowledge I can't find a solution.
There is a Chart.js plugin chartjs-plugin-datasource that makes it easy to load data from CSV files.
Let's suppose you have a CSV file as shown below, and it is saved as sample-dataset.csv in the same directory as your HTML file:
,January,February,March,April,May,June,July
Temperature,7,7,10,15,20,23,26
Precipitation,8.1,14.9,41.0,31.4,42.6,57.5,36.0
Include Chart.js and chartjs-plugin-datasource in your page:
<script src="https://cdn.jsdelivr.net/npm/chart.js#2.8.0"></script>
<script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-datasource#0.1.0"></script>
<canvas id="myChart"></canvas>
Then, specify sample-dataset.csv in your script. By default, each row in a CSV file will be mapped to one dataset, and the first column and the first row will be treated as dataset labels and index labels respectively. You can also customize how to parse CSV data using options.
var ctx = document.getElementsById("myChart");
var chart = new Chart(ctx, {
type: 'bar',
data: {
datasets: [{
type: 'line',
yAxisID: 'temperature',
backgroundColor: 'transparent',
borderColor: 'rgb(255, 99, 132)',
pointBackgroundColor: 'rgb(255, 99, 132)',
tension: 0,
fill: false
}, {
yAxisID: 'precipitation',
backgroundColor: 'rgba(54, 162, 235, 0.5)',
borderColor: 'transparent'
}]
},
plugins: [ChartDataSource],
options: {
scales: {
yAxes: [{
id: 'temperature',
gridLines: {
drawOnChartArea: false
}
}, {
id: 'precipitation',
position: 'right',
gridLines: {
drawOnChartArea: false
}
}]
},
plugins: {
datasource: {
url: 'sample-dataset.csv'
}
}
}
});
Here is my solution that works fine for me. I have a CSV file like this:
country,population
China,1415046
India,1354052
United States,326767
Indonesia,266795
Brazil,210868
...
I want to plot a bar chart with my dataset, the y-axis is population and the x-axis is country.
This is the body of my HTML file.
<body>
<canvas id="myChart" width="100" height="100"></canvas>
<script>
// Load the dataset
d3.csv("data.csv").then(makeChart);
// Plot the data with Chart.js
function makeChart(countries) {
var countryLabels = countries.map(function (d) {
return d.country;
});
var populationData = countries.map(function (d) {
return d.population;
});
var chart = new Chart("myChart", {
type: "bar",
data: {
labels: countryLabels,
datasets: [
{
data: populationData
}
]
}
});
}
</script>
</body>
Result:
You can try it with Codesandbox.
I've had need to do something like this from time to time as well. Here's a link on how to create a chart with Chart.js from a CSV file that explains exactly how to create a chart with Chart.js directly from a CSV file.
The use case explains how to convert a CSV file to JSON using the Flex.io web service (Full disclosure: I'm the senior front end developer at Flex.io).
Here's a JsFiddle if you'd like to see the use case in action:
function getRandomColor() {
var letters = '0123456789ABCDEF'.split('');
var color = '#';
for (var i = 0; i < 6; i++) {
color += letters[Math.floor(Math.random() * 16)];
}
return color;
}
$.ajax({
type: 'post',
url: 'https://www.flex.io/api/v1/pipes/flexio-chart-js-csv-to-json/run?stream=0',
beforeSend: function(xhr) {
xhr.setRequestHeader('Authorization', 'Bearer nmgzsqppgwqbvkfhjdjd');
},
data: $('form').serialize(),
dataType: "json",
success: function(content) {
// render the JSON result from from the Flex.io pipe
$("#flexio-result-data").text(JSON.stringify(content, null, 2))
var first_item = _.get(content, '[0]', {})
var column_labels = _.map(_.omit(first_item, ['os']), function(val, key) {
if (key != 'os')
return key
})
// use Lodash to reformat the JSON for use with Chart.js
var datasets = _.map(content, function(item) {
// use the 'os' column as our label
var item_label = _.get(item, 'os', 'Not Found')
// create an array of number values from each item's JSON object
var item_values = _.map(_.omit(item, ['os']), function(val) {
return parseFloat(val)
})
return {
label: item_label,
data: item_values,
backgroundColor: getRandomColor()
}
})
var chart_data = {
labels: column_labels,
datasets: datasets
}
// render the JSON result after mapping the data with Lodash
$("#chart-data").text(JSON.stringify(chart_data, null, 2))
// render the chart using Chart.js
var ctx = document.getElementById("canvas").getContext("2d");
window.my_chart = new Chart(ctx, {
type: 'bar',
data: chart_data,
options: {
responsive: true,
legend: {
position: 'top'
},
title: {
display: true,
text: 'Use Flex.io to Create a Chart With Chart.js Directly From a CSV File'
}
}
});
}
});
Feel free to step through the use case and let me know if you have any issues.
The simple example of importing CSV data into ChartJS
index.html:
<!-- ChartJS plugin datasrouce example
chartjs-plugin-datasource: https://nagix.github.io/chartjs-plugin-datasource/
Samples: https://nagix.github.io/chartjs-plugin-datasource/samples/
Specific example: https://nagix.github.io/chartjs-plugin-datasource/samples/csv-index.html
Data source: https://gist.githubusercontent.com/mikbuch/32862308f4f5cac8141ad3ae49e0920c/raw/b2b256d69a52dd202668fe0343ded98371a35b15/sample-index.csv -->
<head>
<script src="https://cdn.jsdelivr.net/npm/chart.js#2.8.0"></script>
<script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-datasource#0.1.0"></script>
</head>
<body>
<div>
<canvas id="myChart"></canvas>
</div>
<script src="script.js"></script>
</body>
You can also download this index.html file as a gist.
script.js
// ChartJS plugin datasrouce example
// chartjs-plugin-datasource: https://nagix.github.io/chartjs-plugin-datasource/
// Samples: https://nagix.github.io/chartjs-plugin-datasource/samples/
// Specific example: https://nagix.github.io/chartjs-plugin-datasource/samples/csv-index.html
// Data source: https://gist.githubusercontent.com/mikbuch/32862308f4f5cac8141ad3ae49e0920c/raw/b2b256d69a52dd202668fe0343ded98371a35b15/sample-index.csv
var chartColors = {
red: 'rgb(255, 99, 132)',
blue: 'rgb(54, 162, 235)'
};
var color = Chart.helpers.color;
var config = {
type: 'bar',
data: {
datasets: [{
type: 'line',
yAxisID: 'temperature',
backgroundColor: 'transparent',
borderColor: chartColors.red,
pointBackgroundColor: chartColors.red,
tension: 0,
fill: false
}, {
yAxisID: 'precipitation',
backgroundColor: color(chartColors.blue).alpha(0.5).rgbString(),
borderColor: 'transparent'
}]
},
plugins: [ChartDataSource],
options: {
title: {
display: true,
text: 'CSV data source (index) sample'
},
scales: {
xAxes: [{
scaleLabel: {
display: true,
labelString: 'Month'
}
}],
yAxes: [{
id: 'temperature',
gridLines: {
drawOnChartArea: false
},
scaleLabel: {
display: true,
labelString: 'Temperature (°C)'
}
}, {
id: 'precipitation',
position: 'right',
gridLines: {
drawOnChartArea: false
},
scaleLabel: {
display: true,
labelString: 'Precipitation (mm)'
}
}]
},
plugins: {
datasource: {
type: 'csv',
url: 'https://gist.githubusercontent.com/mikbuch/32862308f4f5cac8141ad3ae49e0920c/raw/b2b256d69a52dd202668fe0343ded98371a35b15/sample-index.csv',
delimiter: ',',
rowMapping: 'index',
datasetLabels: true,
indexLabels: true
}
}
}
};
window.onload = function() {
var ctx = document.getElementById('myChart').getContext('2d');
window.myChart = new Chart(ctx, config);
};
Here is a a gist with this script.js file.
Make sure that both files are in the same directory.
Open index.html with your browser.
Additional materials
CodeSandbox example to preview the example online.
Reason for posting this answer:
I posted this because people are having problems with reading CSV files from the filesystem (directly from the computer) with JavaScript. The examples in chartjs-plugin-datasource documentation don't explain this, and it is assumed that the user has some basic knowledge on the differences in handling URLs from the web, and files from the file system.
My example just shows the basic functionality of the ChartJS datasource plugin, no third-party modules for reading the CSV file are required.
Edit:
According to ggorlen's suggestion from the comment, I also included the code snippets in the answer itself.
Can't post comments on this elitist site, because four years hasn't gotten me enough "points." ....
#huy - interesting how your Codesandbox has completely different code than what you've posted which I found was directly ripped off from another site... it doesn't even relate to the chart you were talking about building. Within Codesandbox, all I see is an image file of the chart, nothing is actually working (and how could it, when the code isn't even related to your dataset!?).

How to create the object literal method to use the http get request to get the json data?

I got stuck with the http get method which is used to get the json data.
The http get method is working fine it is actually fetching the json data, but I'm not able to connect it with the object literal.
To explain clearly here is the piece of code where I'm stuck.
var x ={};
$http.get('chart.json') //reading the studentRecord.json file
.success
(function(data1){
//alert(data1);
$scope.x = data1;
});
var conversionChart = new FusionCharts({
type: 'funnel',
renderAt: 'chart-container',
width: "100%",
dataFormat: 'json',
dataSource: x
});
I'm trying to apply the http.get method to the dataSource:to fetch the json data to it but, its not working. And my main task is to apply the http.get request to the dataSource:which makes my code work properly.
And let me give you the entire piece of code to understand better.
index.html
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title>FusionCharts - Funnel 3D Chart</title>
<link rel="stylesheet" type="text/css" href="/css/result-light.css">
<link rel="stylesheet" type="text/css" href="/css/normalize.css">
<script data-require="angular.js#1.4.0-beta.6" data-semver="1.4.0-beta.6" src="https://code.angularjs.org/1.4.0-beta.6/angular.js"></script>
<script type='text/javascript' src="http://static.fusioncharts.com/code/latest/fusioncharts.js"></script>
<script type='text/javascript' src="http://static.fusioncharts.com/code/latest/fusioncharts.widgets.js"></script>
<script type='text/javascript' src='/js/lib/dummy.js'></script>
<script type='text/javascript' src="http://static.fusioncharts.com/code/latest/themes/fusioncharts.theme.fint.js"></script>
<script src="script.js"></script>
</head>
<body ng-app="myApp">
<!-- A funnel 3D Chart showing a conversion analysis in percentage of visiting to purchase in Harry's Supermart website last year
Attribute :
# showPercentValues - set to 1 to show the values in percentage.
-->
<div id="chart-container" ng-controller="ParentCtrl" ng-init='load()' ng-model="dataSource1">FusionCharts will render here</div>
</body>
</html>
script.js
var myApp = angular.module("myApp", []);
//The below code will read the data from student.json file and will pass to the $scope variable
myApp.controller("ParentCtrl", function($scope, $http)
{
$scope.load = function(){
//alert("2");
FusionCharts.ready(function () {
//alert("1");
var conversionChart = new FusionCharts({
type: 'funnel',
renderAt: 'chart-container',
width: "100%",
dataFormat: 'json',
dataSource : function(){
$http.get('chart.json') //reading the studentRecord.json file
.success
(function(data1){
alert(data1);
$scope.dataSource = data1;// binding the data to the $scope variable
});
}
});
conversionChart.render();
});
};
});
chart.json
{
"chart": {
"caption": "Ensource sales report",
"subcaption": "Purchase - Conversion analysis for last year",
"decimals": "1",
"isHollow": "0",
"isSliced": "1",
"labelDistance": "15",
"plotTooltext": "Success : $percentOfPrevValue",
"theme": "fint",
"baseFontSize":"18"
},
"data":
[
{
"label": "Total",
"value": "385634"
},
{
"label": "Contacts",
"value": "175631"
},
{
"label": "Leads",
"value": "84564"
},
{
"label": "Sanctioned",
"value": "35654"
},
{
"label": "Disbursed",
"value": "12342"
}
]
}
My main intention is to use the http.get method to fetch the json data to
dataSource :
Plunker:http://plnkr.co/edit/HUKvROQv8wIiFfx6uZBk?p=preview
I'll be very thankfull if somebody help me with this .Plz help me because I'm new bee to angular
Based on your plunker, the code should be:
var myApp = angular.module("myApp", []);
//The below code will read the data from student.json file and will pass to the $scope variable
myApp.controller("ParentCtrl", function($scope, $http)
{
$scope.load = function(){
//alert("2");
FusionCharts.ready(function () {
//alert("1");
var conversionChart;
$http.get('chart.json') //reading the studentRecord.json file
.success
(function(data1){
//alert(data1);
$scope.dataSource = data1;// binding the data to the $scope variable
conversionChart = new FusionCharts({
type: 'funnel',
renderAt: 'chart-container',
width: "100%",
dataFormat: 'json',
dataSource : $scope.dataSource
});
conversionChart.render();
});
});
};
});

C3js, Papaparse, Parse CSV to C3js

I've been trying to parse a CSV file with Papaparse4 to use it on charts created with C3js, but I can't get it to work.
I want to be able to load different CSV files, so I'm using a file input, the file gets parsed (I can see it on the console), but I can't load the data to the chart.
You can test it here: http://jsfiddle.net/Honzo_Nebro/mv6eomf4/
function handleFileSelect(evt) {
var file = evt.target.files[0];
Papa.parse(file, {
header: true,
dynamicTyping: true,
complete: function(results) {
data = results;
console.log(data);
var chart = c3.generate({
bindto: '#chart',
size: {
height: 359
},
json: data,
});
}
});
}
$(document).ready(function() {
$("#csv-file").change(handleFileSelect);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="file" id="csv-file" name="files" />
<div id="chart"></div>
So, with lots of insights from a friend we came to this. It seems to not be working on this snippet, but it does on jsfiddle, I may have misplaced something http://jsfiddle.net/Honzo_Nebro/mv6eomf4/3/
function handleFileSelect(evt) {
var file = evt.target.files[0];
Papa.parse(file, {
header: true,
dynamicTyping: true,
complete: function(results) {
console.log(results.data);
//Create an empty array and fill it with the headers
var values = [];
$.each(results.data[0], function(key, value) {
values.push(key);
});
var chart = c3.generate({
bindto: '#chart',
size: {
height: 359
},
data: {
json: results.data,
keys: {
//assign the array to the value property
value: values,
},
type: 'donut',
},
unload: true,
legend: {
postion: 'bottom',
},
tooltip: {
format: {
value: function(name, ratio, id, index) {
ratio2 = ratio * 100;
var text = name + ", (" + ratio2.toFixed(1) + "%)";
return name;
}
}
}
});
}
});
}
<script src="https://rawgit.com/mholt/PapaParse/master/papaparse.min.js"></script>
<link href="https://rawgit.com/masayuki0812/c3/master/c3.css" rel="stylesheet"/>
<script src="https://rawgit.com/masayuki0812/c3/master/c3.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="file" id="csv-file" name="files" />
<div id="chart"></div>