new dataset is not accepted by chartj template - javascript

I am trying to plot a line chart on the node red dashboard.
This template creates the desired scrollable chart with 100 randomly generated datapoints:
<style>.chartWrapper {
position: relative;
}
.chartWrapper > canvas {
position: absolute;
left: 0;
top: 0;
pointer-events: none;
}
.chartAreaWrapper {
width: auto;
overflow-x: scroll;
}
</style>
<div class="chartWrapper">
<div class="chartAreaWrapper">
<div class="chartAreaWrapper2">
<canvas id="chart-Test" height="351" width="4000"></canvas>
</div>
</div>
<canvas id="axis-Test" height="351" width="0"></canvas>
</div>
<script>
$(document).ready(function () {
function generateLabels() {
var chartLabels = [];
for (x = 0; x < 100; x++) {
chartLabels.push(x);
}
return chartLabels;
}
function generateData() {
var chartData = [];
for (x = 0; x < 100; x++) {
chartData.push(Math.floor((Math.random() * 100) + 1));
}
return chartData;
}
function addData(numData, chart) {
for (var i = 0; i < numData; i++) {
chart.data.datasets[0].data.push(Math.random() * 100);
chart.data.labels.push("Label" + i);
var newwidth = $('.chartAreaWrapper2').width() + 60;
$('.chartAreaWrapper2').width(newwidth);
}
}
var chartData = {
labels: generateLabels(),
datasets: [{
label: "Test Data Set",
data: generateData(),
pointRadius: 0,
borderColor: "#4ED7FC",
borderWidth: 2,
fill: false
}]
};
$(function () {
var rectangleSet = false;
var canvasTest = $('#chart-Test');
var chartTest = new Chart(canvasTest, {
type: 'line',
data: chartData,
maintainAspectRatio: false,
responsive: true,
});
addData(5, chartTest);
});
});
</script>
Next I wanted to replace the generated datapoints with a payload message coming into the dashboard template node, where msg.payload[0].data is an array[2500].
I thought I would be able to achieve this by replacing generateData()like so:
<style>.chartWrapper {
position: relative;
}
.chartWrapper > canvas {
position: absolute;
left: 0;
top: 0;
pointer-events: none;
}
.chartAreaWrapper {
width: auto;
overflow-x: scroll;
}
</style>
<div class="chartWrapper">
<div class="chartAreaWrapper">
<div class="chartAreaWrapper2">
<canvas id="chart-Test" height="351" width="4000"></canvas>
</div>
</div>
<canvas id="axis-Test" height="351" width="0"></canvas>
</div>
<script>
$(document).ready(function () {
function generateLabels() {
var chartLabels = [];
for (x = 0; x < 100; x++) {
chartLabels.push(x);
}
return chartLabels;
}
/*function generateData() {
var chartData = [];
for (x = 0; x < 100; x++) {
chartData.push(Math.floor((Math.random() * 100) + 1));
}
return chartData;
}*/
function generateData(msg) {
var chartData = [];
chartData = msg.payload[0].data;
return chartData;
}
function addData(numData, chart) {
for (var i = 0; i < numData; i++) {
chart.data.datasets[0].data.push(Math.random() * 100);
chart.data.labels.push("Label" + i);
var newwidth = $('.chartAreaWrapper2').width() + 60;
$('.chartAreaWrapper2').width(newwidth);
}
}
var chartData = {
labels: generateLabels(),
datasets: [{
label: "Test Data Set",
data: generateData(),
pointRadius: 0,
borderColor: "#4ED7FC",
borderWidth: 2,
fill: false
}]
};
$(function () {
var rectangleSet = false;
var canvasTest = $('#chart-Test');
var chartTest = new Chart(canvasTest, {
type: 'line',
data: chartData,
responsive: true,
options: {
maintainAspectRatio: false,
tooltips: {
titleFontSize: 0,
titleMarginBottom: 0,
bodyFontSize: 12
},
legend: {
display: false
},
scales: {
xAxes: [{
ticks: {
fontSize: 12,
display: false
}
}],
yAxes: [{
ticks: {
fontSize: 12,
beginAtZero: true
}
}]
},
}
});
addData(5, chartTest);
});
});
</script>
But then the chart is just showing a blank:
Why is that?
[edit]
the incoming payload is not empty:

