Reduce the number of lines - javascript

I have defined two charts below for example. But I use more than 50 charts in my code.
The difference between both charts are: chartNumber, containerNumber, id, text and data. Also the condition that is used for checking each chart at the beginning.
Working fiddle of the same: https://jsfiddle.net/2s93zb4j/12/ (pls check all 3 charts to view all of them)
Instead of repeating same lines of code for each chart, will I be able to reduce the number of lines using for loop or forEach. Thank you.
//Chart1
if (checkNA=== "NA")
chart0 = Highcharts.chart('container1', {
id: 1,
yAxis: [{
title: {
text: 'NorthAmerica'
}
}],
series: [{
data: NorthAmericaData,
type: 'line',
}],
});
}
//Chart2
if (checkSA=== "SA")
chart1 = Highcharts.chart('container2', {
id: 2,
yAxis: [{
title: {
text: 'SouthAmerica'
}
}],
series: [{
data: SouthAmericaDta,
type: 'line',
}],
});
}

A class would go a long way here.
class ChartObject {
constructor(id, text, data) {
this.id = id;
this.yAxis = [
{
title: {
text,
},
},
];
this.series = [
{
data,
type: 'line',
},
];
}
}
//Chart1
if (checkNA === 'NA') {
chart0 = Highcharts.chart(
'container1',
new ChartObject(1, 'NorthAmerica', NorthAmericaData)
);
}
//Chart2
if (checkSA === 'SA') {
chart1 = Highcharts.chart(
'container2',
new ChartObject(2, 'SouthAmerica', SouthAmericaDta)
);
}
Hope this helps.

Related

bind first property value of an array of object into chart.js

I have an array of object and this is how I assigned values into it.
$("#gridview").click(function () {
$("table tbody th").each(function () {
var k = $(this).text().trim();
keys.push(k);
});
$("table tbody tr").each(function (i, el) {
var row = {}
$.each(keys, function (k, v) {
row[v] = $("td:eq(" + k + ")", el).text().trim();
});
myData.push(row);
});
myData.shift()
myData.length = 10
console.log(myData);
});
This is how my array of object looks like in inspect element - console
how can I get the values of Region and bind it to the labels below:
new Chart(document.getElementById("chart"), {
type: 'horizontalBar',
data: {
labels: [I want to display all the region here],
datasets: [{
label: "Android",
type: "horizontalBar",
stack: "Base",
backgroundColor: "#eece01",
data: ["I want to display ios user here"],
}, {
label: "ios",
type: "horizontalBar",
stack: "Base",
backgroundColor: "#87d84d",
data: ["I want to display android user here"]
}]
},
options: {
scales: {
xAxes: [{
//stacked: true,
stacked: true,
ticks: {
beginAtZero: true,
maxRotation: 0,
minRotation: 0
}
}],
yAxes: [{
stacked: true,
}]
},
}
});
FYI I have tried myData[Region] but its not working
Guys, I have searched the solutions whole day, seems cant found, please help
You can set the labels using .map() method on myData array like:
data: {
labels: myData.map(d => d.Region),
....
},
EDIT:
You can create a new function and add all chart init code into it like:
function CreateChart() {
new Chart(document.getElementById("chart"), {
type: 'horizontalBar',
data: {
labels: myData.map(d => d.Region),
... you code here
},
...
});
}
CreateChart();
and then on gridview click, again call this CreateChart function in the end like:
$("#gridview").click(function() {
// all your code logic here
console.log(myData);
CreateChart();
});

Problem creating scatter graph using chart.js

