how to use javascript variable for complete series data - javascript

i am generating a Highchart, Instead of assigning each series separately i am assigning all the series data to the variable and assigning this variable to the series section but it is not working.
Here is my code for chart
var seriesdata='{name: '2019',data:[3883,3961,3893,3780,4021,3765,3560,4099,3310,3403,3628,3137,]},{name: '2020',data:[3489,3883,3403,3331,2605,949,]}';
and my assignment of series section in chart is
series: [seriesdata];
but it is not working.
Instead of this if i am using as
series=[{name: '2019',data:[3883,3961,3893,3780,4021,3765,3560,4099,3310,3403,3628,3137,]},{name: '2020',data:[3489,3883,3403,3331,2605,949,]}];
this one is working perfectly.
Kindly help me to solve the issue.

It seems that the data which you are trying to attach is a long string, meanwhile, Highcharts require an array of objects.
Please check this demo: https://jsfiddle.net/BlackLabel/9fzod2ur/
I suggest using this data format:
var seriesdata = [{
name: '2019',
data: [3883, 3961, 3893, 3780, 4021, 3765, 3560, 4099, 3310, 3403, 3628, 3137, ]
},
{
name: '2020',
data: [3489, 3883, 3403, 3331, 2605, 949, ]
}];

Related

chartjs time cartesian axis adapter and date library setup

I am trying to implement this tutorial and could not get it done. https://www.chartjs.org/docs/latest/axes/cartesian/time.html
Input: list of objects with (time,value) attributes. Time is Integer that means unix time in seconds; value is Float.
The tutorial says "Date Adapters. The time scale requires both a date library and a corresponding adapter to be present. Please choose from the available adapters".
Date library, date-fns: https://github.com/date-fns/date-fns
Question 1. how to install/include the date-fns library? The documentation says "npm", but I think it is only for Node.js, but I have a Django project, Ubuntu. If I just download the zip, there is a bunch of files inside.
Adapter, chartjs-adapter-date-fns https://github.com/chartjs/chartjs-adapter-date-fns.
Question 2. how to install the fns adapter? The documentation says "npm", but I have a Django project, Ubuntu. BUT, if I include <script src="https://cdn.jsdelivr.net/npm/chartjs-adapter-date-fns/dist/chartjs-adapter-date-fns.bundle.min.js"></script>, I feel it is enough.
Question 3. after installing adapter and date library, how to fix the script below to make the plot work (Time Cartesian Axis)? I think it is all about updating line point["x"] = elem.time; to convert a unix time to some appropriate type.
HTML
<canvas id="myChart"></canvas>
JS
let points = [];
for(let elem of objs) {
point = {};
point["x"] = elem.time;
point["y"] = elem.value;
points.push(point);
}
var ctx = document.getElementById('myChart').getContext('2d');
var chart = new Chart(ctx, {
// The type of chart we want to create
type: 'line',
// The data for our dataset
data: points,
// Configuration options go here
options: {
responsive: false,
scales: {
x: {
type: 'time',
}
}
}
});
Installing all the 3 required libs can indeed be done using script tags, see live example underneath.
The reason your data doesnt show is because chart.js doesnt expect a data array in the data field. In the data field it expects an object with at least a key for all the datasets which is an array and an optional labels array, but since you are using object format for your data the labels array is not neccesarry.
Each dataset has its own label for the legend and in the dataset object you configure the data array in the data field. See live example:
const options = {
type: 'line',
data: {
datasets: [{
label: '# of Votes',
data: [{
x: 1632664468243,
y: 5
}, {
x: 1632664458143,
y: 10
}],
borderColor: 'pink'
}]
},
options: {
scales: {
x: {
type: 'time'
}
}
}
}
const ctx = document.getElementById('tt').getContext('2d');
new Chart(ctx, options);
<canvas id="tt"></canvas>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.5.1/chart.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/date-fns/1.30.1/date_fns.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chartjs-adapter-date-fns/dist/chartjs-adapter-date-fns.bundle.min.js"></script>

Firebase - JS Query - Get a Node where the Child value has a Child with value=xxx