I would try the follwing:
1.- Check that your array[2500] has values between 1 and 100 and pass in the first 100 instead the whole 2500 array to check if that works
2.- Might depend on the chartjs version, but I would try to put the maintainAspectRatio property inside an options: {} object. See below.
var chart = new Chart('blabla', {
type: 'bar',
data: {},
options: {
maintainAspectRatio: false,
}
});
Apart from that, 2500 records seems to be a too big amount of data to handle. If the graph renders for smaller amounts, I would try to keep the graph drawn with an amount that gets rendered, and the fetch the data + update the chart depending on the users x-scroll.
Edit:
I think you need to call the addData for your new array with a modified addData function that would look something like this, for the width to fit.
function addData(chart) {
for (var i = 0; i < chart.data[0].data.length; i++) {
//chart.data.datasets[0].data.push(Math.random() * 100);
//chart.data.labels.push("Label" + i);
var newwidth = $('.chartAreaWrapper2').width() + 60;
$('.chartAreaWrapper2').width(newwidth);
}
}
Note that your script work up determined num of records with the arrangements mentioned, so if the graph goes blank can only be that your new array is empty or has some issue.
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.2/Chart.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<style>.chartWrapper {
position: relative;
}
.chartWrapper > canvas {
position: absolute;
left: 0;
top: 0;
pointer-events: none;
}
.chartAreaWrapper {
width: auto;
overflow-x: scroll;
}
</style>
<div class="chartWrapper">
<div class="chartAreaWrapper">
<div class="chartAreaWrapper2">
<canvas id="chart-Test" height="300" width="1200"></canvas>
</div>
</div>
<canvas id="axis-Test" height="300" width="0"></canvas>
<div class="chartWrapper">
<div class="chartAreaWrapper">
<div class="chartAreaWrapper2">
<canvas id="chart-Test" height="351" width="4000"></canvas>
</div>
</div>
<canvas id="axis-Test" height="351" width="0"></canvas>
</div>
<script>
$(document).ready(function () {
function generateLabels() {
var chartLabels = [];
for (x = 0; x < 100; x++) {
chartLabels.push(x);
}
return chartLabels;
}
function generateData() {
var chartData = [];
for (x = 0; x < 100; x++) {
chartData.push(Math.floor((Math.random() * 100) + 1));
}
return chartData;
}
function addData(numData, chart) {
for (var i = 0; i < numData; i++) {
chart.data.datasets[0].data.push(Math.random() * 100);
chart.data.labels.push("Label" + i);
var newwidth = $('.chartAreaWrapper2').width() + 60;
$('.chartAreaWrapper2').width(newwidth);
}
}
var chartData = {
labels: generateLabels(),
datasets: [{
label: "Test Data Set",
data: generateData(),
pointRadius: 0,
borderColor: "#4ED7FC",
borderWidth: 2,
fill: false
}]
};
$(function () {
var rectangleSet = false;
var canvasTest = $('#chart-Test');
var chartTest = new Chart(canvasTest, {
type: 'line',
data: chartData,
options: {
maintainAspectRatio: false,
responsive: true
}
});
addData(300, chartTest);
});
});
</script>

