ChartJS - Time graph from JSON - javascript

I am returning a JSON to my view and I want to parse the date on a line graph, but I am having some issues with adding dates using ChartJS.
This is my JSON format: (can be changed)
[
{ "y": 4, "x": "2017-01-01" },
{ "y": 0, "x": "2017-01-02" },
{ "y": 9, "x": "2017-01-03" },
{ "y": 0, "x": "2017-01-04" },
{ "y": 14, "x": "2017-01-05" }
]
I tried this but keep getting random timestamps
data: {
labels: [],
datasets: [{
data: [{
y: 0,
x: new Date('2017,03,01')
}, {
y: 1,
x: new Date('2017,03,02')
}, {
y: 2,
x: new Date('2017,03,03')
}],
label: "test",
Does anyone have any idea on how to put the correct dates on the x-axis and place the values on the y-axis? Thanks.

There is an error in Date initialization:
new Date('2017,03,01')
should be replaced by
new Date(2017,03,01)
(without quotes), because '2017,03,01' is a string with an invalid date format.
You can initialize a Date object with a string with the following format (the same you have as input):
new Date('2017-03-01')
In order to trasform the json of your input you can write a function like this:
var input = [{"y":4,"x":"2017-01-01"},
{"y":0,"x":"2017-01-02"},
{"y":9,"x":"2017-01-03"},
{"y":0,"x":"2017-01-04"},
{"y":14,"x":"2017-01-05"}];
var data = input.map(function(item) {
return {x: new Date(item["x"]), y: item["y"]};
});
and pass data to your graph.

Use the json data as is, but tell chart.js that the x axis is time. working fiddle
options: {
"scales": {
"xAxes": [{
"type": "time"
}]
}
}
See http://www.chartjs.org/docs/latest/axes/cartesian/time.html for more time axis configuration options. Especially the parser (tick) property, if using various time and date formats.

Related

Problems Populating Chart.js OHLC Financial Chart from JSON Array (Ajax call from Django model)

Has anyone had success dynamically creating a Chart.js OHLC financial chart from a JSON array? In this case, I'm using an Ajax call to import the data from a Django model:
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.9.1/chart.min.js" integrity="sha512-ElRFoEQdI5Ht6kZvyzXhYG9NqjtkmlkfYk0wr6wHxU9JEHakS7UJZNeml5ALk+8IKlU6jDgMabC3vkumRokgJA==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<script src="https://cdn.jsdelivr.net/npm/chartjs-adapter-date-fns/dist/chartjs-adapter-date-fns.bundle.min.js"></script>
<script src="..\static\stocks\js\chart.js" type="text/javascript"></script>
<canvas id="myChart" width="300" height="175"></canvas>
<script>
let priceArray = []
const endpoint2 = '/api/stockArray/'
$.ajax({
method: 'GET',
url: endpoint2,
success: function(stockArray){
priceArray = stockArray
setChart(priceArray)
}
})
function setChart() {
let testClose = priceArray.map(e => e.data_close)
let testLabels = priceArray.map(e => new Date(e.data_date).setHours(0, 0, 0, 0))
let testOpen = priceArray.map(e => e.data_open)
let testHigh = priceArray.map(e => e.low)
let testLow = priceArray.map(e => e.high)
const data = {
labels: [],
datasets: [{
type: 'ohlc',
label: 'Stocks',
backgroundColor: '#ffffff',
borderColor: '#000000',
data: [
{
x: testLabels,
o: testOpen,
h: testHigh,
l: testLow,
c: testClose,
}
]
}]
}
const config = {
data,
options: {
scales: {
x: {
type: 'timeseries',
time: {
unit: 'day'
}
},
y: {
beginAtZero: true,
max: 3
}
}
}
};
new Chart(
document.getElementById('myChart'),
config
);
}
</script>
I've followed this tutorial (https://www.youtube.com/watch?v=Mzt7IOKnhDw) and successfully created a static OHLC chart. I've also successfully populated a Chart.js line and bar chart dynamically from the same array. In the case of the OHLC chart, I keep getting a RangeError with an Invalid Time Value from the chartjs-adapter-date-fns.bundle. I've tried three methods of populating the x scale from the date values (stored as testLabels) in the array:
let testLabels = priceArray.map(e => new Date(e.data_date).setHours(0, 0, 0, 0))
let testLabels2 = priceArray.map(e => new Date(e.data_date))
let testLabels3 = priceArray.map(e => e.data_date)
Same error every time. If I log these, the values show as
testLabels = [1450328400000, 1450846800000...]
testLabels2 = [Thu
Dec 17 2015 19:00:00 GMT-0500 (Eastern Standard Time), Wed Dec 23
2015 19:00:00 GMT-0500 (Eastern Standard Time)...]
testLabels3 =
['2015-12-18', '2015-12-24'...]
I'll add one more caveat that's throwing me off. If you populate the chart with static values, this code works:
data: [
{
x: new Date ('2022-08-10').setHours(0, 0, 0, 0),
o: 1.00,
h: 1.35,
l: 0.90,
c: 1.20,
},
{
x: new Date ('2022-08-11').setHours(0, 0, 0, 0),
o: 1.00,
h: 1.35,
l: 0.90,
c: 1.20,
}
]
However, if you only pass one object, the chart appears blank:
data: [
{
x: new Date ('2022-08-10').setHours(0, 0, 0, 0),
o: 1.00,
h: 1.35,
l: 0.90,
c: 1.20,
}]
Makes me think it's not entirely a date/time issue with the axis. The tutorial only came out a month ago, so maybe this plugin still needs some development. I'm happy to explore other js libraries, but this is the exact chart style I'm looking for. Happy to provide any additional information. Thanks in advance.
Marking this as answered. I pivoted to canvasjs because I prefer the chart options. But, as I said, you have to push each data point to the end of the array before populating the chart, as shown here (spline instead of OHLC, but same principle):
window.onload = function () {
var chart = new CanvasJS.Chart("chartContainer", {
title: {
text: "Adding & Updating dataPoints"
},
data: [
{
type: "spline",
dataPoints: [
{ y: 10 },
{ y: 4 },
{ y: 18 },
{ y: 8 }
]
}
]
});
chart.render();
$("#addDataPoint").click(function () {
var length = chart.options.data[0].dataPoints.length;
chart.options.title.text = "New DataPoint Added at the end";
chart.options.data[0].dataPoints.push({ y: 25 - Math.random() * 10});
chart.render();

Highcharts update x-axis categories dynamically

i'm looking for help with updating the x-axis categories on a Highcharts chart with periodically received data.
The chart is defined in a file called forecastgraph.html. It is loaded to index.php, the webpage where I want it displayed, by means of <?php require("widget/forecastgraph.html"); ?>. The chart renders as expected.
Live data which is handled via a js script (called mqtt.js) that receives incoming mqtt data in json format and using jquery updates various parts of index.php in this way: $("#elementid").html(a.b.c);. I load mqtt.js in the head of index.php using <script src="./js/mqtt.js"></script> This again works flawlessly.
What I am struggling with is how to pass incoming data from mqtt.js to the chart to update it as new data comes in. Specifically, I am trying to update the xAxis categories and the corresponding value pairs. Periodically, mqtt.js receives a new weather forecast and so the xAxis categories need to be updated with the new time period that the forecast applies to and the data needs to be updated to reflect the new high and low temperatures for the respective forecast periods.
The code for the chart is posted below. Any help would be appreciated.
Baobab
<script type="text/javascript">
$(function () {
$('#forecastgraph').highcharts({
chart: {
type: 'columnrange',
backgroundColor: 'rgba(0,0,0,0)',
borderWidth: 0,
margin: [12, 6, 36, 20]
},
title: {
text: null,
},
exporting: {
enabled: false
},
credits: {
enabled: false
},
xAxis: {
categories: [1,2,3,4],
labels: {
y: 30,
style: {
color: 'white',
fontSize: '10px',
fontWeight: 'bold'
}
}
},
yAxis: {
title: {
enabled: false,
x: -14,
},
labels: {
align: 'left'
},
maxPadding: 0.5,
plotLines: [{
value: 10, //normmax
width: 2,
color: '#FF0000'
},{
value: 2, //normmin
width: 2,
color: '#009ACD'
}]
},
tooltip: {
enabled: false
},
plotOptions: {
columnrange: {
dataLabels: {
enabled: true,
style: {
textOutline: 'none'
},
crop: false,
overflow: 'none',
formatter: function () {
var color = this.y === this.point.high ? '#33C4FF' : 'red';
return '<span style="font-size: 12px; font-family:helvetica; font-weight:normal; text-shadow: none; color:' + color + '">' + this.y + '°</span>';
}
}
}
},
legend: {
enabled: false
},
series: [{
name: 'Temperatures',
data: [
[20, -3],
[5, -2],
[6, -2],
[8, -15]
],
color: '#b9deea',
borderColor: '#92cbde',
borderRadius: 4
}]
});
});
</script>
EDIT: Additional Information.
The incoming json data looks like this:
[{
"period": "Monday",
"condition": "Cloudy",
"high_temperature": "7",
"low_temperature": "-2"
"icon_code": "10",
"precip_probability": "20"
}, {
"period": "Tuesday",
"condition": "A mix of sun and cloud",
"high_temperature": "6",
"low_temperature": "-2"
"icon_code": "02",
"precip_probability": "20"
}, {
"period": "Wednesday",
"condition": "A mix of sun and cloud",
"high_temperature": "3",
"low_temperature": "-5"
"icon_code": "02",
"precip_probability": "20"
}, {
"period": "Thursday",
"condition": "A mix of sun and cloud",
"high_temperature": "1",
"low_temperature": "-10"
"icon_code": "02",
"precip_probability": "20"
}]
The function responsible for the incoming json formatted data in the mqtt.js script loaded to index.php handles the incoming data in this way (mqtt.js is started when index.php is loaded):
function onMessageArrived(message) {
console.log("onMessageArrived: " + message.payloadString);
//Env Canada forecast
if (message.destinationName == "myHome/ec/json_data_ec") {
var data = JSON.parse(message.payloadString);
$("#forecast_period_1").html(data[0].period); // update div forecast_period_1 in index.php for debugging purposes and show that data is coming in
forecast_period_1 = (data[0].period); // assign to global var
forecast_period_1_high = (data[0].high_temperature); // global var
forecast_period_1_low = (data[0].low_temperature); // global var
Updating various html elements throughout index.php with the incoming data works great and is stable. What I have attempted to do, but with no success, is to update the chart using the data placed in the global variables (declared as global at he beginning of the script) by the mqtt.js script. In the example above, forecast_period_1 needs to be used as the first of the four xAxis categories and forecast_period_1_high and forecast_period_1_low, to update the respective hi and lo values in the chart's data.
Is this an output that you want to achieve? In the below demo, I wrote a function that takes a high and low temperatures value and next is triggered on the button. The new data is attached to the chart via using the series.update feature.
Demo: https://jsfiddle.net/BlackLabel/he768cz3/
API: https://api.highcharts.com/class-reference/Highcharts.Series#update
I have found a solution for it. First, you have to store the chart in a variable then after you are able to update chart data. Like below
var chart = $('#forecastgraph').highcharts({ ...option })
Update xAxis or series data
// Update xAxis data label
chart.update({
xAxis: {
categories: [1,2,3,4]
}
});
// Update series data
chart.series[0].update({
data: [
[20, -3],
[5, -2],
[6, -2],
[8, -15]
]
});

plot a bar chart.js time series

I am trying to plot a bar chart with multiple datasets on a time series, however some of the data gets lost along the way.
for simplicity I have removed the ajax call and plotted some data:-
var config = {
type: 'bar',
data: {
datasets: [{
label: "Dataset 1",
data: [{
x: new Date('2017-03-01'),
y: 1
}, {
x: new Date('2017-03-02'),
y: 2
}, {
x: new Date('2017-03-03'),
y: 3
}, {
x: new Date('2017-03-04'),
y: 4
}],
backgroundColor: "red"
}, {
label: "Dataset 2",
data: [{
x: new Date('2017-03-01'),
y: 1
}, {
x: new Date('2017-03-02'),
y: 2
}, {
x: new Date('2017-03-03'),
y: 3
}, {
x: new Date('2017-03-04'),
y: 4
}],
backgroundColor: "blue"
}]
},
options: {
scales: {
xAxes: [{
type: "time",
time: {
unit: 'day',
round: 'day',
displayFormats: {
day: 'MMM D'
}
}
}],
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
}
var ctx = document.getElementById("canvas").getContext("2d");
window.myLine = new Chart(ctx, config);
using the above configuration dataset 1 point 1 and dataset 2 point 4 (so basically the first and last points) do not get drawn.
Any ideas where I am going wrong here?
Also I am using this time series version because I was hoping to have "gaps" in the chart, for example dataset 1 might have a series for 2017-03-01 and dataset 2 might not, in this case dataset 2's next date will bunch up to dataset 1's making it look like it does belong to that date.
Any help would be appreciated
I had the exact same issue when displaying a bar chart with time as the X axes.
Inside your xAxes you need to add an additional configuration option:
xAxes: [{
offset: true
}]
Description from the ChartJS documentation:
If true, extra space is added to the both edges and the axis is scaled to fit into the chart area. This is set to true in the bar chart by default.
ChartJS Documentation Cartesian

Why is HighCharts not recognizing my data properly?

GOAL:
Plot the JSON data on a scatter plot. Each object contain 3 values but the last (the array of IDs) should be ignored -- it is not necessary to represent it on the graph.
PROBLEM:
It seems that HighCharts is not recognizing my x-data. It will not scale the x-axis (datetime) according to my data. It does understand my y-values. And it is represented in the graph.
WHAT ARE YOU DOING?
I'm taking a JSON string, using JSON.parse() on it, making the dates like YYYY-MM-DD instead of UTC, then I'm giving myArray['vector'] to HighChart's data key.
THOUGHTS:
I believe this is related to how I'm structuring the JSON string or how I'm passing it to the key/value pair data. I'm a bit confused as to how JSON data should be 'translated' to a key/value pair.
Below is the result. Note how the x-axis has no ticks. The values are also in order of their position of the array (not by their date)
JSON:
{
"vector":[
[
"2017-06-06T04:31:16.000Z",
0.42,
[
"10155104233200659_10155105320445659",
"10155107157865659_10155107413550659",
"10155100854365659_10155101259520659",
"10155098835305659_10155101265245659",
"10155100854365659_10155101191290659",
"10155100854365659_10155101285415659",
"10155100854365659_10155101300165659",
"10155100854365659_10155101337070659",
"10155100854365659_10155101354640659",
"1558728630806541_1561351187210952",
"10155101928310659_10155102129290659",
"10155100854365659",
"10155101928310659_10155102183210659",
"10155101455910659_10155101458430659",
"1561546217191449_1561590010520403",
"10155101455910659_10155101459025659",
"10155101455910659_10155101461415659",
"10155101455910659_10155102138275659",
"10155101928310659_10155102150395659",
"10155101455910659_10155101462715659",
"870299173970694144",
"10155101455910659_10155101466670659",
"10155100854365659_10155101699660659",
"10155100854365659_10155102227220659",
"10155100854365659_10155102338105659",
"10155101928310659_10155102363275659",
"10155101455910659_10155101723225659",
"1561432737202797",
"10155101928310659_10155102372445659",
"10155101455910659_10155101481925659"
]
],
[
"2017-06-01T03:06:45.000Z",
0.47,
[
"10155078962635659_10155088932395659",
"10155086108505659_10155086203305659",
"10155086108505659_10155086234940659",
"10155085853500659_10155089736675659",
"10155086108505659_10155086284290659",
"10155086108505659_10155086294655659",
"868637256197840896",
"10155086108505659_10155086299195659",
"10155089549730659_10155089737300659",
"10155086108505659_10155086390050659",
"10155086108505659_10155086391925659",
"10155080256225659_10155089749815659",
"10155089549730659_10155090102235659",
"10155089549730659_10155090105425659",
"10155089549730659_10155090154310659",
"10155089549730659_10155090160515659",
"10155089549730659_10155090191730659",
"10155089549730659_10155090365070659",
"10155041106080659_10155086572640659",
"10155086108505659_10155086121160659",
"10155086108505659_10155086155370659",
"10155085853500659_10155086166860659",
"10155086108505659_10155086173400659",
"10155086108505659_10155086176665659",
"10155086108505659_10155086186500659",
"10155086108505659_10155086189325659",
"10155086108505659_10155086193075659",
"10155086108505659_10155086197225659",
"10155086108505659_10155086635920659",
"10155086108505659_10155087687155659"
]
],
[
"2017-05-26T03:32:24.000Z",
0.43,
[
"10155076988775659_10155077020050659",
"10155076988775659_10155077018590659",
"10155076988775659_10155077016610659",
"10155076988775659_10155077018385659",
"10155076988775659_10155077016860659",
"10155076988775659_10155077016865659",
"10155076988775659_10155077018410659",
"10155076988775659_10155077016530659",
"10155076988775659_10155077015135659",
"10155076988775659_10155077017130659",
"10155076988775659_10155077016630659",
"10155076988775659_10155077015210659",
"10155076988775659_10155077015205659",
"10155076988775659_10155077018990659",
"10155076988775659_10155077015255659",
"10155076988775659_10155077017270659",
"10155076988775659_10155077013155659",
"10155076988775659_10155077016690659",
"10155076988775659_10155077019325659",
"10155076988775659_10155077017305659",
"10155076988775659_10155077017385659",
"10155076677150659_10155077073125659",
"10155076677150659_10155077036660659",
"10155076988775659_10155077017615659",
"10155076988775659_10155077019365659",
"10155076988775659_10155077017695659",
"10155076988775659_10155077017680659",
"10155076988775659_10155077017780659",
"10155076988775659_10155077017760659",
"10155076568000659_10155077074260659"
]
],
[
"2017-05-07T03:02:04.000Z",
0.8,
[
"15a1e146e7ed603aecbe16de25ed53fc",
"10155015378740659_10155015486550659",
"10155011834555659_10155013722600659",
"10155015378740659_10155015483050659",
"10155012171695659_10155022393165659",
"859973050628026368",
"860299410340630528",
"860096826610941952",
"859989850455408642",
"7d79e45313c878ec78a0b34de60c69f3",
"860127021120327680",
"860300107266138112",
"860311173073391617",
"860312531407163393",
"860316615765876736",
"860156681401114626",
"860317260409257985",
"Qd_q0XF0Y10",
"860166160851099649",
"860190399180222466",
"860204548777889792",
"860211634886901760",
"1529799180366153_1532172110128860",
"860269305077870592",
"860287769960165376",
"860297098775982082",
"860162336727977985",
"10155014502490659_10155016027360659",
"1532221810123890_1533617433317661",
"10155015378740659_10155015420560659"
]
],
[
"2017-05-04T03:08:33.000Z",
0.55,
[
"10155005822955659_10155006234215659",
"10155005822955659_10155006238455659",
"10155005609550659_10155006194705659",
"10155005822955659_10155006241065659",
"10155005822955659_10155006241655659",
"10155005822955659_10155006177605659",
"10155005114840659_10155006201270659",
"10155005609550659_10155006091430659",
"10155005609550659_10155006095520659",
"10155005609550659_10155006099105659",
"10155002652900659_10155006101040659",
"10155005822955659_10155006101600659",
"10155005609550659_10155006109155659",
"10155002652900659_10155006110655659",
"10155005822955659_10155006113965659",
"10155005609550659_10155006132275659",
"10155005609550659_10155006139910659",
"10155005822955659_10155006142495659",
"10155005609550659_10155006143850659",
"10154997175925659_10155006178085659",
"10155005822955659_10155006148580659",
"10155005609550659_10155006190080659",
"10155005114840659_10155006154345659",
"10155005822955659_10155006154825659",
"10155005114840659_10155006167935659",
"10155005609550659_10155006157700659",
"10155005114840659_10155006160225659",
"10155005609550659_10155006231175659",
"10155005609550659_10155006187295659",
"10155005822955659_10155006162850659"
]
],
[
"2017-05-02T03:01:57.000Z",
0.49,
[
"874302750531694592",
"851862555752640513",
"851862767925637120",
"874318907250757634",
"874329266107936768",
"874335249144086531",
"851870647521341443",
"874107458871894021",
"851772861501059072",
"874355138969956352",
"874250856476139520",
"874274312253034496",
"874278730088280066",
"874356894428798977",
"851893814474264576",
"874666827904937985",
"851923766158520320",
"851891395493101568",
"874684725188845572",
"874685434911236098",
"874391730396708864",
"874396116737019909",
"874737533766311937",
"874799536073519104",
"874817322791313409",
"851892924115582977",
"874396860777091072",
"874551209625100288",
"874558005903335424",
"874609184905588736"
]
],
[
"2017-04-11T03:04:21.000Z",
0.54,
[
"872880479300603905",
"872905370355855361",
"872914304227475460",
"872661418985877506",
"872662404416638976",
"872922590024794115",
"872923180117241856",
"872967240488034305",
"872980087943176193",
"872989868145741829",
"872997173008486402",
"872880235649392640",
"873003042869792790",
"872941776868433921",
"873004432853696512",
"872841099542450178",
"872767600647954435",
"872819121804726272",
"872940586894061568",
"872985706150350848",
"872762907746066432",
"872869944161165312",
"872880243824103424",
"872846343147999233",
"873015156883812353",
"872938894320390145",
"872655599145824256",
"873351602639384576",
"873352989515403264",
"ea4b7c58ceee69909aad70a8d25f46ef"
]
]
]
}
JavaScript and HighCharts initialization:
var myJSON = '{"vector":[["2017-06-06T04:31:16.000Z",0.42,["10155104233200659_10155105320445659","10155107157865659_10155107413550659","10155100854365659_10155101259520659","10155098835305659_10155101265245659","10155100854365659_10155101191290659","10155100854365659_10155101285415659","10155100854365659_10155101300165659","10155100854365659_10155101337070659","10155100854365659_10155101354640659","1558728630806541_1561351187210952","10155101928310659_10155102129290659","10155100854365659","10155101928310659_10155102183210659","10155101455910659_10155101458430659","1561546217191449_1561590010520403","10155101455910659_10155101459025659","10155101455910659_10155101461415659","10155101455910659_10155102138275659","10155101928310659_10155102150395659","10155101455910659_10155101462715659","870299173970694144","10155101455910659_10155101466670659","10155100854365659_10155101699660659","10155100854365659_10155102227220659","10155100854365659_10155102338105659","10155101928310659_10155102363275659","10155101455910659_10155101723225659","1561432737202797","10155101928310659_10155102372445659","10155101455910659_10155101481925659"]],["2017-06-01T03:06:45.000Z",0.47,["10155078962635659_10155088932395659","10155086108505659_10155086203305659","10155086108505659_10155086234940659","10155085853500659_10155089736675659","10155086108505659_10155086284290659","10155086108505659_10155086294655659","868637256197840896","10155086108505659_10155086299195659","10155089549730659_10155089737300659","10155086108505659_10155086390050659","10155086108505659_10155086391925659","10155080256225659_10155089749815659","10155089549730659_10155090102235659","10155089549730659_10155090105425659","10155089549730659_10155090154310659","10155089549730659_10155090160515659","10155089549730659_10155090191730659","10155089549730659_10155090365070659","10155041106080659_10155086572640659","10155086108505659_10155086121160659","10155086108505659_10155086155370659","10155085853500659_10155086166860659","10155086108505659_10155086173400659","10155086108505659_10155086176665659","10155086108505659_10155086186500659","10155086108505659_10155086189325659","10155086108505659_10155086193075659","10155086108505659_10155086197225659","10155086108505659_10155086635920659","10155086108505659_10155087687155659"]],["2017-05-26T03:32:24.000Z",0.43,["10155076988775659_10155077020050659","10155076988775659_10155077018590659","10155076988775659_10155077016610659","10155076988775659_10155077018385659","10155076988775659_10155077016860659","10155076988775659_10155077016865659","10155076988775659_10155077018410659","10155076988775659_10155077016530659","10155076988775659_10155077015135659","10155076988775659_10155077017130659","10155076988775659_10155077016630659","10155076988775659_10155077015210659","10155076988775659_10155077015205659","10155076988775659_10155077018990659","10155076988775659_10155077015255659","10155076988775659_10155077017270659","10155076988775659_10155077013155659","10155076988775659_10155077016690659","10155076988775659_10155077019325659","10155076988775659_10155077017305659","10155076988775659_10155077017385659","10155076677150659_10155077073125659","10155076677150659_10155077036660659","10155076988775659_10155077017615659","10155076988775659_10155077019365659","10155076988775659_10155077017695659","10155076988775659_10155077017680659","10155076988775659_10155077017780659","10155076988775659_10155077017760659","10155076568000659_10155077074260659"]],["2017-05-07T03:02:04.000Z",0.8,["15a1e146e7ed603aecbe16de25ed53fc","10155015378740659_10155015486550659","10155011834555659_10155013722600659","10155015378740659_10155015483050659","10155012171695659_10155022393165659","859973050628026368","860299410340630528","860096826610941952","859989850455408642","7d79e45313c878ec78a0b34de60c69f3","860127021120327680","860300107266138112","860311173073391617","860312531407163393","860316615765876736","860156681401114626","860317260409257985","Qd_q0XF0Y10","860166160851099649","860190399180222466","860204548777889792","860211634886901760","1529799180366153_1532172110128860","860269305077870592","860287769960165376","860297098775982082","860162336727977985","10155014502490659_10155016027360659","1532221810123890_1533617433317661","10155015378740659_10155015420560659"]],["2017-05-04T03:08:33.000Z",0.55,["10155005822955659_10155006234215659","10155005822955659_10155006238455659","10155005609550659_10155006194705659","10155005822955659_10155006241065659","10155005822955659_10155006241655659","10155005822955659_10155006177605659","10155005114840659_10155006201270659","10155005609550659_10155006091430659","10155005609550659_10155006095520659","10155005609550659_10155006099105659","10155002652900659_10155006101040659","10155005822955659_10155006101600659","10155005609550659_10155006109155659","10155002652900659_10155006110655659","10155005822955659_10155006113965659","10155005609550659_10155006132275659","10155005609550659_10155006139910659","10155005822955659_10155006142495659","10155005609550659_10155006143850659","10154997175925659_10155006178085659","10155005822955659_10155006148580659","10155005609550659_10155006190080659","10155005114840659_10155006154345659","10155005822955659_10155006154825659","10155005114840659_10155006167935659","10155005609550659_10155006157700659","10155005114840659_10155006160225659","10155005609550659_10155006231175659","10155005609550659_10155006187295659","10155005822955659_10155006162850659"]],["2017-05-02T03:01:57.000Z",0.49,["874302750531694592","851862555752640513","851862767925637120","874318907250757634","874329266107936768","874335249144086531","851870647521341443","874107458871894021","851772861501059072","874355138969956352","874250856476139520","874274312253034496","874278730088280066","874356894428798977","851893814474264576","874666827904937985","851923766158520320","851891395493101568","874684725188845572","874685434911236098","874391730396708864","874396116737019909","874737533766311937","874799536073519104","874817322791313409","851892924115582977","874396860777091072","874551209625100288","874558005903335424","874609184905588736"]],["2017-04-11T03:04:21.000Z",0.54,["872880479300603905","872905370355855361","872914304227475460","872661418985877506","872662404416638976","872922590024794115","872923180117241856","872967240488034305","872980087943176193","872989868145741829","872997173008486402","872880235649392640","873003042869792790","872941776868433921","873004432853696512","872841099542450178","872767600647954435","872819121804726272","872940586894061568","872985706150350848","872762907746066432","872869944161165312","872880243824103424","872846343147999233","873015156883812353","872938894320390145","872655599145824256","873351602639384576","873352989515403264","ea4b7c58ceee69909aad70a8d25f46ef"]]]}';;
var myArray = JSON.parse(myJSON);
$.each(myArray['vector'],function(index, value){
//Reduce the datetime to just YYYY-MM-DD
myArray['vector'][index][0] = myArray['vector'][index][0].substring(0,10);
});
$(document).ready(function(){
Highcharts.setOptions({
global: {
useUTC: false
}
});
Highcharts.chart('container', {
chart:{
zoomType:'x',
},
exporting: {
enabled: false
},
xAxis: {
type: 'datetime',
title:{text:'Time'},
tickInterval: 1000 * 60 * 60 * 24
},
yAxis: {
max:1,
min: 0,
title:{ text: 'Focus of Conversations'},
plotBands: [{
color: 'black',
from: .5, // Start of the plot band
to: .51 // End of the plot band
}]
},
title: {
text: 'Focus of Conversations Over Time'
},
series: [
{
type: 'scatter',
data: myArray['vector'],
marker: { radius: 8 },
showInLegend: false
}]
});
});
Issue solved. I converted my YYYY-MM-DD dates into seconds since the epoch and everything worked fine.
I changed this...
$.each(myArray['vector'],function(index, value){
//Reduce the datetime to just YYYY-MM-DD
myArray['vector'][index][0] = myArray['vector'][index][0].substring(0,10);
});
to this...
$.each(myArray['vector'],function(index, value){
//Reduce the datetime to just YYYY-MM-DD
console.log(myArray['vector'][index][0].substring(0,10));
myArray['vector'][index][0] = (new Date(myArray['vector'][index][0].substring(0,10))).getTime();
});

time scatter plot w/ chart.js

I'm trying to render a scatter plot in chart.js of (x,y) data where x is a date string. I've seen many examples and tutorials online where the instructor uses a function to generate the time stamp for an example chart, but I haven't found any examples that use real data like one might collect.
I have data that looks like this (collected from cron):
2017-07-08T06:15:02-0600,23.375
2017-07-08T06:20:02-0600,23.312
2017-07-08T06:25:02-0600,23.312
2017-07-08T06:30:02-0600,23.25
I tried a data like this in chart.js (both with and without "quotes" around the data string):
data: [{
x: 2017-07-08T06:15:02-0600,
y: 23.375
},{
x: 2017-07-08T06:20:02-0600,
y: 23.312
},{
x: 2017-07-08T06:25:02-0600,
y: 23.312
},{
x: 2017-07-08T06:30:02-0600,
y: 23.25
}],
Nothing renders. What am I doing wrong?
According to the documentation of scatter charts:
Unlike the line chart where data can be supplied in two different formats, the scatter chart only accepts data in a point format.
So you can't use values like 2017-07-08T06:15:02-0600. You can convert dates into numbers and use them in your data.
In your case:
data: [{
x: 1499516102000,
y: 23.375
}, {
x: 1499516402000,
y: 23.312
}, {
x: 1499516702000,
y: 23.312
}, {
x: 1499517002000,
y: 23.25
}
]
Now your xAxes will be with numbers, so you can use a callback to modify xAxes labels.
That advice isn't quite right. The javascript moment.js makes it possible to plat scatter data using dates as the x axis value. For some reason the bundled version in Chart.bundle.js wasn't working for me, so I downloaded moment.js directly. I'm using this to setup:
<script src="js/moment.js"></script>
<script src="js/Chart.min.js"></script>
and this for my chart.js data details:
data: [
{x: moment("2017-07-08T06:15:02-0600"), y: 23.375},
{x: moment("2017-07-08T06:20:02-0600"),y: 23.312},
{x: moment("2017-07-08T06:25:02-0600"),y: 23.312},
{x: moment("2017-07-08T06:30:02-0600"),y: 23.25}
],
It's working great!
Another solution that worked great for me, was to just use the line type for the chart, configure it for using dates for the x axis, and addtionally disable the lines, so that it just looks like a scatterplot.
new Chart(ctx, {
type: 'line',
data: {
datasets: [{
x: 2017-07-08T06:15:02-0600,
y: 23.375
},{
x: 2017-07-08T06:20:02-0600,
y: 23.312
},{
x: 2017-07-08T06:25:02-0600,
y: 23.312
},{
x: 2017-07-08T06:30:02-0600,
y: 23.25
}]
},
options: {
showLine: false,
scales: {
x:{
type: 'time',
display: true,
title: {
display: true,
text: 'Date'
},
},
}
}
}
);
I see this as a quite elegant solution. The documentation even specifies:
The scatter chart supports all of the same properties as the line chart. By default, the scatter chart will override the showLine property of the line chart to false.
I couldn't find a working example from these answers, so here's mine.
new Chart(document.getElementById("chart"), {
type: "line",
data: {
datasets: [
{
showLine: false,
fill: false,
data: [
{
x: new Date(Date.now()),
y: 100,
},
{
x: new Date(Date.now() + 1000 * 60 * 60),
y: 200,
},
{
x: new Date(Date.now() + 2000 * 60 * 60),
y: 300,
},
{
x: new Date(Date.now() + 3000 * 60 * 60),
y: 400,
},
],
},
],
},
options: {
plugins: {
legend: {
display: false,
},
title: {
text: "Chart.js Time Scale",
display: true,
},
},
scales: {
x: {
type: "time",
time: {
unit: "hour",
// Luxon format string
// tooltipFormat: "DD T",
},
title: {
display: true,
text: "Hour",
},
},
y: {
title: {
display: true,
text: "value",
},
},
},
},
});
I pulled it from here: https://www.chartjs.org/docs/latest/samples/scales/time-line.html
You'll need to install momentjs and its adapter:
npm install moment chartjs-adapter-moment --save
..and then import all libraries like
import Chart from "chart.js/auto";
import "chartjs-adapter-moment";

Categories

Resources