I ran into a little problem with my firebase queries.
I want to get all series with episodes that i haven't watched yet. At the moment i load them all from firebase and use the filter function in JavaScript. But i would like to minimize the Data Download from firebase a bit.
So i only want the get the series that match this dummycode criteria:
ref("series").orderByChild("seasons/*/episodes/*/episodeWatched").equalTo(false)
This is a small output of my structure in firebase
series >
<unique series id>
seriesName: string
seasons >
seasonCount: number
<season nummer>
episodes >
<episode number>
episodeName: string
episodeWatched: boolean
episodeAirDate: Date
a more "real" exampel would be:
{ series:
[{ 123456:
{ seriesName: "Mr Robot",
seasonCount: 3,
seasons:
[{ 0: episodeCount: 10,
episodes:
[{ 0:
{ episodeName: "Eps1.0_hellofriend.mov",
episodeWatched: true,
episodeAirDate: 27-05-2015 }
{ 1:
{ episodeName: "Eps1.1_ones-and-zer0es.mpeg",
episodeWatched: false,
episodeAirDate: 01-07-2015 }
...
}]
...
}]
}
}]
}
I have a problem with this "wildcards" in my dummycode above, i get only the values of specific nodes, and i can't concat the "orderByChild" function.
If i could concat the function, my aproach to this would be like:
ref("series").orderByChild("seasons").orderByChild("episodes").orderByChild("episodeWatched").equalTo(false)
At the moment i tried several things with wildcards or anything like that, the only thing that works at the moment is:
ref("series").orderByChild("seasons/0/episodes/0/episodeWatched").equalTo(false)
but this only checks: is the first episode of the first season checked.
Did anyone had this problem yet?
I think this is one of those times you duplicate / restructure your db to optimize for reads.
user/uid/notWatched: {
"showId_seasonId_epId": true
}

Converting Poloniex API Callback JSON into format suitable for Highcharts.Stockchart

I am trying to get JSON from Poloniex's public API method (specifically the returnChartData method) to display chart history of cryptocurrencies against one another into a Highchart Stockchart graph (looking like the demo one here.).
This is part of my JavaScript code to use the Poloniex returnChartData callback, get the JSON from it and implement it into the 'data' segment of the chart. So far it is not working and I can't for the life of me figure out what I need to change.
var poloniexUrl = "https://poloniex.com/public?command=returnChartData&currencyPair=BTC_XMR&start=1405699200&end=9999999999&period=14400";
$.getJSON(poloniexUrl, function(data){
results = data;
});
// Creates Chart
var chart = new Highcharts.StockChart({
chart: {
renderTo: 'cryptoChart',
backgroundColor: 'white'
},
title: {
text: currentTitle
},
series: [{
data: results,
turboThreshold: 1000
}],
xAxis: {
original: false
},
rangeSelector: {
selected: 1
},
plotOptions: {
line: {
gapSize: 2
}
}
});
Would love any help!
Refer to this live demo: http://jsfiddle.net/kkulig/0f4odg5q/
If you use turboThreshold the points' options need to be given as an integer or an array (Explanation: https://api.highcharts.com/highstock/plotOptions.series.turboThreshold). In your case the format is JSON, so I disabled turboThreshold to prevent Higcharts error 12 (https://www.highcharts.com/errors/12):
turboThreshold: 0
$.getJSON is asynchronous - the best way to make sure that data variable is initialized is using it inside callback function (second argument of getJSON):
$.getJSON(poloniexUrl, function(data) {
// Creates Chart
var chart = new Highcharts.StockChart({
chart: {
(...)
The data that you fetch looks like candlestick series - I changed the type of the series:
type: 'candlestick'
Date will be properly understood by Highcharts if it's kept in the x property of JSON object (not date):
data: data.map((p) => {
p.x = p.date;
return p
}),

Change label of donut chart in c3js

I've used setting label on start and its working, here is the working code:
var chartDonut1 = c3.generate({
data: {
columns: [
['data1', 30],
['data2', 120],
],
type : 'donut'
},
donut: {
title: "title"
}
});
But, i want to change the label on the donut based on search, and for that purpose i need to use load function.
EDIT:
Here is example of donut chart and with title: LINK
How can label be change/set on load?
I've tried setting like code bellow, but i can't make it work:
chartDonut1.load({
json: dataJsonGraph,
donut: {
title: 'title1',
},
bindto: '#chartDonut1'
});
Any suggestion will be great!
I think the bindto: '#chartDonut1' should be declared inside the generate function.
It seems you cannot change dynamically graph's title inside load function (In c3js documentation, no reference to it).
You will need to select the chart using d3 instance, then change the title. Example:
var label = d3.select('#chart2 text.c3-chart-arcs-title');
label.html(''); // remove existant text
label.insert('tspan').text('30').attr('dy', 0).attr('x', 0).attr('class','big-font');
label.insert('tspan').text('Test Data').attr('dy', 20).attr('x', 0);
A way to change it is to edit html's code : http://plnkr.co/edit/ew5dDA1R3biXnMp80LDd?p=preview

Parsing JSON data for Highcharts

I have been going in circles for a few hours with this and have exhausted all the similar stackoverflow threads and also highcharts docs, so hopefully someone can help.
I am trying to plot a pie chart with a gender split. I have worked with line charts before and so had my data in the format for x and y axis, like this:
[{"y":"Mr","x":"145"},{"y":"Miss","x":"43"},{"y":"Mrs","x":"18"},{"y":"Ms","x":"2"}]
This was getting me somewhere, i could tap into the json and pull out the ints but i couldnt for the life of me get the titles associated with the figures...
function genderData() {
$.getJSON('/statsboard/gender', function(data_g) {
$.each(data_g, function(key_g, val_g) {
obj_g = val_g;
genderChart.series[0].addPoint(parseInt(obj_g.x));
//genderChart.xAxis[0].categories.push(obj_g.y);
});
});
}
I then just called the function genderData as follows:
genderChart = new Highcharts.Chart({
chart: {
renderTo: 'gender',
events: {
load: genderData
}
}
title: {
text: 'Gender Split'
},
plotOptions: {
pie: {
allowPointSelect: true,
cursor: 'pointer',
dataLabels: {
enabled: false
},
showInLegend: true
},
},
series: [{
type: 'pie',
name: 'Gender Split',
data: []
}]
});
So i ended up with an accurate chart but with out the labels, and they would just default to 'slice'...
So close but no cigar ;-)
Soooo i altered my serverside code to return the following format as per the docs :-), now returning the following:
[{"Mr":"145"},{"Miss":"43"},{"Mrs":"18"},{"Ms":"2"}]
This looks pretty much spot on to me, but alas, when i try to accomodate for this on the js code, everything falls apart.
I have been looking at this:
Write JSON parser to format data for pie chart (HighCharts)
but cant get the practice applied here to fit my circumstances.. Can anyone help?
The forms:
[{"name": "Mr", "y": 145}, ...]
or
[["Mr", 145], ...]
will work. Notice the second form is an array of arrays not an array of objects (you were close).
See basic-pie demo (click view options and scroll down to data), series.data docs, and series.addPoint docs for more info.
If you make the server side return the data in one of the two above forms you can just do:
function genderData() {
$.getJSON('/statsboard/gender', function(data_g) {
genderChart.series[0].setData(data_g, true);
});
}
You can set your points as follows:
genderChart.series[0].addPoint({
name: key_g,
y: val_g
});
By rearranging my Json to have "name" and "y" as the keys i was able to make progress i.e:
[{"name":"Mr","y":"145"},{"name":"Miss","y":"43"},{"name":"Mrs","y":"18"},{"name":"Ms","y":"2"}]
Then by looping through the json data and parsing the "y" value as a int with the function parseInt() in the JS i was able to get my desired result...
function genderData() {
$.getJSON('/statsboard/gender', function(data_g) {
$.each(data_g, function(key_g, val_g) {
obj_g = val_g;
genderChart.series[0].addPoint({
name: obj_g.name,
y: parseInt(obj_g.y)
});
console.log(obj_g.y)
});
});
}
I know this question has been solved. but the map function for array might be a good choice in these cases, I love map in functional language!
data = [{"y":"Mr","x":"145"},{"y":"Miss","x":"43"},
{"y":"Mrs","x":"18"},{"y":"Ms","x":"2"}];
var series = data.map(function(e){ return parseInt(e.x); });
.... hight chart ....

Categories

Resources