I found out that the dashboard template node does not easily accept payload messages on the script section.
watch function
I have to use something like:
// Watch the payload and update
(function(scope) {
scope.$watch('msg.payload', function(data) {
update(data);
});
})(scope);
function update(dta) {
theScope.send({payload:dta});
bleh = dta.name;
otherStuff();
}
to watch a incoming payload and store it.
My initial question "Why is that?" is therefore answered.
Unfortunately I am not quite sure how to implement this new bit of code to the array coming in in msg.payload[0.data in my specific case.

Related

I want to Display Data instead of percentages when cursor hovers over Doughnut Chart in JS

const data = {
labels: ['xyz', 'abc'],
datasets: [{
label: 'Weekly Sales',
data: [12, 20],
backgroundColor: [
'rgb(254, 214, 10)',
'rgb(255, 90, 48)'
],
borderColor: [
"#ffffff",
],
borderWidth: 1
}]
};
var sum = 0;
var i;
for (i = 0; i < data.datasets[0].data.length; ++i) {
sum += data.datasets[0].data[i];
}
console.log("sume", sum);
for (i = 0; i < data.datasets[0].data.length; ++i) {
data.datasets[0].data[i] = Math.round((data.datasets[0].data[i] / sum) * 100);
}
// config
const config = {
type: 'doughnut',
data,
options: {
plugins: {
datalabels: {
formatter: (value, ctx) => {
let datasets = ctx.chart.data.datasets;
if (datasets.indexOf(ctx.dataset) === datasets.length - 1) {
//var sum = datasets[0].data.reduce((a, b) => a + b, 0);
var percentage = Math.round((value / sum) * 100) +"%";
return percentage;
} else {
return percentage;
}
},
color: '#fff',
}
}
}
};
// render init block
const myChart = new Chart(
document.getElementById('myChart'),
config
);
$(document).ready(function () {
$("#count1").text( data.datasets[0].data[0]+"%" );
$("#count2").text( data.datasets[0].data[1]+"%" )
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chart.js#2.9.4"></script>
<!-- <script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-datalabels#0.7.0"></script> -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/chartjs-plugin-datalabels/2.0.0/chartjs-plugin-datalabels.min.js"></script>
<canvas id="myChart"></canvas>
<div class="block-text">
<div class="flex-chart"> <div class="box-file"></div><p class="spacing">abc</p>
<p id = "count1">20%</p></div>
<div class="flex-chart"> <div class="box-url"></div><p class="spacing">xyz</p>
<p id = "count2">30%</p>
</div>
</div>
I just want to display data: [12, 20], this data instead of percentages when cursor hovers over Doughnut Chart without Changing other code.**
**When cursor hovers over Doughnut Chart, it shows the percentage of the Data value. Simply, I want to display Data values when cursor hover overs Doughnut Chart without changes in this Code.
In the following line, you are overwriting the data items:
data.datasets[0].data[i] = Math.round((data.datasets[0].data[i] / sum) * 100);
It would be better to create a new array here, legendData, which you can then use later on. So:
const legendData = [];
for (i = 0; i < data.datasets[0].data.length; ++i) {
legendData[i] = Math.round((data.datasets[0].data[i] / sum) * 100);
}
And at the bottom of the JavaScript code you need to make the following changes:
$("#count1").text( legendData[0]+"%" );
$("#count2").text( legendData[1]+"%" )
I am not sure if your formatter function is working properly, but that does not affect this solution.
const data = {
labels: ['xyz', 'abc'],
datasets: [{
label: 'Weekly Sales',
data: [12, 20],
backgroundColor: [
'rgb(254, 214, 10)',
'rgb(255, 90, 48)'
],
borderColor: [
"#ffffff",
],
borderWidth: 1
}]
};
var sum = 0;
var i;
for (i = 0; i < data.datasets[0].data.length; ++i) {
sum += data.datasets[0].data[i];
}
const legendData = [];
for (i = 0; i < data.datasets[0].data.length; ++i) {
legendData[i] = Math.round((data.datasets[0].data[i] / sum) * 100);
}
const config = {
type: 'doughnut',
data,
options: {
plugins: {
datalabels: {
formatter: (value, ctx) => {
let datasets = ctx.chart.data.datasets;
if (datasets.indexOf(ctx.dataset) === datasets.length - 1) {
//var sum = datasets[0].data.reduce((a, b) => a + b, 0);
var percentage = Math.round((value / sum) * 100) + "%";
return percentage;
} else {
return percentage;
}
},
color: '#fff',
}
}
}
};
// render init block
const myChart = new Chart(
document.getElementById('myChart'),
config
);
$(document).ready(function() {
$("#count1").text(legendData[0] + "%");
$("#count2").text(legendData[1] + "%")
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chart.js#2.9.4"></script>
<!-- <script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-datalabels#0.7.0"></script> -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/chartjs-plugin-datalabels/2.0.0/chartjs-plugin-datalabels.min.js"></script>
<canvas id="myChart"></canvas>
<div class="block-text">
<div class="flex-chart">
<div class="box-file"></div>
<p class="spacing">abc</p>
<p id="count1">20%</p>
</div>
<div class="flex-chart">
<div class="box-url"></div>
<p class="spacing">xyz</p>
<p id="count2">30%</p>
</div>
</div>

refresh chart data every second javascript

I am creating an html web page with a chart on that shows voltage levels continuously changing. I want to refresh the page every second so that the bars in the bar chart go to the new values. I am not sure how to update the chart data like this. I have the following so far:
Chart.plugins.unregister(ChartDataLabels);
function myFunction() {
var cells = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16];
var voltages = [];
for (i = 0; i < 16; i++) {
voltages[i] = Math.floor(28 + Math.floor(Math.random() * 8)) / 10;
}
var colours = [];
for (i = 0; i < voltages.length; i++) {
colours[i] = getColour(voltages[i]);
}
var ctx = document.getElementById("voltageChart");
var voltageChart = new Chart(ctx, {
plugins: [ChartDataLabels],
type: "bar",
data: {
labels: cells,
datasets: [{
data: voltages,
backgroundColor: colours,
}]
},
});
function updateData(chart) {
chart.data.datasets[0].data = voltages;
chart.data.datasets[0].backgroundColor = colours;
chart.update();
}
function refreshData() {
for (i = 0; i < 16; i++) {
voltages[i] = Math.floor(28 + Math.floor(Math.random() * 8)) / 10;
}
for (i = 0; i < voltages.length; i++) {
colours[i] = getColour(voltages[i]);
}
updateData(voltageChart);
}
setInterval(refreshData, 1500);
}
There are different problems in your code. Please have a look at the following code snippet that shows how it can be done in a simple way.
<html>
<head>
<title>Polar Area Chart</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script>
<style>
canvas {
-moz-user-select: none;
-webkit-user-select: none;
-ms-user-select: none;
}
</style>
</head>
<body>
<div style="width: 60%">
<canvas id="voltageChart"></canvas>
</div>
<script>
window.onload = () => {
const cells = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16];
const voltages = [];
const colours = [];
refreshData();
const ctx = document.getElementById("voltageChart");
const voltageChart = new Chart(ctx, {
type: "bar",
data: {
labels: cells,
datasets: [{
data: voltages,
backgroundColor: colours,
}]
},
options: {
legend: {
display: false
}
}
});
function refreshData() {
for (i = 0; i < cells.length; i++) {
voltages[i] = Math.floor(28 + Math.floor(Math.random() * 8)) / 10;
colours[i] = voltages[i] < 3.2 ? 'green' : 'red';
}
}
setInterval(() => {
refreshData();
voltageChart.update();
}, 1500);
};
</script>
</body>
</html>
We can use chart.data.datasets.pop() and push new data chart.data.datasets.push() and then invoke chart.js function chart.update to re-render the graph . here is the example : https://codepen.io/bhupendra1011/pen/MWwWogO?editors=1111.
More on adding/removing data here

Make y-axis sticky when having horizontal scroll on chartJS and Angular

I would like to fix y-axis position when scrolling horizontally.
Here's an example that works but without using Angular
$(document).ready(function () {
function generateLabels() {
var chartLabels = [];
for (x = 0; x < 100; x++) {
chartLabels.push("Label" + x);
}
return chartLabels;
}
function generateData() {
var chartData = [];
for (x = 0; x < 100; x++) {
chartData.push(Math.floor((Math.random() * 100) + 1));
}
return chartData;
}
function addData(numData, chart) {
for (var i = 0; i < numData; i++) {
chart.data.datasets[0].data.push(Math.random() * 100);
chart.data.labels.push("Label" + i);
var newwidth = $('.chartAreaWrapper2').width() + 60;
$('.chartAreaWrapper2').width(newwidth);
}
}
var chartData = {
labels: generateLabels(),
datasets: [{
label: "Test Data Set",
data: generateData()
}]
};
$(function () {
var rectangleSet = false;
var canvasTest = $('#chart-Test');
var chartTest = new Chart(canvasTest, {
type: 'bar',
data: chartData,
maintainAspectRatio: false,
responsive: true,
options: {
tooltips: {
titleFontSize: 0,
titleMarginBottom: 0,
bodyFontSize: 12
},
legend: {
display: false
},
scales: {
xAxes: [{
ticks: {
fontSize: 12,
display: false
}
}],
yAxes: [{
ticks: {
fontSize: 12,
beginAtZero: true
}
}]
},
animation: {
onComplete: function () {
if (!rectangleSet) {
var sourceCanvas = chartTest.chart.canvas;
var copyWidth = chartTest.scales['y-axis-0'].width;
var copyHeight = chartTest.scales['y-axis-0'].height + chartTest.scales['y-axis-0'].top + 10;
var targetCtx = document.getElementById("axis-Test").getContext("2d");
targetCtx.canvas.width = copyWidth;
targetCtx.drawImage(sourceCanvas, 0, 0, copyWidth, copyHeight, 0, 0, copyWidth, copyHeight);
var sourceCtx = sourceCanvas.getContext('2d');
sourceCtx.clearRect(0, 0, copyWidth, copyHeight);
rectangleSet = true;
}
},
onProgress: function () {
if (rectangleSet === true) {
var copyWidth = chartTest.scales['y-axis-0'].width;
var copyHeight = chartTest.scales['y-axis-0'].height + chartTest.scales['y-axis-0'].top + 10;
var sourceCtx = chartTest.chart.canvas.getContext('2d');
sourceCtx.clearRect(0, 0, copyWidth, copyHeight);
}
}
}
}
});
addData(5, chartTest);
});
});
.chartWrapper {
position: relative;
}
.chartWrapper > canvas {
position: absolute;
left: 0;
top: 0;
pointer-events: none;
}
.chartAreaWrapper {
width: 600px;
overflow-x: scroll;
}
<script src="https://github.com/chartjs/Chart.js/releases/download/v2.6.0/Chart.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="chartWrapper">
<div class="chartAreaWrapper">
<div class="chartAreaWrapper2">
<canvas id="chart-Test" height="300" width="1200"></canvas>
</div>
</div>
<canvas id="axis-Test" height="300" width="0"></canvas>
</div>
When I use this in my angular example , it does not work anymore, the axis does not follow the scroll
Here's a stackblitz reproduction
In your StackBlitz, the section (rectanlge) of the y-axis is correctly created on the target canvas and removed from the source canvas. The problem is that the wrong div is horizontally scrolled. This can be fixed by changing the template and corresponding css.
Please have a look at the following StackBlitz.
UPDATE (dynamic data)
In cases where the chart component receives dynamically changing data through an #Input() property, your component needs to implement the OnChange lifecycle hook.
See the following StackBlitz.
Please note that this code is far from being optimized. Instead of creating the chart from scratch on every data change, you should simply update the data and options on the existing chart.

Dygraphs: Highlight specific point on mouse over

Is there a way to highlight a specific point when mouse is over or near that specific point ? The thing is that I don't want to highlight all the lines but only the point(s) under or near my cursor. My goal is to show a tooltip at that position with the informations for that point.
This ChartJs example demonstrate pretty well what I would like to do:
http://www.chartjs.org/samples/latest/scales/time/line.html
And these are my current options:
{
drawPoints: true,
showRoller: false,
highlightCircleSize: 5,
labels: ['Time', 'Vac', 'Temp'],
ylabel: 'Vaccum (In/Hg)',
y2label: 'Temperature ('+ TemperatureUnitFactory.getTemperatureUnit() + ')',
series : {
'Vac': {
axis: 'y'
},
'Temp': {
axis: 'y2'
}
},
axes: {
y: {
drawGrid: true,
independentTicks: true,
valueRange: [0, -32],
label: 'Vaccum'
},
y2: {
drawGrid: false,
independentTicks: true,
valueRange: [
TemperatureUnitFactory.getTemperatureForUnit(-30),
TemperatureUnitFactory.getTemperatureForUnit(35)
],
ylabel: 'Temperature'
}
}
}
If you feel like I am missing informations that would help you enlighting me, just let me know in a comment.
Thank you all!
So here's a snippet for the solution to my problem. I believe it could be optimized by throtling the mousemouve callback, but in my case it did just fine. I converted the snippet from angular to jQuery for "simplicity".
var data = [
[new Date(20070101),62,39],
[new Date(20070102),62,44],
[new Date(20070103),62,42],
[new Date(20070104),57,45],
[new Date(20070105),54,44],
[new Date(20070106),55,36],
[new Date(20070107),62,45],
[new Date(20070108),66,48],
[new Date(20070109),63,39],
[new Date(20070110),57,37],
[new Date(20070111),50,37],
[new Date(20070112),48,35],
];
var graph = new Dygraph(
document.getElementById("chart"), data, {
rollPeriod: 1,
labels: ['Time', 'Vac', 'Temp'],
showRoller: false,
drawPoints: true,
}
);
var tooltip = {
element: $('#tooltip'),
x: function(_x){
this.element.css('left', _x);
},
y: function(_y) {
this.element.css('top', _y);
},
shown: false,
throttle: null,
currentPointData: null,
show: function() {
if(!this.shown) {
this.element.show();
this.shown = true;
}
},
hide: function() {
this.cancelThrottle();
if(this.shown) {
this.element.hide();
this.shown = false;
}
},
cancelThrottle: function () {
if(this.throttle !== null) {
clearTimeout(this.throttle);
this.throttle = null;
}
},
bindPoint: function (_point) {
this.element.html([_point.point.name,_point.point.xval, _point.point.yval].join(' | '))
console.log('Handle point data', _point);
}
};
var chartElement = $('#chart');
var isMouseDown = false;
chartElement.on('mousedown', function(){ isMouseDown = true; });
chartElement.on('mouseup', function(){ isMouseDown = false; });
chartElement.on('mousemove', function(){
if(graph === null) { return; }
if(isMouseDown) {
tooltip.hide();
return;
}
const ACCEPTABLE_OFFSET_RANGE = 8;
const TOOLTIP_BOTTOM_OFFSET = 25;
const TOOLTIP_THROTTLE_DELAY = 600;
var graphPos = Dygraph.findPos(graph.graphDiv),
canvasX = Dygraph.pageX(event) - graphPos.x,
canvasY = Dygraph.pageY(event) - graphPos.y,
rows = graph.numRows(),
cols = graph.numColumns(),
axes = graph.numAxes(),
diffX, diffY, xPos, yPos, inputTime, row, col, axe;
for (row = 0; row < rows; row++)
{
inputTime = graph.getValue(row, 0);
xPos = graph.toDomCoords(inputTime, null)[0];
diffX = Math.abs(canvasX - xPos);
if (diffX < ACCEPTABLE_OFFSET_RANGE)
{
for (col = 1; col < cols; col++)
{
var inputValue = graph.getValue(row, col);
if (inputValue === null) { continue; }
for(axe = 0; axe < axes; axe++)
{
yPos = graph.toDomCoords(null, inputValue, axe)[1];
diffY = Math.abs(canvasY - yPos);
if (diffY < ACCEPTABLE_OFFSET_RANGE)
{
tooltip.cancelThrottle();
if(!tooltip.shown)
{
var self = this;
tooltip.throttle = setTimeout(function () {
var ttHeight = tooltip.element.height(),
ttWidth = tooltip.element.width();
tooltip.x((xPos - (ttWidth / 2)));
tooltip.y((yPos - (ttHeight + TOOLTIP_BOTTOM_OFFSET)));
tooltip.show();
var closestPoint = graph.findClosestPoint(xPos, yPos);
if(closestPoint) {
tooltip.bindPoint(closestPoint);
}
}, TOOLTIP_THROTTLE_DELAY);
}
return;
}
}
}
}
}
tooltip.hide();
});
.chart-container {
position:relative;
}
.chart-container > .tooltip {
position:absolute;
padding: 10px 10px;
background-color:#ababab;
color:#fff;
display:none;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/dygraph/2.1.0/dygraph.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/dygraph/2.1.0/dygraph.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="chart-container">
<div id="chart"></div>
<div id="tooltip" class="tooltip">
Some data to be shown
</div>
</div>

Can't get Highstock "scroll" to work

trying to compare two sensor readings - the data is coming from thingspeak. I've got the zoom part working, but for some reason I cant get the scroll to work.
<script type="text/javascript">
// 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: 'line',
zoomType: 'x', // added here
backgroundColor: '#ffffff',
events: { }
},
title: { text: chart_title },
plotOptions: {
series: {
marker: { radius: 3 },
animation: true,
step: false,
borderWidth: 0,
turboThreshold: 0
}
},
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',
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
},
title: { text: 'Date' }
},
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: data.channel[field_name], color: color });
});
}
// 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);
}
</script>
​
<style type="text/css">
body { background-color: white; height: 100%; margin: 0; padding: 0; }
#chart-container { width: 800px; height: 400px; display: block; position:absolute; bottom:0; top:0; left:0; right:0; margin: 5px 15px 15px 0; overflow: hidden; }
</style>​
<!DOCTYPE html>
<html style="height: 100%;">
<head>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript" src="//code.highcharts.com/stock/highstock.js"></script>
<script type="text/javascript" src="//thingspeak.com/exporting.js"></script>
</head>
<body>
<div id="chart-container">
// <img alt="Ajax loader" src="//thingspeak.com/assets/ajax-loader.gif" style="position: absolute; margin: auto; top: 0; left: 0; right: 0; bottom: 0;" />
</div>
</body>
</html>​
I would also like to get the chart updating automatically, so any help on that score would also be appreciated. The final issue I am having is trying to get the legend to display the sensor names properly: UV Index (red) should read "Zims Sensor" and UV Index (blue) should read "UVM30A"

Categories

Resources