Parse Datatime only show YYYY Plot.ly javascript - javascript

I've got a dataset which I am parsing into Plot.ly for use in javascript. The issue i have is that whereas my data is defined as 'yyyy-mm-dd hh:MM:ss' I only see yyyy after the parse. Wher eam i going wrong or what am i missing?
My script looks like this:
processData = function(dataset) {
// Data is in the dataset in a column based format, where each column
has an array of data
// eg. dataset.column_name[0].raw_data,
dataset.column_name[0].formatted_data
data={x: [], y1: [], y2: [], y3: [], y4: []}
for (i=0;i<dataset['datetime'].length;i++){
data['x'].push(parseFloat(dataset['datetime'][i].raw_data));
data['y1'].push(parseFloat(dataset['mp_price'][i].raw_data));
data['y2'].push(parseFloat(dataset['upper'][i].raw_data));
data['y3'].push(parseFloat(dataset['lower'][i].raw_data));
data['y4'].push(parseFloat(dataset['market_price'][i].raw_data));
}
return data
},
doDrawing = function(data, $chartDiv, height, width, errorFunction) {
// Use require to load the javascript libraries you need
// Libraries we ship with and their location:
// js/chartingLibraries/c3/c3
// js/chartingLibraries/chartjs/Chart
// js/chartingLibraries/d3_3.5.17/d3_3.5.17
require(['https://cdn.plot.ly/plotly-latest.min.js'], function(Plotly)
{
var trace1 = {
x: data['x'],
y: data['y1'],
mode: 'markers',
type: 'scatter',
name: 'Trade Price'
};
var trace2 = {
x: data['x'],
y: data['y2'],
mode: 'lines+markers',
type: 'line',
name: 'Upper Threshold'
};
var trace3 = {
x: data['x'],
y: data['y3'],
mode: 'lines+markers',
type: 'line',
name: 'Lower Threshold'
};
var trace4 = {
x: data['x'],
y: data['y4'],
mode: 'lines+markers',
type: 'line',
name: 'Market Price'
};
var layout = {
title: 'Off Market Trades',
xaxis: {
title: 'Year',
showgrid: true,
zeroline: false
},
yaxis: {
title: 'Trade Values and Thresholds',
showline: false
}
};
var data2 = [trace1, trace2, trace3, trace4];
Plotly.newPlot($chartDiv[0], data2, layout);
});
}
One row of data example would be:
datetime: 2018-11-22 09:28:15.0
mp_price: 5.2
market_price: 5.1
lower: 4.8
upper: 5.6

Related

Highcharts, Set XAXIS only show certain time/number

