Date and Time value from Database to be used on axis - javascript

I am trying to add axis labels to my X axis with the date instead of just 1,2,3,4 etc. which it defaults to.
The date_time returned from the server also needs to be converted to a readable date/time.
Any help appreciated.
Code
<script type="text/javascript">
var chart;
var store;
require(["dojo/request/xhr",
"dojo/json",
"dojo/store/Memory",
"dojo/store/Observable",
"dojox/charting/StoreSeries",
"dojox/charting/Chart2D",
"dojox/charting/plot2d/Lines",
"dojox/charting/axis2d/Default",
"dojo/domReady!"],
function(xhr, JSON, Memory, Observable, StoreSeries, Chart) {
xhr("json_result.php",{
handleAs: "json"
}).then(function(data){
store = Observable(new Memory({data: data}));
chart = new Chart("graph");
chart.addPlot("default", {type: "Lines", markers:true});
chart.addAxis("x", {title:"Time", titleOrientation:"away"});
chart.addAxis("y", {vertical: true, majorTick: false, title:"Load"});
chart.addSeries("Load Cell 1", new StoreSeries(store, { query: { load_cell_id:0 }}, "kn"));
chart.addSeries("Load Cell 2", new StoreSeries(store, { query: { load_cell_id:1 } }, "kn"));
chart.render();
});
});
</script>
JSON Result
[{"date_time":1351280845,"load_cell_id":0,"kn":56.8},{"date_time":1351280845,"load_cell_id":1,"kn":45},{"date_time":1351367241,"load_cell_id":0,"kn":23.7},{"date_time":1351367241,"load_cell_id":1,"kn":34.9},{"date_time":1351417945,"load_cell_id":0,"kn":56.9},{"date_time":1351417945,"load_cell_id":1,"kn":67.8},{"date_time":1353914066,"load_cell_id":0,"kn":12.4},{"date_time":1353914066,"load_cell_id":1,"kn":19.43},{"date_time":1353992714,"load_cell_id":0,"kn":45.8},{"date_time":1353992714,"load_cell_id":1,"kn":40.8}]

Try following, its about controlling the indexes (major) and then formatting the data-date_time in a label generating function.
ddl => "dojo/date/locale", require this
chart.addAxis("x", {
title: "Time",
titleOrientation: "away",
includeZero: true,
//from: 0, to: (data.length -1),
minorTicks: false,
labelFunc: function(n){
// I am assuming that your timestamp needs to be multiplied by 1000.
var date = new Date(parseInt(data[n].date_time) * 1000);
return ddl.format(date, {
selector: "date",
datePattern: "dd MMMM"
});
}
});
The minor ticks will produce 0.1, 0.2 additions to the current major tick - and does not go well together with an array indice.

Related

Getting values instead of percentages of dataZoom in Apache Echarts

