I'm trying to implement highcharts, but having difficulties in mapping the JSON data correctly.
Fiddle: https://jsfiddle.net/AndreasBren/vux52sL4/11/
var endpoint = '/api/chart/data/'
var label = []
var start = []
var end = []
var werk = []
$.ajax({
method: 'GET',
url: endpoint,
success: function(data) {
labels = data.label
start = data.start
end = data.end
uplant = data.werk
const forstart = start;
const newstart = forstart.map((str) => {
const [year, month, date] = str.split("-");
return `${date}.${month}.${year}`;
});
// console.log(newstart); "01.01.2019"
var dates = newstart.map(function(str) {
return new Date(str);
});
var sdates_ms = dates.map(function(date) {
return date.getTime();
});
const forend = end;
const newend = forend.map((str) => {
const [year, month, date] = str.split("-");
return `${date}.${month}.${year}`;
});
// console.log(newend); // "03.01.2019"
var dates = newend.map(function(str) {
return new Date(str);
});
var edates_ms = dates.map(function(date) {
return date.getTime();
});
var obj = {}
var finalArray = []
for (var i = 1; i <= start.length; i++) {
var first = {
name: uplant[i]
}
obj = {
...obj,
...first
}
var data = {
start: sdates_ms[i - 1],
end: edates_ms[i - 1],
name: labels[i],
y: 0
}
if (obj.data) {
obj.data.push(data)
} else {
obj.data = [data]
}
finalArray.push(obj)
}
day = 1000 * 60 * 60 * 24
var chart = Highcharts.ganttChart('container', {
chart: {
spacingLeft: 1,
scrollablePlotArea: {
minWidth: 700,
scrollPositionX: 0
}
},
title: {
text: 'Gantt Visualisation'
},
subtitle: {
text: ''
},
plotOptions: {
series: {
animation: true,
dragDrop: {
draggableX: true,
draggableY: true,
dragPrecisionX: day / 3
},
dataLabels: {
enabled: false,
format: '{point.name}',
style: {
cursor: 'default',
pointerEvents: 'none'
}
},
allowPointSelect: true,
}
},
scrollbar: {
enabled: true
},
yAxis: {
type: 'category',
categories: uplant,
},
xAxis: {
currentDateIndicator: true,
},
tooltip: {
xDateFormat: '%a %b %d, %H:%M'
},
series: finalArray,
scrollbar: {
enabled: true,
barBackgroundColor: 'gray',
barBorderRadius: 7,
barBorderWidth: 0,
buttonBackgroundColor: 'gray',
buttonBorderWidth: 0,
buttonArrowColor: 'yellow',
buttonBorderRadius: 7,
rifleColor: 'yellow',
trackBackgroundColor: 'white',
trackBorderWidth: 1,
trackBorderColor: 'silver',
trackBorderRadius: 7
}
});
},
error: function(error_data) {
console.log("error")
console.log(error_data)
}
});
Result:
One row contains all plants and all orders
Row 1 > Plant 1, Plant 2, ... > Order 1, Order 2, ...
Expected Result:
Each row stands for one plant and contains the orders of this plant
Row 1 > Plant 1 > Order 1
Row 2 > Plant 2 > Order 2
....
Fiddle: https://jsfiddle.net/AndreasBren/vux52sL4/11/
Thank you very much for any help!
There is a lot of confusion in your code. The main reason that all the orders appear to the first row, is because you're setting the y:0 inside the data binding loop. Also you start the for loop index from 1 which is unnecessary and leads to unwanted behavior. There is a much more cleaner and simple way to make the data object like this:
labels = ["Workorder1","Workorder2"]
start = ["2001.02.01","2002.02.10"]
end = ["2001.03.02","2002.03.10"]
uplant = ["Plant A","Plant B"]
const makeDate = str => {
const [year, month, date] = str.split(".")
return new Date(`${month}.${date}.${year}`).getTime()
}
const finalArray = start.map((s, i) => ({
name: labels[i],
start: makeDate(s),
end: makeDate(end[i]),
y: i
}))
define the yAxis like this:
yAxis: {
type: 'category',
categories: uplant,
min: 0,
max: uplant.length - 1
},
and the series like this:
series: [{ data: finalArray }]
Check my working fiddle: https://jsfiddle.net/lytrax/hyq206xt/26/
Related
Im dealing with this problem.
I have smoothed line chart from amcharts v5.
And everything is working properly until i want to add second line to the chart. It only displays one line chart. And i need to add second line to the same chart.
If I change data values to another chart. It is working fine but same problem, only one line.
So my question is, how to add second line into same chart.
am5.ready(function() {
// Create root element
// https://www.amcharts.com/docs/v5/getting-started/#Root_element
var root = am5.Root.new("chartdiv");
// Set themes
// https://www.amcharts.com/docs/v5/concepts/themes/
root.setThemes([
am5themes_Animated.new(root)
]);
// Create chart
// https://www.amcharts.com/docs/v5/charts/xy-chart/
var chart = root.container.children.push(am5xy.XYChart.new(root, {
panX: true,
panY: true,
wheelX: "panX",
wheelY: "zoomX",
pinchZoomX:true
}));
// Add cursor
// https://www.amcharts.com/docs/v5/charts/xy-chart/cursor/
var cursor = chart.set("cursor", am5xy.XYCursor.new(root, {
behavior: "none"
}));
cursor.lineY.set("visible", false);
function generateDataInvestice(roky,investice) {
value = investice;
return {
date: roky,
value: value
};
}
function generateDatasInvestice(count,i) {
var data = [];
var investice = 5;
for (var i = 1; i < count; ++i) {
data.push(generateDataInvestice(i,investice));
}
return data;
}
//generate uver
function generateDataUver(roky,uver) {
value = uver;
return {
date: roky,
value: value
};
}
function generateDatasUver(count,i) {
var data = [];
var uver = 1;
for (var i = 1; i < count; ++i) {
data.push(generateDataUver(i,uver));
}
return data;
}
// Create axes
// https://www.amcharts.com/docs/v5/charts/xy-chart/axes/
var xAxis = chart.xAxes.push(am5xy.ValueAxis.new(root, {
maxDeviation: 1,
baseInterval: {
count: 1
},
renderer: am5xy.AxisRendererX.new(root, {
pan:"zoom"
}),
tooltip: am5.Tooltip.new(root, {})
}));
var yAxis = chart.yAxes.push(am5xy.ValueAxis.new(root, {
maxDeviation:1,
renderer: am5xy.AxisRendererY.new(root, {
pan:"zoom"
})
}));
// Add series
// https://www.amcharts.com/docs/v5/charts/xy-chart/series/
var series = chart.series.push(am5xy.SmoothedXLineSeries.new(root, {
name: "Series",
xAxis: xAxis,
yAxis: yAxis,
valueYField: "value",
valueXField: "date",
tooltip: am5.Tooltip.new(root, {
labelText: "{valueY}"
})
}));
series.fills.template.setAll({
visible: true,
fillOpacity: 0.2
});
series.bullets.push(function() {
return am5.Bullet.new(root, {
locationY: 0,
sprite: am5.Circle.new(root, {
radius: 4,
stroke: root.interfaceColors.get("background"),
strokeWidth: 2,
fill: series.get("fill")
})
});
});
var data = generateDatasInvestice(30,0);
var data_uver = generateDatasUver(30,0);
series.data.setAll(data,data_uver);
series.appear(30);
chart.appear(1000, 100);
}); // end am5.ready()
Here is working soluiton on codepen: https://codepen.io/tom-august/pen/KKQLgbm
Thanks a lot.
In your data, you should have several value fields like so:
var data = [
{
date: new Date("2022-12-27").getTime(),
value1: 10,
value2: 20
},
{
date: new Date("2022-12-28").getTime(),
value1: 20,
value2: 30
},
{
date: new Date("2022-12-29").getTime(),
value1: 10,
value2: 20
}
];
Then you need to create a series for each line that you want to display, associating each series with the corresponding value field. This can be done using a function:
function createSeries(name, field) {
var series = chart.series.push(am5xy.SmoothedXLineSeries.new(root, {
name: name,
xAxis: xAxis,
yAxis: yAxis,
valueXField: "date",
valueYField: field
}));
series.data.setAll(data);
}
createSeries("Series 1", "value1");
createSeries("Series 2", "value2");
am5.ready(function() {
var root = am5.Root.new("chartdiv");
var chart = root.container.children.push(am5xy.XYChart.new(root, {}));
var data = [
{
date: new Date("2022-12-27").getTime(),
value1: 10,
value2: 20
},
{
date: new Date("2022-12-28").getTime(),
value1: 20,
value2: 30
},
{
date: new Date("2022-12-29").getTime(),
value1: 10,
value2: 20
}
];
var xAxis = chart.xAxes.push(am5xy.DateAxis.new(root, {
baseInterval: { timeUnit: "day", count: 1 },
renderer: am5xy.AxisRendererX.new(root, {}),
}));
var yAxis = chart.yAxes.push(am5xy.ValueAxis.new(root, {
renderer: am5xy.AxisRendererY.new(root, {})
}));
function createSeries(name, field) {
var series = chart.series.push(am5xy.SmoothedXLineSeries.new(root, {
name: name,
xAxis: xAxis,
yAxis: yAxis,
valueXField: "date",
valueYField: field
}));
series.data.setAll(data);
}
createSeries("Series 1", "value1");
createSeries("Series 2", "value2");
});
#chartdiv {
width: 100%;
height: 350px;
}
<script src="https://cdn.amcharts.com/lib/5/index.js"></script>
<script src="https://cdn.amcharts.com/lib/5/xy.js"></script>
<div id="chartdiv"></div>
with my current configs, I can't get tooltips to appear. I am using the latest version of Chart.js, with the latest luxon, and the luxon-chartjs plugin via cdn.
i am using a logarithmic Y axis and cartesian timeline x-axis
i can only get a tooltip to appear when I include a blank callback for label. However, that tooltip that appears only has the unformatted date of the datapoint and no other info. when i ask the label callback to return something, nothing is displayed... when i include a blank callback for title or return anything in the title callback, this works and is displayed. i have hacked together a tooltip but in previous versions I've had no issue with the chart automagically creating these for me.
here is my current code and the working fiddle
let maxArray, correctArray, incorrectArray, objectArray
let yourImage = new Image()
yourImage.src = `https://res.cloudinary.com/behaviorreportcard/image/upload/w_10,h_18,c_scale/v1623785517/Untitled_10_qbwmx4.png`;
let ctx = document.getElementById('myChart').getContext('2d');
Chart.defaults.font.size = '10px';
Chart.defaults.plugins.tooltip.enabled = true
const Interval = luxon.Interval,
DateTime = luxon.DateTime,
Duration = luxon.Duration;
let minTime = "2017-01-19",
maxTime = "2017-04-01",
start = DateTime.fromISO(minTime),
end = DateTime.fromISO(maxTime),
duration = Duration.fromObject({
days: 1
});
function getStart() {
let newStart
if (start.weekday != 7) {
return start.minus({
days: start.weekday
}).toFormat("yyyy-MM-dd")
} else {
return start.toFormat("yyyy-MM-dd")
}
}
let emptyArray = Interval.fromDateTimes(start, end).splitBy(duration).map(t => ({
date: t.s.toFormat("yyyy-MM-dd"),
correct: null,
incorrect: null
}));
let incomingData = [{
date: '2017-01-01',
correct: 10,
incorrect: 20
},
{
date: '2017-01-02',
correct: 10,
incorrect: 0.09
},
{
date: '2017-01-03',
correct: 0.9,
incorrect: null
}, {
date: '2017-01-04',
correct: 3,
incorrect: 0.09
}, {
date: '2017-01-27',
correct: 5,
incorrect: 0.09
}, {
date: '2017-01-28',
correct: 10,
incorrect: null
}, {
date: '2017-02-19',
correct: null,
incorrect: 50
}, {
date: '2017-02-20',
correct: 75,
incorrect: 50
}, {
date: '2017-02-28',
correct: 60,
incorrect: 0.085
}, {
date: '2017-03-01',
correct: 75,
incorrect: null
}, {
date: '2017-03-02',
correct: 10,
incorrect: null
}
]
let returns = []
emptyArray.forEach(x => {
let objToReplace = incomingData.find(o => o.date === x.date)
let objIndex = incomingData.indexOf(objToReplace);
if (objIndex != -1) {
returns.push(incomingData[objIndex])
} else {
returns.push(x)
}
})
let dates = []
let corrects = []
let incorrects = []
let nulls = []
let nullVal = 0.025
returns.forEach(x => {
dates.push(x.date)
if (x.correct != null && x.incorrect != null) {
nulls.push(null)
} else if (x.correct == null && x.incorrect != null) {
nulls.push(nullVal)
}
if (x.incorrect == null) {
incorrects.push(null)
} else {
incorrects.push(x.incorrect)
}
if (x.correct == null) {
corrects.push(null)
} else {
corrects.push(x.correct)
}
})
function returnList(key) {
return returns.map(x => {
return x[key]
})
}
function returnNulls() {
let list = []
returns.forEach(x => {
if ((x.correct != null && x.incorrect == null) || (x.correct == null && x.incorrect != null)) {
list.push(nullVal)
} else {
list.push(null)
}
})
return list
}
console.log(returnNulls())
var myChart = new Chart(ctx, {
type: 'line',
data: {
labels: returnList('date'),
datasets: [{
label: 'none',
data: returnNulls(),
spanGaps: false,
pointStyle: yourImage,
},
{
label: 'Corrects',
data: returnList('correct'),
borderWidth: 1,
pointRadius: 5,
spanGaps: false,
fill: false,
borderColor: 'green',
pointStyle: 'circle'
},
{
label: 'Incorrects',
data: returnList('incorrect'),
fill: false,
spanGaps: false,
borderColor: 'red',
pointStyle: 'triangle',
pointRadius: 5,
borderWidth: 1
}
]
},
options: {
events: ['mousemove', 'mouseout', 'click', 'touchstart', 'touchmove'],
interaction: {
mode: 'nearest'
},
plugins: {
tooltip: {
enabled: true,
callbacks: {
label: function(item) {},
title: function(item) {
let date = item[0].label.split(',').slice(0, 2).join(',')
let dataSet = item[0].dataset.label
if (dataSet == 'none') {
return
}
return date + '\n' + dataSet
}
}
},
legend: {
display: true,
position: 'bottom',
labels: {
filter: (x, y) => {
if (!x.text.includes('none')) {
return x
}
},
usePointStyle: 'true',
fontColor: 'black',
fontSize: 12
}
},
title: {
display: true,
text: 'Your daily average results for chapter __',
fontColor: 'black',
fontSize: 18,
}
},
scales: {
x: {
ticks: {
font: {
size: 12
}
},
min: getStart(),
max: '2017-03-31',
type: 'time',
time: {
unit: 'day',
stepSize: 7
}
},
y: {
type: 'logarithmic',
max: 100,
min: 0.01,
ticks: {
autoSkip: false,
callback: function(value,
index,
values) {
switch (value) {
case 1:
return '1 per minute';
case 0.1:
return '.1/min';
case 0.01:
return '.01/min';
case 0.001:
return '.001/min';
case 10:
return '10 per min';
case 100:
return '100 per min';
case 1000:
return '1000 per min';
}
},
}
},
},
},
}
);
the HTML
<div id='chart' class='chart' width='400px' height='100%'>
<canvas id="myChart" class='chart' ></canvas>
</div>
and the scripts I'm calling out to
https://cdn.jsdelivr.net/npm/chart.js#3.3.2/dist/chart.min.js
https://cdnjs.cloudflare.com/ajax/libs/luxon/1.27.0/luxon.min.js
https://cdn.jsdelivr.net/npm/chartjs-adapter-luxon#0.2.1
I am working on chart.js and I have data coming from JSON via ajax. See the example below:
[{"timestamp":"06:00:00.000000","true_count":2},{"timestamp":"07:00:00.000000","true_count":5},{"timestamp":"08:00:00.000000","true_count":7},{"timestamp":"09:00:00.000000","true_count":8},{"timestamp":"10:00:00.000000","true_count":12},{"timestamp":"11:00:00.000000","true_count":15},{"timestamp":"12:00:00.000000","true_count":20},{"timestamp":"13:00:00.000000","true_count":17},{"timestamp":"14:00:00.000000","true_count":14},{"timestamp":"16:00:00.000000","true_count":11},{"timestamp":"17:00:00.000000","true_count":19},{"timestamp":"18:00:00.000000","true_count":22},{"timestamp":"19:00:00.000000","true_count":16},{"timestamp":"20:00:00.000000","true_count":14},{"timestamp":"22:00:00.000000","true_count":7}]
The JS code i am using for my chart is below:
// create initial empty chart
var ctx_live = document.getElementById("chLine");
var myChart = new Chart(ctx_live, {
type: 'bar',
data: {
labels: [],
datasets: [{
data: [],
borderWidth: 1,
borderColor:'#00c0ef',
label: 'liveCount',
}]
},
options: {
responsive: true,
title: {
display: true,
text: "Count Per Hour",
},
legend: {
display: false
},
scales: {
yAxes: [{
ticks: {
beginAtZero: true,
}
}]
}
}
});
// logic to get new data
var getData = function() {
var _data =[];
var _labels = [];
$.ajax({
url: 'chart_data',
type: "get",
success: function(data) {
full_data = JSON.parse(data);
full_data.forEach(function(key,index) {
_data.push(key.true_count);
_labels.push(key.hour);
});
myChart.data.labels = _labels;
myChart.data.datasets[0].data = _data;
myChart.update();
}
});
};
// get new data every 3 seconds
setInterval(getData, 3000);
Now, this is working fine and shows the true_count over time which is a one-hour basis. Now, the chart is showing only hours with count but what I would like to do is to set the static hours from 12 AM to 11 PM, and for hours for which I don't have data the true_count will be zero, and for those that I have data for, the true count will be assigned to that hour and show on the chart.
Any ideas on how do I do that?
Here is an example:
// create initial empty chart
var ctx_live = document.getElementById("chLine");
var myChart = new Chart(ctx_live, {
type: 'bar',
data: {
labels: [],
datasets: [{
data: [],
borderWidth: 1,
borderColor: '#00c0ef',
label: 'liveCount',
}]
},
options: {
responsive: true,
title: {
display: true,
text: "Count Per Hour",
},
legend: {
display: false
},
scales: {
yAxes: [{
ticks: {
beginAtZero: true,
}
}]
}
}
});
// Some constants to be changed later:
const HOUR_TO_START = 0;
const HOUR_TO_END = 23;
// helper:
const intToAmPm = (i) =>
i==0 ? '12 AM' :
i==12 ? '12 PM' :
i < 12 ? i + ' AM' :
(i-12) + ' PM';
// logic to get new data
var getData = function() {
var _data = [];
var _labels = [];
$ajax({
url: 'chart_data',
type: "get",
success: function(data) {
full_data = JSON.parse(data);
let preparedData = {};
full_data.forEach(function(key, index) {
let hour = parseInt(String(key.timestamp).substring(0, 2));
preparedData[hour] = key.true_count;
});
for (let i = HOUR_TO_START; i <= HOUR_TO_END; i++) {
_data.push(preparedData[i] === undefined ? 0 : preparedData[i]);
_labels.push(intToAmPm(i));
}
myChart.data.labels = _labels;
myChart.data.datasets[0].data = _data;
myChart.update();
}
});
};
// get new data every 3 seconds
//setInterval(getData, 3000);
getData();
// THIS IS FOR TESTING. IMITATE BACKEND
function $ajax(param) {
param.success('[{"timestamp":"06:00:00.000000","true_count":2},{"timestamp":"07:00:00.000000","true_count":5},{"timestamp":"08:00:00.000000","true_count":7},{"timestamp":"09:00:00.000000","true_count":8},{"timestamp":"10:00:00.000000","true_count":12},{"timestamp":"11:00:00.000000","true_count":15},{"timestamp":"12:00:00.000000","true_count":20},{"timestamp":"13:00:00.000000","true_count":17},{"timestamp":"14:00:00.000000","true_count":14},{"timestamp":"16:00:00.000000","true_count":11},{"timestamp":"17:00:00.000000","true_count":19},{"timestamp":"18:00:00.000000","true_count":22},{"timestamp":"19:00:00.000000","true_count":16},{"timestamp":"20:00:00.000000","true_count":14},{"timestamp":"22:00:00.000000","true_count":7}]');
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script>
<canvas id="chLine"></canvas>
I have some UV Sensors (currently running on Thingspeak) - but I need to have multiple series on the same chart, so I made a sample .php page on my website.
I have the basic chart working nicely, but I have not been able to get it to do live updates - my coding skills are very lacking & I would appreciate any help I can get!
The sample chart is here: http://www.sesupply.co.nz/test.php
I have the code on JSFiddle here: https://jsfiddle.net/SESupply/9xn65qrL/9/
// variables for the first series
var series_1_channel_id = 43330;
var series_1_field_number = 4;
var series_1_read_api_key = '7ZPHNX2SXPM0CA1K';
var series_1_results = 480;
var series_1_color = '#d62020';
var series_1_name = 'Zims Sensor';
// variables for the second series
var series_2_channel_id = 45473;
var series_2_field_number = 2;
var series_2_read_api_key = 'N12T3CWQB5IWJAU9';
var series_2_results = 480;
var series_2_color = '#00aaff';
var series_2_name = 'UVM30A';
// chart title
var chart_title = 'UV Sensors Zim / UVM30A';
// y axis title
var y_axis_title = 'UV Index';
// user's timezone offset
var my_offset = new Date().getTimezoneOffset();
// chart variable
var my_chart;
// when the document is ready
$(document).on('ready', function () {
// add a blank chart
addChart();
// add the first series
addSeries(series_1_channel_id, series_1_field_number, series_1_read_api_key, series_1_results, series_1_color, series_1_name);
// add the second series
addSeries(series_2_channel_id, series_2_field_number, series_2_read_api_key, series_2_results, series_2_color, series_2_name);
});
// add the base chart
function addChart() {
// variable for the local date in milliseconds
var localDate;
// specify the chart options
var chartOptions = {
chart: {
renderTo: 'chart-container',
defaultSeriesType: 'spline',
zoomType: 'x', // added here
panning: true,
panKey: 'shift',
backgroundColor: '#ffffff',
events: {
load: addSeries
}
},
title: {
text: chart_title
},
subtitle: {
text: 'Click and drag to zoom in. Hold down shift key to pan.'
},
plotOptions: {
series: {
marker: {
radius: 2
},
animation: true,
step: false,
borderWidth: 0,
turboThreshold: 0
}
},
scrollbar: {
enabled: true
// barBackgroundColor: 'gray',
// barBorderRadius: 7,
// barBorderWidth: 0,
// buttonBackgroundColor: 'gray',
// buttonBorderWidth: 0,
// buttonArrowColor: 'yellow',
// buttonBorderRadius: 7,
// rifleColor: 'yellow',
// trackBackgroundColor: 'white',
// trackBorderWidth: 1,
// trackBorderColor: 'silver',
// trackBorderRadius: 7
},
tooltip: {
// reformat the tooltips so that local times are displayed
formatter: function () {
var d = new Date(this.x + (my_offset * 60000));
var n = (this.point.name === undefined) ? '' : '<br>' + this.point.name;
return this.series.name + ':<b>' + this.y + '</b>' + n + '<br>' + d.toDateString() + '<br>' + d.toTimeString().replace(/\(.*\)/, "");
}
},
xAxis: {
type: 'datetime',
title: {
text: 'Date'
}
},
rangeSelector: {
enabled: true,
buttons: [{
type: 'minute',
count: 60,
text: 'Hour'
}, {
type: 'day',
count: 1,
text: 'Day'
}, {
type: 'week',
count: 1,
text: 'Week'
}, {
type: 'all',
text: 'All'
}]
},
yAxis: {
title: {
text: y_axis_title
}
},
exporting: {
enabled: true
},
legend: {
enabled: true
},
credits: {
text: 'ThingSpeak.com',
href: 'https://thingspeak.com/',
style: {
color: '#D62020'
}
}
};
// draw the chart
my_chart = new Highcharts.Chart(chartOptions);
}
// add a series to the chart
function addSeries(channel_id, field_number, api_key, results, color, name) {
var field_name = 'field' + field_number;
// get the data with a webservice call
$.getJSON('https://api.thingspeak.com/channels/' + channel_id + '/fields/' + field_number + '.json?offset=0&round=2&results=' + results + '&api_key=' + api_key, function (data) {
// blank array for holding chart data
var chart_data = [];
// iterate through each feed
$.each(data.feeds, function () {
var point = new Highcharts.Point();
// set the proper values
var value = this[field_name];
point.x = getChartDate(this.created_at);
point.y = parseFloat(value);
// add location if possible
if (this.location) {
point.name = this.location;
}
// if a numerical value exists add it
if (!isNaN(parseInt(value))) {
chart_data.push(point);
}
});
// add the chart data
my_chart.addSeries({
data: chart_data,
name: name,
color: color
});
});
setTimeout(addSeries, 1000);
}
cache: false;
// converts date format from JSON
function getChartDate(d) {
// offset in minutes is converted to milliseconds and subtracted so that chart's x-axis is correct
return Date.parse(d) - (my_offset * 60000);
}
I have tried following the livedata example but seem to be failing miserably. The sensors update about every 60 seconds (only during the day - as there is no UV at night, I put the sensors into "sleep" mode to save battery power)
I cannot figure out how to get the 'to' and 'from' dates from my data into the tooltips. Tried various methods I found around SO. Anyone got any tips? I normally load data from CSV. Right now the data is hard-coded in the code.
var options = {
chart: {
zoomType: 'y',
borderWidth: '0',
borderRadius: '15',
renderTo: 'container',
inverted: true,
backgroundColor: {
linearGradient: [0, 0, 500, 500],
stops: [
[0, 'rgb(44, 44, 58)'],
[1, 'rgb(62, 62, 62)']
]
},
plotBackgroundColor: 'rgba(255, 255, 255, .9)'
},
tooltip: {
formatter: function () {
var point = this.point;
return '<b>' + point.category +
'</b><br/>' + Highcharts.dateFormat('%b %e, %Y', this.y) +
' - ' + Highcharts.dateFormat('%b %e, %Y', this.series[0]);
}
},
legend: {
enabled: false
},
title: {
text: 'EVMS Calendar'
},
xAxis: {
categories: []
},
plotOptions: {
series: {
grouping: false
}
},
yAxis: {
type: 'datetime',
minRange: '604800000',
startOnTick: false,
endOnTick: false,
title: {
text: ''
}
},
series: []
},
categories = [];;
//// This is the data processing section \\\\
// Hard Coded Data
var data ="valid data";
// Split the lines
var lines = data.split('\n');
// Iterate over the lines and add categories or series
// Split the data by comma
// Get the number of items in the object (iLen)
// Series start
// Series type is columnrange
// Servies name is item 0 of the line (employees name)
$.each(lines, function (lineNo, line) {
var items = line.split(','),
iLen = items.length,
series = {
type: 'columnrange',
data: [],
name: items[0]
};
// Start categories
// for each items (0) get the row data (dates) and push to categories(line number, from and to)
categories.push(items[0]);
for (var i = 1; i < iLen; i += 2) {
var from = (new Date(items[i])).getTime(),
to = (new Date(items[i + 1])).getTime();
if (!isNaN(from) && !isNaN(to)) {
series.data.push([lineNo, from, to]);
}
};
options.series.push(series);
});
options.xAxis.categories = categories;
// Create the chart
var chart = new Highcharts.Chart(options);
ah, my bad. Its this.point.high / low. I found out by looking through the elements in chrome