Logic Machine Forum
chartist to display nice pie... - Printable Version

+- Logic Machine Forum (https://forum.logicmachine.net)
+-- Forum: LogicMachine eco-system (https://forum.logicmachine.net/forumdisplay.php?fid=1)
+--- Forum: General (https://forum.logicmachine.net/forumdisplay.php?fid=2)
+--- Thread: chartist to display nice pie... (/showthread.php?tid=3789)

Pages: 1 2


RE: chartist to display nice pie... - domotiqa - 25.03.2024

Hi admin, any idea how to have GA from grp.tag for example:
var ids = [ '20/4/1','20/4/2' , '20/4/3' ];

instead of trend ID
var ids = [ 1, 3, 5 ];


RE: chartist to display nice pie... - admin - 25.03.2024

Not possible without an .lp script to find matching trend IDs to the provided group addresses.


RE: chartist to display nice pie... - domotiqa - 25.03.2024

ouch... that was what I was thinking.
I will maybe try to add script that put in comment of an object his trend id

there is no way in javacript to do sql query


RE: chartist to display nice pie... - admin - 25.03.2024

I don't see any other solution but to use a .lp script.


RE: chartist to display nice pie... - jmir - 25.03.2024

(14.03.2024, 07:31)admin Wrote: This function can be used to fetch trend data. Change ids array as needed.
Code:
function getdate(offset) {
  var date = new Date();
 
  date.setDate(date.getDate() + offset);
 
  var year = date.getFullYear();
  var month = date.getMonth() + 1;
  var day = date.getDate();
 
  return { year, month, day };
}

function getdata() {
  var ids = [ 1, 3, 5 ];

  var data = JSON.stringify({
    dates_curr: {
      start: getdate(0),
      end: getdate(1)
    },
    ids: ids,
  });
 
  $.post('/scada-vis/trends/fetch', { data }, function(trends) {
    var result = [];
   
    trends = JSON.parse(trends);
    $.each(trends, function(_, trend) {
      result.push(trend.data);
    });

    console.log(result);
  });
}

Hi,
Is it possible to get data timestamps using this code?


RE: chartist to display nice pie... - admin - 27.03.2024

Custom JS to fetch trend data from trends.lp:
Code:
function getdate(offset) {
  var date = new Date();
 
  date.setDate(date.getDate() + offset);
 
  var year = date.getFullYear();
  var month = date.getMonth() + 1;
  var day = date.getDate();
 
  return { year, month, day };
}

function getdata() {
  var trends = [
    1,
    'Temperature',
    'Humidity',
   ];

  var data = JSON.stringify({
    trends: trends,
    dates: {
      start: getdate(0),
      end: getdate(1),
    },
    // resolution: 86400,
    // timestamps: true,
  });
 
  $.post('/user/trends.lp', data, function(resp) {
    console.log(resp);
  });
}

Both trend ID and name can be specified. Set resolution to 86400 to fetch daily data. Set timestamps to true to fetch both data and timestamps.


trends.lp
Code:
<?

require('json')
require('trends')

trends.NaN = json.null

ngx.header.content_type = 'application/json'

local req = ngx.req.get_body_data()
req = json.pdecode(req)

local res = {}
local dates = req.dates
local resolution = tonumber(req.resolution)
local timestamps = toboolean(req.timestamps)

for i, idname in ipairs(req.trends) do
  local id = tonumber(idname)

  if id then
    res[ i ] = trends.fetchrangebyid(id, dates, resolution, timestamps)
  else
    res[ i ] = trends.fetch(idname, dates, resolution, timestamps)
  end
end

json.write(res)

Note that there is no input data validation so the script can end with 500 Internal Server Error if the input data is incorrect.


RE: chartist to display nice pie... - domotiqa - 27.03.2024

Thanks for your lp file.

I tried to do sum of the value, but can't get length value, still 0 for result. however I can see the result value as array type in console...
I tried lots of solution with each, for... without success. Any idea ?

Code:
function readTrend( listeId, dayBefore, dayBase )
{

  var data = JSON.stringify({
    dates_curr: {
      start: getdate(dayBefore),
      end: getdate(dayBase)
    },
    ids: listeId,
  });
  var result = [];
  var totVal=[];
 
  $.post('/scada-vis/trends/fetch', { data }, function(trends) {

    trends = JSON.parse(trends);
    $.each(trends, function(_, trend) {
      result.push(trend.data);
    });

  });
 
  return sum(result);

}



Code:
function sum(array) {
 
//test each
  let totVal = 0
  console.log(array[1]);
  let newArray=new Array();
  newArray=array;
 
   $.each(newArray, function(_, lined) {
      console.log(lined.data);
    });
 
// test for
for (let l = 0; l < array.length; l++) {
   console.log('hello');
   var sum = 0;
    for (let k = 0; k < array[l].length; k++) {
        sum += array[l][k];
    }
    //console.log(sum);
   totVal.push(sum);
    }
   
  return sum(result);
}


result array in console log. Also result[0] or result[1] or result[0][0]...don't work.


Code:
Array []

0: Array(24) [ 112, 112, 114, … ]

1: Array(24) [ 291, 173, 666, … ]

2: Array(24) [ 13, 14, 13, … ]

length: 3

<prototype>: Array []
scada-vis:771:11

----------

only solution I found is using inside the function

Code:
function readTrend( listeId, dayBefore, dayBase, total )
{

  var data = JSON.stringify({
    dates_curr: {
      start: getdate(dayBefore),
      end: getdate(dayBase)
    },
    ids: listeId,
  });
  var result = [];
  var totVal=[];
 
  $.post('/scada-vis/trends/fetch', { data }, function(trends) {

    trends = JSON.parse(trends);
    $.each(trends, function(_, trend) {
      if (total>0) {
        let totVal = 0
        for (let l = 0; l < trend.data.length; l++) {
           totVal += trend.data[l];
        }
          result.push(totVal);
       
      } else {
        result.push(trend.data);
      }
    });

  });
 
  return result;

}

However I can't understand why in the other solution the lenght and [x] don't work


RE: chartist to display nice pie... - domotiqa - 08.04.2024

I need help.
Not so good with Javascript... Sleepy 


I have this code:

Code:
function getdate(offset) {
  var date = new Date();

  date.setDate(date.getDate() + offset+1);

  var year = date.getFullYear();
  var month = date.getMonth() + 1;
  var day = date.getDate();

  return { year, month, day };
}






function getdata(nom, dayBefore, dayBase,total) {
    var result = [];
  var trendsName = [];
  var trendsAddress = [];
    var myJsonString='';

  //FIND GA NAME AND ADDRESS
  $.each(grp.tag(nom), function(id, object) {
    trendsName.push(object.name);
    trendsAddress.push(Scada.encodeGroupAddress(object.address));
  });

  // CREATE ARGUMENT
  var data = JSON.stringify({
    trends: trendsAddress,
    dates: {
      start: getdate(dayBefore),
      end: getdate(dayBase),
    },
    // resolution: 86400,
    // timestamps: true,
  });

  // TRENDS.LP POST
  $.post('/user/trends.lp', data, function(resp) {

    $.each(resp, function(id, object) {

      // SUM TO TOTAL
      if (total>0) {
        let totVal = 0;
        for (let l = 0; l < object.length; l++) {
           totVal += object[l];
        }
          result.push(trendsName[id],totVal);

      // NO TOTAL
      } else {
        result.push(trendsName[id],object);
      }
    });
 
  });
   
  return result;

}


My problem I can't iterate on the array on the function:

for example with


//last day
let day=getdata(classImage,-1,0,1);

this don't work. Lentgth return 0...

for (let i = 0; i < day .length; i++) {
console.log(day[i])
}

however a console.log of day show all result... Rolleyes  and a length. I gess there is something with scope/timelaps but I try also in jquery, with map... all same.

Code:
Array []

0: "PV - Active Energy No reset"

1: 16854

2: "General- Active Energy No reset"

3: 19329

length: 4

<prototype>: Array []


If our so nice admin could help me a bit, greatly appreciated.


RE: chartist to display nice pie... - admin - 08.04.2024

Does the request to trends.lp return anything?
I suppose you need two arrays if you want to display the data in the chart - one with labels (trend names) another with the actual data.


RE: chartist to display nice pie... - domotiqa - 08.04.2024

yes the right value.

It s just I can't iterate here for example:

            let day=getdata(classImage,-1,0,1);
            console.log(day)
            for (let l = 0; l < day.length; l++) {
              console.log(day[l])
            } 

the console.log(day)  return right value array with value, length...

if I console.log( day.length ) it say zero Dodgy

and so  the console.log(day[l]) never happen, I i log day.length it said zero.


I thing there is something with

Code:
$.ajaxSetup({async:false});  //execute synchronously



I add it and it works....
https://stackoverflow.com/questions/9269296/store-data-in-variable-from-post-jquery


RE: chartist to display nice pie... - hocine - 02.05.2024

Hello, 

Does anyone know how to integrate the legend in the Chartist pie like this exemple ?

Pie Chart


RE: chartist to display nice pie... - admin - 02.05.2024

Click "Show code" under the example and it will show the relevant code.


RE: chartist to display nice pie... - hocine - 03.05.2024

(02.05.2024, 10:39)admin Wrote: Click "Show code" under the example and it will show the relevant code.


I tried like that, but I don't have the color in front of the legend like in the example


Code:
$(function() {
  var chart;

  grp.listen('32/1/22', function(obj, type) {
    var planid = 12;
    var groups = ['32/2/19','32/2/21', '32/2/23','32/2/25','32/2/27','32/2/29','32/2/31','32/2/33','32/2/35','32/2/37','32/2/39','32/2/41'];

    var labels = [];
    var series = [];

    for (var group of groups) {
      var obj = grp.find(group);
      console.log(group, obj);
      labels.push(obj.name);
      series.push(obj.value);
    }

    var data = {
      labels: labels,
      series: series
    };

    var options = {
      width: '300px',
      height: '300px',
      donut: true,
      donutWidth: 50,
      donutSolid: true,
      startAngle: 270,
      showLabel: false
    };

    if (chart) {
      chart.update(data);
    } else {
      var el = $('<div class="chart"></div>').css({
        position: 'absolute',
        top: '750px',
        left: '1210px'
      }).appendTo('#plan-' + planid);

      chart = new Chartist.Pie('.chart', data, options);

      // Ajout des légendes
      var legendContainer = $('<div class="legend"></div>'); // Création du conteneur de légende
      data.labels.forEach(function(label, index) {
        legendContainer.append('<div><span class="dot" style="background-color: ' + chart.data.series[index].meta + '"></span>' + label + '</div>'); // Ajout de chaque élément de légende avec la couleur associée
      });
      el.append(legendContainer); // Ajout du conteneur de légende au graphique
    }
  }, true);
});



RE: chartist to display nice pie... - admin - 03.05.2024

A work-around trick is to use SVG with the same classes as the chart to display a color box next to the legend text:
Code:
var legendContainer = $('<div class="legend"></div>'); // Création du conteneur de légende  
var code = ('a').charCodeAt(0)
data.labels.forEach(function(label, index) {
  var letter = String.fromCharCode(index + code)
  var svg = '<svg width="16" height="16" class="ct-series-' + letter + '"><rect width="16" height="16" class="ct-slice-pie" /></svg>'
  legendContainer.append('<div>' + svg + ' ' +  label +' </div>'); // Ajout de chaque élément de légende avec la couleur associée
});
el.append(legendContainer); // Ajout du conteneur de légende au graphique



RE: chartist to display nice pie... - busta - 03.05.2024

(03.05.2024, 08:31)admin Wrote: A work-around trick is to use SVG with the same classes as the chart to display a color box next to the legend text:
Code:
var legendContainer = $('<div class="legend"></div>'); // Création du conteneur de légende   
var code = ('a').charCodeAt(0)
data.labels.forEach(function(label, index) {
  var letter = String.fromCharCode(index + code)
  var svg = '<svg width="16" height="16" class="ct-series-' + letter + '"><rect width="16" height="16" class="ct-slice-pie" /></svg>'
  legendContainer.append('<div>' + svg + ' ' +  label +' </div>'); // Ajout de chaque élément de légende avec la couleur associée
});
el.append(legendContainer); // Ajout du conteneur de légende au graphique

Thanks ADMIN you are a magician