I am using Apache Echarts, and I have a chart with an X axis of type time, with a dataZoom of type slider. This serves as an example:
var values = [];
for(var i = 0; i < 15; i++) {
var date = new Date();
date.setDate(date.getDate() + i);
values.push([date, i])
}
const firstDate = values[1][0];
const lastDate = values[5][0];
option = {
xAxis: {
type: 'time',
boundaryGap: false,
},
yAxis: {
type: 'value',
},
dataZoom: [{
type: 'slider',
}],
series: [
{
type: 'line',
data: values,
}
]
};
myChart.on('datazoom', (event) => {
console.log(event)
})
In the event I receive 'start' and 'end' as percentages, but what I would like to receive are the actual start and end date. This means, the values of the axis itself.
I checked the docs, and they say that I can actually get the values when "zoom event of triggered by toolbar". I am not sure whether this refers to the toolbox datazoom (which does not fulfill my needs) or any other thing.
Any help would be appreciated.
As F.Marks answered here, you should get the values in dataZoom echart`s option property object like the code below:
myChart.on('dataZoom', function() {
var option = myChart.getOption();
console.log(option.dataZoom[0].startValue, option.dataZoom[0].endValue);
});

Using ECharts visualMap with time axis

I am using Echarts, and I want to color my series (the trends, not the background) with different ranges. The following example is almost what I need:
But with two modifications:
I have a "time" axis instead of a "category" axis.
For the ranges of the series that are not specified in the visualMap, I want them to keep their original, random-generated color.
I just modified the code in the previous example to try to do it, with no luck:
var values = [];
for(var i = 0; i < 15; i++) {
var date = new Date();
date.setDate(date.getDate() + i);
values.push([date, i])
}
const firstDate = values[1][0];
const lastDate = values[5][0];
option = {
xAxis: {
type: 'time',
boundaryGap: false,
},
yAxis: {
type: 'value',
},
visualMap: {
pieces: [{
gt: firstDate,
lte: lastDate,
color: 'green'
}]
},
series: [
{
type: 'line',
data: values,
}
]
};
I just get errors like:
Uncaught DOMException: Failed to execute 'addColorStop' on 'CanvasGradient': The value provided ('undefined') could not be parsed as a color.
t.indexOf is not a function at py (echarts.min.js:formatted:15975)
I do not see any information related with time axes in the visualMap documentation.... any ideas?

How do I add time sourced from an external source as an X axis to a ChartJS graph?

https://plnkr.co/edit/O4BxVsdOZBc4R68p
fetch(target)
.then(response => response.json())
.then(data => {
var prices = data['Time Series (5min)'];
for (prop in prices) {
var stockPrices = prices[prop]['1. open'];
//change to 2. high, etc
console.log(`${prop} : ${stockPrices}`);
stocksData.datasets[0].data.push({x: prop, y: +stockPrices})
//time x axes are preventing render
window.lineChart.update();
}
})
I am getting information from the AlphaVantage API and am trying to graph the time as the X axis and the open price as the Y axis. However, the time from the API is in an odd format and doesn't appear to graph. I have looked into Moment.js but that appears to be making times, not formatting them. Can anyone give me any pointers on graphing the time correct?
Your problem comes from 2 things:
Your Chart config in options with xAxes that should be xAxis instead
Missing Labels and correct data in Chart data
Here is the codes that works:
var stocksData = {
datasets: [
{
label: 'open',
backgroundColor: 'rgba(104,0,255,0.1)',
data: [
],
},
],
};
window.onload = function() {
var ctx = document.getElementById('myChart').getContext('2d');
var lineChart = new Chart(ctx, {
type: 'line',
data: stocksData,
options: {
scales: {
xAxis: [
{
type: 'linear',
position: 'bottom',
},
],
},
},
});
window.lineChart = lineChart;
};
var sym = 'AAPL'; //get from form
var tseries = 'TIME_SERIES_INTRADAY'; //get from form
var target = `https://www.alphavantage.co/query?function=${tseries}&symbol=${sym}&interval=5min&apikey=VA3RZ8B9PPYWKQKN`;
function update () {
fetch(target)
.then(response => response.json())
.then(data => {
var prices = data['Time Series (5min)'];
for (prop in prices) {
var stockPrices = prices[prop]['1. open'];
//change to 2. high, etc
console.log(`${prop} : ${stockPrices}`);
//stocksData.datasets[0].data.push({x: prop, y: +stockPrices})
stocksData.datasets[0].data.push(stockPrices);
// Format date here. For example with Moment:
// var date = moment(prop).format('YYYY-MM-DD')
stocksData.labels.push(prop);
//time x axes are preventing render
window.lineChart.update();
}
})
.catch(error => console.error(error));
}
A complete format for Chart data would be like:
var stocksData = {
labels: ['date1', 'date2', 'date3', 'date4'],
datasets: [
{
label: 'open',
backgroundColor: 'rgba(104,0,255,0.1)',
data: [
'data1', 'data2', 'data3', 'data4'
],
},
],
};
Then each data and date label should be push separately:
stocksData.datasets[0].data.push(stockPrices);
stocksData.labels.push(prop);
To format with Moment you can use:
var dateStr = moment(prop).format('YYYY-MM-DD');
The "odd" time format is (almost) the standard international datetime format. In this case YYYY-MM-DD HH:MM:SS. I strongly suggest you familiarise yourself with it and use it in preference to DD/MM/YYYY or MM/DD/YYYY.
You can fix your code by changing the x-axis type to time and adding the appropriate configuration options:
options: {
scales: {
xAxes: [
{
type: 'time',
...
Note that you'll also need to change your call to Chart.js to the version with moment.js bundled (or include moment separately):
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.bundle.min.js"></script>

HighCharts Playing with YAxis & TimeStamps

I will need to display objects (a doublebar chart for each object). The structure of the object is:
{
dates: (5) ["2018-12-26", "2018-12-27", "2018-12-28", "2018-12-31", "2019-01-02"]
formattedDates: (5) ["2018/12/26", "2018/12/27", "2018/12/28", "2018/12/31", "2019/01/02"]
formatPoints2: (5) [1545945000000, 1546026562061, 1546284847056, 1546465543023, 1546545993086]
points: (5) ["2018-12-27T10:36:24.893", "2018-12-28T17:29:56.517", "2018-12-31T05:48:41.587", "2019-01-01T10:10:09.683", "2019-01-03T10:36:42.002"]
points2: (5) ["2018-12-27T16:10", "2018-12-28T14:49:22.061", "2018-12-31T14:34:07.056", "2019-01-02T16:45:43.023", "2019-01-03T15:06:33.086"]
formatPoints: (5) [1545924984893, 1546036196517, 1546253321587, 1546355409683, 1546529802002]
}
I took the liberty of converting the points and points 2 array using date.getTime() to get the formatPoints and formatPoints2
what I need to do is plot the time of the timestamps vs the dates.
e.g. points[0] = 2018-12-27T10:36:24.893, dates[0] = 2018-12-26
plot 10:36:24 vs 2018-12-26 and so on for each time in the array
an extra catch I need to display the FULL timestamp in the tool-tip (2018-12-27T10:36:24.893) on the chart when you hover over the bar for that point
the chart is a double bar chart where points&points2 is plotted against dates.
In your case the key is to set the right axis types. For timestamp values on yAxis the best type will be datetime and for dates on xAxis - category. Please check the example below and let me know if everything is fine.
var series = [{data: []}, {data: []}];
data.points.forEach(function(point, i){
series[0].data.push({
name: data.formattedDates[i],
tooltipText: data.points[i],
y: data.formatPoints[i]
});
series[1].data.push({
name: data.formattedDates[i],
tooltipText: data.points2[i],
y: data.formatPoints2[i]
});
});
Highcharts.chart('container', {
chart: {
type: 'bar'
},
xAxis: {
type: 'category'
},
tooltip: {
pointFormat: '{point.tooltipText}'
},
yAxis: {
min: 1545945000000,
max: 1546529802002,
type: 'datetime'
},
series: series
});
Live demo: http://jsfiddle.net/BlackLabel/asm64f5r/
API: https://api.highcharts.com/highcharts/xAxis.type

Format Kendo grid column filter for percentages

I have a kendo grid and my datasource data returns number with unknown decimal places. So I'm using a parse function on the datasource to compensate for that.
DefaultMonoCPP: {
editable: false,
type: "number",
parse: function(e) {
return kendo.parseFloat(kendo.toString(e,"p4"));
}
}
Now when I filter, I don't want it to automatically multiply the percentage by 100. So I have filterable set on the columns.
{
field: "DefaultMonoCPP",
title: "Mono Cost",
format: '{0:p4}',
filterable: {
ui: function(e) {
e.kendoNumericTextBox({
//format: "{0:p4}",
//format: "p4",
format: "##.0000 \\%",
decimals: 4
});
}
}
}
But this messes up the filtered number (1.2700% => 1.27). So filtering fails.
JSFiddle for clarification: http://jsfiddle.net/dmathisen/mecny50f/
Is there any way to have both the parse and filterable work correctly together?
My suggestion would be to format the numeric textbox as a percentage and set the step to 0.01 so that it increments/decrements 1% at a time. If you're worried about the user typing in a percentage as a whole number, handle it in the change event.
e.kendoNumericTextBox({
format: '{0:p4}',
step: 0.01,
decimals: 4,
change: function () {
var val = this.value();
if (val > 1) {
this.value(val / 100);
this.trigger("change");
}
}
});
JSFiddle

Categories