JSON Data formatting for Highcharts - javascript

I have a json object as shown below. I would like it to groupBy based on a specific property say "SEX" and pass it to highcharts such that I have only one xAxis category for "TIME" and chart should look like below:
[{"TIME":"2017-09-15","SEX":"MALE","ARIZONA":483280000.0,"IDAHO":6624960.0,"RATE":98.6291686272},
{"TIME":"2017-09-15","SEX":"FEMALE","ARIZONA":1034350000.0,"IDAHO":32409500.0,"RATE":96.8666697274},
{"TIME":"2017-09-16","SEX":"MALE","ARIZONA":482379000.0,"IDAHO":9578100.0,"RATE":98.0144001036},
{"TIME":"2017-09-16","SEX":"FEMALE","ARIZONA":1052960000.0,"IDAHO":40686800.0,"RATE":96.1359744871},
{"TIME":"2017-09-17","SEX":"FEMALE","ARIZONA":1052530000.0,"IDAHO":41476900.0,"RATE":96.0593301937},
{"TIME":"2017-09-17","SEX":"MALE","ARIZONA":1052590000.0,"IDAHO":41479900.0,"RATE":96.0893301937},]
How do we achieve it for the above JSON format..??

First of all, you should use filter method in order to obtain two arrays: one for male and another for female entities.
Then use map method in order to obtain dates, femaleRates and maleRates arrays.
let array=[{"TIME":"2017-09-15","SEX":"MALE","ARIZONA":483280000.0,"IDAHO":6624960.0,"RATE":98.6291686272}, {"TIME":"2017-09-15","SEX":"FEMALE","ARIZONA":1034350000.0,"IDAHO":32409500.0,"RATE":96.8666697274}, {"TIME":"2017-09-16","SEX":"MALE","ARIZONA":482379000.0,"IDAHO":9578100.0,"RATE":98.0144001036}, {"TIME":"2017-09-16","SEX":"FEMALE","ARIZONA":1052960000.0,"IDAHO":40686800.0,"RATE":96.1359744871}, {"TIME":"2017-09-17","SEX":"FEMALE","ARIZONA":1052530000.0,"IDAHO":41476900.0,"RATE":96.0593301937}, {"TIME":"2017-09-17","SEX":"MALE","ARIZONA":1052590000.0,"IDAHO":41479900.0,"RATE":96.0893301937}];
let males=array.filter(a=>a.SEX=='MALE');
let females=array.filter(a=>a.SEX=='FEMALE');
let dates=males.map(a=>a.TIME);
let malesRates=males.map(a=>a.RATE);
let femaleRates=females.map(a=>a.RATE);
console.log(dates);
console.log(malesRates);
console.log(femaleRates);
The last step is to display data in your chart.
let array=[{"TIME":"2017-09-15","SEX":"MALE","ARIZONA":483280000.0,"IDAHO":6624960.0,"RATE":98.6291686272}, {"TIME":"2017-09-15","SEX":"FEMALE","ARIZONA":1034350000.0,"IDAHO":32409500.0,"RATE":96.8666697274}, {"TIME":"2017-09-16","SEX":"MALE","ARIZONA":482379000.0,"IDAHO":9578100.0,"RATE":98.0144001036}, {"TIME":"2017-09-16","SEX":"FEMALE","ARIZONA":1052960000.0,"IDAHO":40686800.0,"RATE":96.1359744871}, {"TIME":"2017-09-17","SEX":"FEMALE","ARIZONA":1052530000.0,"IDAHO":41476900.0,"RATE":96.0593301937}, {"TIME":"2017-09-17","SEX":"MALE","ARIZONA":1052590000.0,"IDAHO":41479900.0,"RATE":96.0893301937}];
let males=array.filter(a=>a.SEX=='MALE');
let females=array.filter(a=>a.SEX=='FEMALE');
let dates=males.map(a=>a.TIME);
let malesRates=males.map(a=>a.RATE);
let femaleRates=females.map(a=>a.RATE);
Highcharts.chart('container', {
xAxis: {
categories:dates
},
series: [{
name: 'Males',
data: malesRates
}, {
name: 'Females',
data:femaleRates
}],
responsive: {
rules: [{
condition: {
maxWidth: 500
},
chartOptions: {
legend: {
layout: 'horizontal',
align: 'center',
verticalAlign: 'bottom'
}
}
}]
}
});
<script src="https://code.highcharts.com/highcharts.js"></script>
<script src="https://code.highcharts.com/modules/series-label.js"></script>
<script src="https://code.highcharts.com/modules/exporting.js"></script>
<div id="container"></div>

