chartjs time cartesian axis adapter and date library setup - javascript

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>

Related

Chart.js showing different graphs with select

basically, I have made a Graph that looks like this Image.
I want to make the Graph update whenever I choose an option ( a location in this example). Any idea how could I go on about this?
It sounds like you need to update the chart data whenever the user selects a value from the dropdown. So, add an event listener to the location selector dropdown element, then replace the chart data with the data for the selected location, then call chart update. That part is very simple. It's explained in the chart.js docs under Updating Charts. https://www.chartjs.org/docs/latest/developers/updates.html
For example, if you had location data in an object and a transformData function to convert it to x/y coordinates, you might do something like this for a line chart:
const defaultLocation = 'munchen';
const chart = new Chart(chartCanvas,
{
type: 'line',
data: transformData(locationData[defaultLocation]),
options: {
animation: false,
responsive: true,
maintainAspectRatio: false,
scales: {
y: {
beginAtZero: true,
},
x: {
type: 'timeseries',
},
},
},
});
const locationSelector = document.getElementById("location-selector");
locationSelector.addEventListener('change', ({ target }) => {
chart.data = transformData(locationData[target.value]);
chart.update();
});

Show Labels on Pie pieces instead of Data values Chart.js

I use Chart.js for making charts. I discovered today new plugin for the original Chart.js.
Plugin
After i added <script> tags with the plugin, it applied automatically values to all my charts. It looks great, but it shows number values. How do i make it show labels instead of values on the pieces of the pie? I have found some posts about the subject, but they contain different commands, and i tried all i could but it didn't change anything. Also for the future, tell me please how to turn off showing values for specific chart :)
fillPie()
{
// Three arrays have same length
let labelsArr = []; // Array with some names
let values = []; // Array with values
let randomColor = [];
var ctx = document.getElementById('pie-chart').getContext('2d');
var chart = new Chart(ctx, {
// The type of chart we want to create
type: 'pie',
// The data for our dataset
data: {
labels: labelsArr, // I want it to show these labels
datasets: [{
backgroundColor: randomColor,
data: values, // It shows these values
hoverBackgroundColor: "#fba999"
}]
},
// Configuration options go here
options: {
legend: {
display: false
}
}
});
}
You can find the answer in the docs of the plugin:
https://chartjs-plugin-datalabels.netlify.com/guide/formatting.html#custom-labels
options: {
plugins: {
datalabels: {
formatter: function(value, context) {
return context.chart.data.labels[context.dataIndex];
}
}
}
}
The dev simonbrunel explained on GitHub how you can disable the plugin globally or for specific datasets. The following is a quote from the GitHub link:
That should be possible by disabling labels for all datasets via the plugin options at the chart level using the display option, then enable labels per dataset at the dataset level (dataset.datalabels.*):
new Chart('id', {
data: {
datasets: [{
// no datalabels for this dataset
}, {
datalabels: {
// display labels for this specific dataset
display: true
}
}
},
options: {
plugins: {
datalabels: {
// hide datalabels for all datasets
display: false
}
}
}
})
You can also globally disable labels for all charts using:
// Globally disable datalabels
Chart.defaults.global.plugins.datalabels.display = false

How to dynamically link json data to chart.js

I am trying to create a chart using json data. Currently I have the data within my script, but I would like to link it to a separate .json file within the project folder.
This is what I have currently:
var jsonfile = {
"jsonarray": [{
"name": "Joe",
"age": 12
}, {
"name": "Tom",
"age": 14
}]
};
var labels = jsonfile.jsonarray.map(function(e) {
return e.name;
});
var data = jsonfile.jsonarray.map(function(e) {
return e.age;
});
var ctx = document.getElementById("chart");
var chart = new Chart(ctx, {
type: 'line',
data: {
labels: labels,
datasets: [{
label: 'Graph Line',
data: data,
backgroundColor: 'rgba(0, 119, 204, 0.3)'
}]
}
});
Ideally, I would like the json data to be in a separate file so that it can be dynamically saved.
Thanks :)
You can use the fs module to read and write to a file
var fs = require('fs');
var jsonfile = fs.readFileSync('the/path');
//if you want to write to the file I gave you a link that shows you the way
For more information about the fs module you can check File System | Node.js v12.6.0 Documentation.
You may need to pass by JSON.stringify and JSON.parse to save your object as a string in the file and to parse the string back to an object while reading the file.
Another manner that you may consider is lightweight javascript databases such as IndexedDB which is an embedded database in the browser side, or other databases such as neDB if you want to persist data especially with an electron app.
Have many way to use with your wish
var data = {"a" : "b", "c" : "d"};
then
<script src="data.js" ></script>
or
var json = require('./data.json');
or
$.getJSON("data.json", function(json) {
console.log(json);
});
Good luck!

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
}),

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