Jump to content

ECharts: Difference between revisions

From Torben's Wiki
mNo edit summary
 
(No difference)

Latest revision as of 22:46, 30 October 2024

Docu

Examples

// init
const myChart = echarts.init(document.getElementById('div_chart_24h'))

// Load data from a local JSON file in same dir
fetch('MT681_watt_24h.json')
  .then(response => response.json())
  .then(rawData => {
    // raw: {"1720724640000":54.0,"1720724760000":53.5,...}
    // Convert data to ECharts format (x: timestamp, y: value) and set name to time
    const seriesData = Object.entries(rawData).map(([timestamp, value]) => ({
      name: new Date(parseInt(timestamp)).toLocaleTimeString(['DE'], {
        hour: '2-digit',
        minute: '2-digit'
      }),
      value: [parseInt(timestamp), value]
      // [name: '12:23' value: [1720724640000, 123.3]]
    }))

    const last = seriesData[seriesData.length - 1]

    // calc kWh sum
    let pos = 0
    let neg = 0
    for (const data of seriesData) {
      const value = data.value[1]
      if (value >= 0) {
        pos += value
      } else {
        neg -= value
      }
    }
    // average watt over all data
    pos /= seriesData.length
    neg /= seriesData.length
    // kWh over 24h
    pos = (pos * 24) / 1000
    neg = (neg * 24) / 1000
    // rounding
    pos = Math.round(10 * pos) / 10
    neg = Math.round(10 * neg) / 10

    const textTitle =
      'Stromzähler: ' + last['value'][1] + 'W @' + last['name'] + ' ' + pos + '/' + neg + 'kWh'

    const option = {
      xAxis: {
        type: 'time',
        splitLine: { show: true } // grid
      },
      yAxis: {
        type: 'value',
        splitLine: { show: true } // grid
      },
      series: [
        {
          type: 'line',
          data: seriesData,
          showSymbol: false,
          smooth: false,
          areaStyle: {} // To enable coloring under the graph
        }
      ],
      visualMap: {
        show: false,
        min: 0,
        max: 1,
        inRange: {
          color: ['green', 'red']
        },
        calculable: true
      },
      animation: false,
      title: {
        text: textTitle
      },
      //   axisPointer: { show: true, snap: true },
      tooltip: {
        trigger: 'axis',
        formatter: function (params) {
          let p = params
          if (Array.isArray(params)) {
            p = params[0]
          }
          return p.name + '
' + p.value[1] + 'W' } }, dataZoom: [ { xAxisIndex: 0, filterMode: 'none' }, { yAxisIndex: 0, filterMode: 'none' } ] } myChart.setOption(option) }) .catch(error => { console.error('Error loading data:', error) })