I want to create chart like this with highcharts, it is possible to set xAxis like image below?
I try to use tickpoints and tickinterval but still didn't get the result I wanted
Sample of actual data,
This is result I get now, i want to change xaxis into interval 30 minutes like first image
My code
$.ajax({
url: "",
type: 'GET',
dataType:'json',
success: function(data) {
// console.log(data) ;
var chartSeriesData=[];
var chartCatData=[];
$.each(data, function(i,item){
var series_name = item.time;
var series_data = item.power;
chartSeriesData.push(series_data);
chartCatData.push(series_name);
});
Highcharts.chart('power', {
title: {text: ''},
subtitle: {text: ''},
yAxis: {
title: {text: ''}
// ,min: 0, max: 0.010
},
xAxis: {
categories: chartCatData,
title: {
text: ''
},
labels: {
enabled: true
}
},
legend: {
layout: 'vertical',
align: 'right',
verticalAlign: 'middle'
},
plotOptions: {
series: {
label: {
connectorAllowed: false
}
}
},
series: [
{
// name: 'Power',
data: chartSeriesData
}
],
Result console.log(data)
You should use datetime axis type and format your x values as timestamps in milliseconds.
const chartSeriesData = data.map(
item => [new Date(item.date).getTime(), item.power]
);
Highcharts.chart('container', {
xAxis: {
type: 'datetime',
tickInterval: 1000 * 60 * 30
},
series: [{
data: chartSeriesData
}]
});
Live demo: http://jsfiddle.net/BlackLabel/vzepscjr/
API Reference: https://api.highcharts.com/highcharts/xAxis

Chart.js - Timeline

I am trying to display dates on xAxes with Chart.js
I tried this with 2 dates but it shows nothing.
Probably something I did wrong with the labels or date format.
<canvas id="graph"></canvas>
<script>
var ctx = document.getElementById('graph').getContext('2d');
var myChart = new Chart(ctx, {
type: 'line',
data: {
labels: ["2013-02-08", "2013-02-10"],
datasets: [{
label: "Something",
data: [{
x: "2013-02-08",
y: 1
}, {
x: "2013-02-10",
y: 10
}]
}]
},
options: {
scales: {
xAxes: [{
type: 'time',
time: {
unit: 'day'
}
}]
}
}
});
</script>
Need help :)
Your code looks fine except that you don't need to define data.labels since the data in your dataset is defined as individual points through objects containing x and y properties.
Chart.js internally uses Moment.js for the functionality of the time axis. Therefore you should use the bundled version of Chart.js that includes Moment.js in a single file.
var ctx = document.getElementById('graph').getContext('2d');
var myChart = new Chart(ctx, {
type: 'line',
data: {
datasets: [{
label: "Something",
data: [
{ x: "2013-02-08", y: 1 },
{ x: "2013-02-10", y: 10 }
]
}]
},
options: {
scales: {
xAxes: [{
type: 'time',
time: {
unit: 'day'
}
}]
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.bundle.min.js"></script>
<canvas id="graph"></canvas>

chart.js plotting timeseries

Attempting to pass through data from django to a webpage to render a responsive chart. The data are being passed correctly to js, but I am driving myself crazy trying to understand why charts.js is throwing an error.
I have hardcoded some data for example:
function setLineChart() {
var ctx = document.getElementById("myLineChart").getContext('2d');
var dat_1 = {
label: 'things',
borderColor: 'blue',
data: [
{t: new Date("04/01/2020"), y: 310},
{t: new Date("04/02/2020"), y: 315},
{t: new Date("04/03/2020"), y: 320},
]
};
var myLineChart = new Chart(ctx, {
type: 'line',
data: {
datasets: [dat_1]
},
options: {
scales: {
xAxes: [{
type: 'time',
time: {
unit: 'day'
},
}],
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
})
}
<canvas id="myLineChart" width="600" height="600"></canvas>
And this returns a Uncaught TypeError: Cannot read property 'skip' of undefined error that I can't debug. setLineChart() gets called as part of an ajax response on a form update. When I comment out the options section, it does render a chart, but misses off the last data point, and has undefined as the x-axis marker.
Any help would be appreciated.
Chart.js internally uses Moment.js for the functionality of the time axis. Therefore you should use the bundled version of Chart.js that includes Moment.js in a single file.
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.bundle.min.js"></script>
This will solve your problem as the following amended code snippet illustrates.
var ctx = document.getElementById("myLineChart").getContext('2d');
var dat_1 = {
label: 'things',
borderColor: 'blue',
data: [
{ t: new Date("04/01/2020"), y: 310 },
{ t: new Date("04/02/2020"), y: 315 },
{ t: new Date("04/03/2020"), y: 320 },
]
};
var myLineChart = new Chart(ctx, {
type: 'line',
data: {
datasets: [dat_1]
},
options: {
scales: {
xAxes: [{
type: 'time',
time: {
unit: 'day'
},
}],
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.bundle.min.js"></script>
<canvas id="myLineChart" height="90"></canvas>

Plotly line chart - multiple lines

I want to create a line chart with three lines (male,female,unknown). This is a sample of my data:
timestamp;sex;number
06:00;male;5
07:00;male;2
07:00;unkown;3
07:00;female;4
09:00;female;4
Is there a option in plotly to automatically create the three lines or do I need to loop through the data and create three traces by myself? This is my code so far:
var trace1 = {
type: 'scatter',
x: x,
y: y,
name: "Male",
transforms: [{
type: 'aggregate',
groups: x,
aggregations: [
{target: 'y', func: 'count', enabled: true},
]
}]
};
var data = [trace1];
Plotly.newPlot('myDiv', data, {title: 'Plotting CSV data from AJAX call'});
You need to create different data set(trace) for each category.
Maybe this can help you.
var men = {
x: x,
y: y,
type: 'scatter',
name:'male'
};
var female = {
x: x,
y: y,
type: 'scatter',
'name':'female'
};
var unknown = {
x: x,
y:y,
type: 'scatter',
'name':'unknown'
};
var data = [men, female,unknown];

C3 creating a bar chart with categorical JSON data

How do you specify the x-axis labels for a C3 bar chart with data loaded via JSON? I don't see anything in the docs and the closest I found was this but it only gives an example for data specified in column format, whereas I have data specified in JSON format like in this example
My attempt:
const chart = c3.generate({
data: {
// x: "title",
json: bookData,
type: "bar",
keys: {
value: ["count"]
}
},
axis: {
x: {
tick: {
values: labels,
rotate: 90,
},
type: "category",
}
},
bindto: "#book-title-histogram",
});
By uncommenting x: "title" it leads to the plot to no longer be visible. With that line commented out, the axis is simply blank.
EDIT: bookData is an array with each element having keys count and title
Looks like mapping your data works.
const bookData = [{
count: 3,
title: 'The Foutainhead'
},{
count: 4,
title: 'Fight Club'
},{
count: 2,
title: 'Ender\'s Game'
}]
const titles = bookData.map((obj) => {
return obj.title
})
const counts = bookData.map((obj) => {
return obj.count
})
console.log(titles)
const chart = c3.generate({
data: {
x: 'title',
y: 'count',
json: {
title: titles,
data: counts,
},
type: "bar",
},
axis: {
x: {
tick: {
count: bookData.length,
rotate: 45,
},
type: "category",
}
},
bindto: "#book-title-histogram",
});

Categories

Resources