Related

Stacked bar chart with chartjs with included values

I am trying to create a visitors bar chart with included values, for example:
I want to show a bar chart of total daily visitors, and that bar should contain info of total visitors and first time visitors.
so data for a bar should look like:
data: {
labels: getDataAttributes(data, 'data-date'),
// an array holding the date of each bar (custom function)
// for example purposes lets say its just 3 bars
datasets: [{
label: ['Number of visitors', 'Number of new visitors'],
data: [[20,15], [25,10], [30, 15]],
// Here if we would use a simple stacked bar chart the height would be the sum of 2 values
// e.g.(20+15=35), but I wish that the bar height would be the number of total visitors 20
// the tooltip should contain values of total visitors and new visitors respectively 20 and 15
}]
}
I looked in the chartjs documentation, but found only examples with stacked values and that solution is not applied in my desired design, can someone please reference documentation/articles/tutorials or personal experience or perhaps I should switch to d3js? Thanks.
You could define two datasets, the first one would contain the values of new visitors, the second one the values of all visitors.
Then you would define the x-axis as being stacked:
options: {
scales: {
xAxes: [{
stacked: true
}],
Please take a look at below runnable code snippet to see how it works:
const baseData = [[20,15], [25,10], [30, 15]];
new Chart('chart', {
type: 'bar',
data: {
labels: ['25.10.2020', '26.10.2020', '27.10.2020'],
datasets: [{
label: 'Number of new visitors',
data: baseData.map(v => v[1]),
backgroundColor: 'green'
},
{
label: 'Number of visitors',
data: baseData.map(v => v[0]),
backgroundColor: 'blue'
}]
},
options: {
scales: {
xAxes: [{
stacked: true
}],
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.min.js"></script>
<canvas id="chart" height="100"></canvas>

Plot a bar graph using Highcharts drilldown with two different JSON end points

I have two JSON end points. I am trying to plot a Highcharts bar graph with drilldown. The drilldown will point to another JSON endpoint. In the graph data is coming dynamically from end points.
JSON 1 :- https://api.myjson.com/bins/156yh3
JSON 1 Structure :-
[{
"name": "cricket",
"number": "2"
}]
It will first plot the graph with JSON 1 Data. In the first graph, X-Axis represents "name" and Y-Axis represents "number". Whenever we click on any bar then it will call the JSON 2 endpoint and pass the clicked bar "name" as URL parameter.
JSON 2 end point looks like, api.domain.com/{{name}}//
if we click on "orange" bar then request url will change to api.domain.com/cricket/
JSON 2 Structure :-
[{
"player": "xyz",
"points": "2"
}]
In the second graph, X-Axis represents "player" and Y-Axis represents "points". I think, I have to call a Ajax request in drilldown when a bar is clicked. I can plot the first graph but what is the recommended way to plot the second graph, which will come in drill down.
Code for graph 1 :-
$(function() {
$.getJSON("https://api.myjson.com/bins/156yh3", function(data) {
console.log(data);
Highcharts.chart('container', {
chart: {
type: 'column'
},
title: {
text: 'Name Vs Numbers'
},
subtitle: {
text: 'Chart View Here'
},
xAxis: {
type: 'category',
categories: data.map(function(x) {
return x.name;
})
},
yAxis: {
title: {
text: 'Numbers'
}
},
legend: {
enabled: false
},
plotOptions: {
series: {
borderWidth: 0,
dataLabels: {
enabled: true,
format: '{point.y:.1f}'
}
}
},
tooltip: {
headerFormat: '<span style="font-size:11px">{series.name}</span><br>',
pointFormat: '<span style="color:{point.color}">{point.name}</span>: <b>{point.y:.2f}</b> of total<br/>'
},
series: [{
colorByPoint: true,
data: data.map(function(x) {
return x.number * 1;
})
}]
});
});
});
HTML :-
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://code.highcharts.com/highcharts.js"></script>
<div id="container" style="min-width: 310px; height: 400px; margin: 0 auto;"></div>
Refer to this live demo: http://jsfiddle.net/kkulig/1o4mr6jk/
It always adds a new drilldown series (with randomly generated data from the API) on point click event and performs drilldown.
In callback for series.point.events.click I used addSeriesAsDrilldown:
plotOptions: {
series: {
point: {
events: {
click: function(e) {
var point = this,
chart = point.series.chart;
$.getJSON('https://canvasjs.com/services/data/datapoints.php?xstart=1&ystart=10&length=10&type=json&callback=?', function(data) {
chart.addSeriesAsDrilldown(point, {
data: data
});
});
}
}
}
}
},
You can use the value of point.name to construct your URL.
It seems that there's some issue with the core code - it throws an error on drillup (you can check that by commenting out everything before var chart = Highcharts.chart('container', {). this.ddDupes in H.Chart.prototype.drillUp function is undefined so its length property cannot be accessed. I modified the core code by changing the following piece of code:
this.ddDupes.length = []; // #3315
to this:
if (this.ddDupes) {
this.ddDupes.length = []; // #3315
}
and everything works fine.
EDIT
I found a better solution. It's based on the official Highcharts demo referred in the API record for chart.events.drilldown: https://api.highcharts.com/highcharts/chart.events.drilldown
Live demo: http://jsfiddle.net/kkulig/u1z5z40b/
var chart = Highcharts.chart('container', {
chart: {
type: 'column',
events: {
drilldown: function(e) {
var chart = this;
$.getJSON('https://canvasjs.com/services/data/datapoints.php?xstart=1&ystart=10&length=10&type=json&callback=?', function(data) {
chart.addSeriesAsDrilldown(e.point, {
data: data
});
});
}
}
},
series: [{
data: [{
name: 'John',
y: 1,
drilldown: true
}, 2],
}]
});
drilldown: true indicates that the drilldown event should happen even though there's no drilldown series explicitly assigned to the point yet.

take an array of objects and put it in a bar graph

i am a new when it comes to jquery and javascript but I'm trying learn slowly.What my question is, if i have a json file that looks like
var data= [{"tasknumber":304030,
"date":"2012-05-05",
"operator":"john doe"},
{"tasknumber":23130,
"date":"2012-07-07",
"operator":"john doeeeeeeee"},
{"tasknumber":233330,
"date":"2012-08-08",
"operator":"john doe"}]
and i applied .countBy to it from the underscore library to get a array that looks like this
{"john doe":2,"john doeeeeeeee":1}
so for the next part im using a sample jquery graph outline which i found online
<!DOCTYPE HTML>
<html>
<head>
<script src="http://canvasjs.com/assets/script/canvasjs.min.js"></script>
<script type="text/javascript">
window.onload = function () {
var chart = new CanvasJS.Chart("chartContainer", {
title:{
text: "My First Chart in CanvasJS"
},
data: [
{
// Change type to "doughnut", "line", "splineArea", etc.
type: "column",
dataPoints: [
{ label: "apple", y: 10 },
{ label: "orange", y: 15 },
{ label: "banana", y: 25 },
{ label: "mango", y: 30 },
{ label: "grape", y: 28 }
]
}
]
});
chart.render();
}
</script>
</head>
<body>
<div id="chartContainer" style="height: 300px; width: 100%;"></div>
</body>
</html>
I tried a couple ways to call my new array within this part of the code
data: [
{
// Change type to "doughnut", "line", "splineArea", etc.
type: "column",
dataPoints: [
//insert here
]
}
]
but i only get blank screens and undefine when i try and open it.does anyone have any guidance for me on how to call my array within the datapoints?
my data is in a different file called task.json and i gotta call it using
var input=require('./task.json');
const _ = require(`underscore`);
var names=_.countBy(input,'operator');
Lets say, your JSON object is stored in some variable(eg: myObject).
var myObject = {"john doe":2,"john doeeeeeeee":1};
Declare a variable to store dataPoints from your JSON and push dataPoints into your array.
var dps = [];
for(var element in myObject) {
dps.push({label: element, y: myObject[element]});
}
Once you have done this, assign this variable (dps) to dataPoints of CanvasJS chart.
data: [
type: "column",
dataPoints: dps
]
You can see a working example in this fiddle.

Highcharts X-axis labels on the side

I'm using Highcharts, and I used to be able to get labels on the side. But it's not working now, am I missing something? The red arrow is where I would want the labels like in the following example.
http://jsfiddle.net/gh/get/jquery/1.9.1/highslide-software/highcharts.com/tree/master/samples/highcharts/demo/bar-basic/
This is the code I'm using, I add the series in a dynamic way.
credits: {
enabled: false
},
chart: {
type: 'bar'
},
xAxis: {
categories: ['Jan', 'Feb'],
labels: {
enabled: true,
}
},
yAxis: {
min: 0,
max: 100,
title: {
text: 'Score',
align: 'high'
}
},
plotOptions: {
bar: {
dataLabels: {
enabled: true
}
}
}
});
// Add Series
var detailchart = $('#chart-detail').highcharts();
var categories = new Array;
// Set Chart Title
detailchart.setTitle({text: results[0].category});
$.each(results, function(i, data){
categories.push(data.name);
detailchart.addSeries({
name: data.name,
data: [data.score]
});
});
detailchart.xAxis[0].setCategories(["1", "2"]);
$('#chart-detail').highcharts().reflow();
Results is an array that looks like this (I get it through ajax):
As I understand from your code here, you wish to specify two categories with names 1 and 2 but you are not specifying any data for second category, So the only category that is showing on your chart is 1. Your data array for each series must have elements per each category. For example if you have two category you should consider having two data elements in each series. In this line data: [data.score] you are just specifying one element in data array. Your code should be something like this: (make it dynamic per your need)
$.each(results, function(i, data){
categories.push(data.name);
detailchart.addSeries({
name: data.name,
data: [data.score, 40], //40 is some data for your second category.
});
});
Demo: http://jsfiddle.net/u6crkatv/
Only what you need is use 4 series, each of them with single data point.
series: [{
name: 'Year 1800',
data: [107]
}, {
name: 'Year 1900',
data: [138]
}, {
name: 'Year 2008',
data: [973]
},{
name: 'Year 20098',
data: [973]
}]
Example: http://jsfiddle.net/y9wzggc4/

Highcharts navigator not working with data set

Can someone please take a look at this example? It works when I use a smaller data set, but when I use a larger historical data set, it stops working and the data series does not render. Please help.
Small data set example - http://jsfiddle.net/Yrygy/250/
Large data set example (SERIES DOES NOT RENDER) - http://jsfiddle.net/Yrygy/249
var chart = new Highcharts.StockChart({
chart: {
renderTo: 'container',
height: 120
},
navigator: {
series: {
data: chartData
}
},
series: [{
data: [null],
markers: {
enabled:true
}
}]
});
You need to have your data sorted in ascending time order. Currently your "large" data set is not.
There is a couple of problems. First of all, as said #wergeld, you need to sort your data:
chartData.sort(function(a,b) { return a[0] - b[0]; });
Then the problem is with setting option for navigator:
navigator: {
series: [{
name: 'MSFT',
data: chartData
}]
},
When should be an object, not an array:
navigator: {
series: {
name: 'MSFT',
data: chartData
}
},
And the last one, do you really need to set xAxis.min/max ? Escpecially to values 2 and 4. when you have timestamps like
Working demo: http://jsfiddle.net/Yrygy/253/

Categories

Resources