I have been trying to create a scatter graph using chart.js, and using data from a JSON object I am fetching from a public api, however my graph is not being created but I am not getting any errors on my console therefore I am unsure as to where the problem is.
This is the structure of my JSON object
0:{
first_name: "Shkodran"
form: "2.3"
points_per_game: "3.2"
now_cost: 51
second_name: "Mustafi"
web_name: "Mustafi"
minutes: 620
goals_scored: 0
assists: 2
clean_sheets: 2
goals_conceded: 9
}
Each entry is a different player and there are 628 entries.
Below is the code I am using
Fetching the public api and parsing the response
var request = new XMLHttpRequest()
var json;
request.open('GET','https://cors- anywhere.herokuapp.com/https://fantasy.premierleague.com/api/bootstrap-static/' , true)
request.onload = function() {
if (request.status >= 200 && request.status < 400) {
json = JSON.parse(this.response);
}
console.log(json);
}
request.send();
Generating the datasets for the scatter graph as I want my graph to be x:now_cost and y:points_per_game.
Creating the chart using chart.js
if (document.readyState === 'complete') {
function generateData() {
var data=[];
json.elements.forEach(elements => {
data.push({
x: elements.now_cost,
y: points_per_game
});
});
return data;
}
var ctx = document.getElementById('chart1').getContext('2d');
var scatterChart = new Chart(ctx, {
type: 'scatter',
data: {
dataset: [{
data: generateData()
}]
},
options: {
title: {
display: true,
text: 'Cost vs Points Per Game Chart'
},
scales: {
xAxes: [{
title:{
display:true,
text: 'Cost'
},
type: 'linear',
position: 'bottom'
}],
yAxes: [{
title:{
display:true,
text: 'Points Per Game'
},
type: 'linear',
position: 'bottom'
}]
}
}
});
}
Your data is not of valid JSON format, individual properties need to be separated by a comma each. There's also an error inside the generateData function with the assignment to the y property. It should be rewritten as follows:
function generateData() {
var data = [];
json.elements.forEach(element => {
data.push({
x: element.now_cost,
y: element.points_per_game
});
});
return data;
}
Or you could even get rid of this function generateData and assign data directly as follows:
dataset: [{
data: json.elements.map(e => ({ x: e.now_cost, y: e.points_per_game }))
}]

Highcharts combination chart from JSON data

