refresh chart data every second javascript - 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

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>

new dataset is not accepted by chartj template

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.

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>

plotly.js how to change z data on hover to display % as well as % on colorscale

I would like to add a % tag to the z value that is show on hover. Also, right now, my colorscale is only displaying -10 to 10, but I would like it to show % so -10% to 10%. Here is the code I have.
I have tried to add the ticksuffix : "%", but I'm not sure where I should put it since it seems like the colorscale is not an axis like the x and y axis.
var xValues = ['A', 'B', 'C',];
var yValues = ['W', 'X', 'Y', 'Z'];
var zValues = [[-2.45,-0.4,1.3],
[2.9,3.9,-5.66],
[0.5,-2.6,-3.2],
[-8.3,-0.5,-0.1]];
var a_text = [["Comodities + producers","Consumer Discretionary","Utilities Equities"],
["Health and Biotech","Global Real Estate","Financial Equities"],
["Emerging Market Bonds","Technology Equities","Industrials Equities"],
["Oil and Gas","China Equities","Diversified Portfolio"]];
var data = [{
x: xValues,
y: yValues,
z: zValues,
hoverinfo: "z",
reversescale: true,
type: 'heatmap',
// zsmooth: "best",
colorscale: "Spectral",
zauto: false,
zmin:-10,
zmax:10,
showscale: true,
}];
var layout = {
title: 'Annotated Heatmap',
annotations: [],
xaxis: {
ticks: '',
side: 'top',
tickfont: {color: 'rgb(255,255,255)'}
},
yaxis: {
ticks: '',
ticksuffix: ' ',
width: 700,
height: 700,
autosize: true,
tickfont: {color: 'rgb(255,255,255)'},
}
};
for ( var i = 0; i < yValues.length; i++ ) {
for ( var j = 0; j < xValues.length; j++ ) {
var currentValue = (zValues[i][j]);
if (currentValue < -0.05) {
var textColor = 'white';
}else{
var textColor = 'black';
}
var result = {
xref: 'x1',
yref: 'y1',
x: xValues[j],
y: yValues[i],
text: a_text[i][j],
font: {
family: 'Arial',
size: 12,
color: 'rgb(50, 171, 96)'
},
showarrow: false,
font: {
color: textColor
}
};
layout.annotations.push(result);
}
}
Plotly.newPlot('myDiv', data, layout);
You need to change two things, the color bar and the hover text.
Color bar
Add this info to your variable data.
colorbar: {
title: 'Relative change',
ticksuffix: '%',
}
Hover text
First convert the z-values into strings and append %.
var zText = [];
var prefix = "+";
var i = 0;
var j = 0;
for (i = 0; i < zValues.length; i += 1) {
zText.push([]);
for (j = 0; j < zValues[i].length; j += 1) {
if (zValues[i][j] > 0) {
prefix = "+";
} else {
prefix = "";
}
zText[i].push(prefix + zValues[i][j] + "%");
}
}
Then assign the new text to the plot.
Add
text: zText,
hoverinfo: "text",
to your variable data.
Here is a fiddle with the complete data and code: https://jsfiddle.net/Ashafix/e6936boq/2/

Categories

Resources