I am creating a combination chart taking data from a database. I am able to import all the data and render it in single type i.e. Column. There is one series though which I want to render in spline type. The tutorial I am following only teaches about rendering in a single type, so I am kind of lost here.
This is my JavaScript
$(document).ready(function(){
var options = {
chart: {
renderTo: 'fetch-render',
type: 'column',
},
xAxis: {
title: {
text: 'Date'
},
categories: []
},
yAxis: {
title: {
text: 'Number'
},
series: []
}
$.getJSON("includes/fetch-data.php", function(json) {
options.xAxis.categories = json[0]['data'];
options.series[0] = json[1];
options.series[1] = json[2];
/*so on...... */
options.series[7] = json[8];
/* i want to draw this series in spline */
options.series[8] = json[9];
chart = new Highcharts.Chart(options);
});
})
I want to draw data from series 8 as a spline unlike others which are drawn in column type
Highcharts Demos have all kinds of demos of using Highcharts. One of them shows how to draw different types of series in the same chart: http://jsfiddle.net/gh/get/library/pure/highcharts/highcharts/tree/master/samples/highcharts/demo/combo/
Basically, instead of defining the type on the chart object like you did, you will set the type for each series on your series object:
series: [{
type: 'column',
name: 'Jane',
data: [3, 2, 1, 3, 4]
}, {
type: 'column',
name: 'John',
data: [2, 3, 5, 7, 6]
}, {
type: 'column',
name: 'Joe',
data: [4, 3, 3, 9, 0]
}, {
type: 'spline',
name: 'Average',
data: [3, 2.67, 3, 6.33, 3.33],
marker: {
lineWidth: 2,
lineColor: Highcharts.getOptions().colors[3],
fillColor: 'white'
}
}
Thanks for the heads up by #João Menighin . i adopted the method given in this demo. its neater, cleaner and can be used to add as many chart types as needed. here is the code for someone else who wants to make a combined chart taking data from the database.
$(document).ready(function(){
$.getJSON("includes/fetch-data.php", function(json){
Highcharts.chart('fetch-render', {
title: {
text: 'Fetched Data'
},
xAxis: {
categories: json[0]['data']
},
series: [{
type: json[1]['type'],
name: json[1]['name'],
data: json[1]['data']
}, {
type: json[2]['type'],
name: json[2]['name'],
data: json[2]['data']
}, {
type: json[3]['type'],
name: json[3]['name'],
data: json[3]['data']
},{
type: json[4]['type'],
name: json[4]['name'],
data: json[4]['data']
}, {
type: json[5]['type'],
name: json[5]['name'],
data: json[5]['data']
}, {
type: json[6]['type'],
name: json[6]['name'],
data: json[6]['data']
}, {
type: json[7]['type'],
name: json[7]['name'],
data: json[7]['data']
},{
type: json[8]['type'],
name: json[8]['name'],
data: json[8]['data']
},{
type: json[9]['type'],
name: json[9]['name'],
data: json[9]['data']
}],
});
})
})
And i have set the chart types in fetch-data.php like this
$date = array();
$date['name'] = 'Date';
$blank=array();
$blank['name'] = 'Blank';
$blank['type'] = 'column';
$direct=array();
$direct['name'] = 'Direct';
$direct['type'] = 'area';
$checked_in=array();
$checked_in['name'] = 'Checked In';
$checked_in['type'] = 'column';
$conf=array();
$conf['name'] = 'Conf';
$conf['type'] = 'column';
$gdf=array();
$gdf['name'] = 'GDF';
$gdf['type'] = 'column';
$gdp=array();
$gdp['name'] = 'GDP';
$gdp['type'] = 'column';
$gtn=array();
$gtn['name'] = 'GTN';
$gtn['type'] = 'column';
$prov=array();
$prov['name'] = 'PROV';
$prov['type'] = 'column';
$enquire=array();
$enquire['name'] = 'ENQUIRE';
$enquire['type'] = 'spline';

Formatting dates in HighCharts

I have the following code:
<script>
$.getJSON('https://www.quandl.com/api/v3/datasets/OPEC/ORB.json?order=asc', function(json) {
var hiJson = json.dataset.data.map(function(d) {
return [new Date(d[0]), d[1]]
});
// Create the chart
$('#container').highcharts('chart', {
rangeSelector: {
selected: 1
},
title: {
text: 'OPEC Crude Oil Price',
},
series: [{
type: 'line',
name: 'OPEC',
data: hiJson,
}]
});
});
Which prints a beautiful chart as follows:
OPEC Crude Oil Price
But as you can see, the dates are not in the correct format. I am struggling to work out what is wrong?
All help much appreciated as always!
UPDATE:
So thanks to Holvar's comment I solved one problem, but now I have another on the same theme.
My code is as follows:
<script>
$.getJSON('https://www.quandl.com/api/v3/datasets/BOE/IUAAAMIH.json?auth_token=pg6FBmvfQazVFdUgpqHz&start_date=2003-01-02&order=asc', function(json) {
var hiJson = json.dataset.data.map(function(d) {
return [new Date(d[0]), d[1]]
});
// Create the chart
$('#interest').highcharts('chart', {
xAxis: {
type: 'datetime',
dateTimeLabelFormats: {
day: '%Y'
}
},
rangeSelector: {
selected: 1
},
title: {
text: 'UK Interest Rates',
},
series: [{
type: 'line',
name: 'Interest Rate',
data: hiJson,
}]
});
});
But this produces a chart without dates on the bottom. I'd like years from 2003-01-02. The chart looks like this
UK Interest Rate
I don't understand why it's not showing an annual date as in the solution to the initially posed question?!
You help is much appreciated!
I believe the issue is with the way the data map is happening. The ending array contains multiple arrays, instead of an object with "x" and "y" properties. Try changing the initialization of the hiJson variable to something like:
var hiJson = json.dataset.data.map(function(d) { return { x: new Date(d[0]), y: d[1] }; });
That seems to be working on my local environment.

How do I add secondary axis to highstock charts?

I'm still pretty wet behind the ears when it comes to javascript. I need some help adding a secondary axis that is something like revenue to a highstock chart that also uses $.getJSON (JSONP) to snag a json file to populate the data.
Check out the JSFiddle example here. And here is the sample data set to play with. And finally, an example of secondary axis in Highcharts.
$(function () {
var seriesOptions = [],
seriesCounter = 0,
names = ['MSFT', 'AAPL', 'GOOG'],
// create the chart when all data is loaded
createChart = function () {
$('#container').highcharts('StockChart', {
rangeSelector: {
selected: 4
},
yAxis: {
labels: {
formatter: function () {
return (this.value > 0 ? ' + ' : '') + this.value + '%';
}
},
plotLines: [{
value: 0,
width: 2,
color: 'silver'
}]
},
yAxis: {
floor: 0
},
plotOptions: {
series: {
compare: 'value'
}
},
tooltip: {
pointFormat: '<span style="color:{series.color}">{series.name}</span>: <b>{point.y}</b> ({point.change}%)<br/>',
valueDecimals: 2
},
series: seriesOptions
});
};
$.each(names, function (i, name) {
$.getJSON('http://www.highcharts.com/samples/data/jsonp.php?filename=' + name.toLowerCase() + '-c.json&callback=?', 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();
}
});
});
});
Any help and explanations (so I can learn) is much appreciated. I'm still trying to learn how to tie jsonp and charting together, especially multiple series of data and json files.
Write it like this:
yAxis: [{
labels: { ... },
title: { ... },
...
},
{
labels: { ... },
title: { ... },
...
}]
http://jsfiddle.net/5eem7a2a/1/

Categories