阿里云主机折上折
  • 微信号
Current Site:Index > Time series analysis display

Time series analysis display

Author:Chuan Chen 阅读数:2046人阅读 分类: ECharts

Characteristics of Time Series Data

Time series data consists of a sequence of observations ordered by time, commonly found in fields such as finance, meteorology, and IoT. This type of data exhibits several distinct features: temporal dependency (adjacent time points are often correlated), trend (long-term upward or downward movement), seasonality (periodic fluctuations), and noise interference. For example, minute-by-minute stock price records or hourly temperature monitoring data for a city are typical time series.

// Example time series data format
const timeSeriesData = [
  { date: '2023-01-01', value: 12.5 },
  { date: '2023-01-02', value: 15.2 },
  { date: '2023-01-03', value: 18.7 },
  // More data points...
];

Basic ECharts Configuration

Initializing ECharts requires preparing a DOM container and setting up basic configuration options. For time series visualization, the xAxis must be set to the 'time' type, and the yAxis should be adjusted based on the actual data range. Enabling the dataZoom component is recommended for time range zooming, which is particularly important for long-period time series.

const chart = echarts.init(document.getElementById('chart-container'));

const option = {
  tooltip: {
    trigger: 'axis',
    formatter: params => {
      const date = new Date(params[0].value[0]);
      return `${date.toLocaleString()}<br/>Value: ${params[0].value[1]}`;
    }
  },
  xAxis: {
    type: 'time',
    axisLabel: {
      formatter: '{yyyy}-{MM}-{dd}'
    }
  },
  yAxis: { type: 'value' },
  dataZoom: [{
    type: 'inside',
    start: 0,
    end: 100
  }, {
    start: 0,
    end: 100
  }]
};

Line Chart Implementation

Line charts are the most intuitive way to display trends in time series data. ECharts' line series supports optimizations for large datasets. Setting series-line.showSymbol to false can improve performance. For high-frequency data (e.g., second-level stock data), enabling the large mode and progressive rendering is recommended.

// Add line chart series
option.series = [{
  type: 'line',
  data: timeSeriesData.map(item => [
    new Date(item.date).getTime(),
    item.value
  ]),
  smooth: true,
  areaStyle: {
    opacity: 0.3
  },
  lineStyle: {
    width: 2
  },
  symbol: 'none',
  large: true,
  progressive: 1000
}];

chart.setOption(option);

Multi-Series Comparison

When comparing multiple time series, use different colors to distinguish series and add legend interactions. For example, to display temperature changes in Beijing and Shanghai simultaneously, the visualMap component can map threshold ranges to colors.

const multiSeriesOption = {
  legend: {
    data: ['Beijing', 'Shanghai']
  },
  series: [
    {
      name: 'Beijing',
      type: 'line',
      data: beijingData,
      itemStyle: { color: '#c23531' }
    },
    {
      name: 'Shanghai',
      type: 'line',
      data: shanghaiData,
      itemStyle: { color: '#2f4554' }
    }
  ],
  visualMap: {
    top: 50,
    right: 10,
    pieces: [
      { gt: 30, color: '#d94e5d' }, // High temperature (red)
      { gt: 20, lte: 30, color: '#eac736' }, // Normal temperature (yellow)
      { lte: 20, color: '#50a3ba' } // Low temperature (blue)
    ]
  }
};

Dynamic Data Updates

Real-time time series require dynamic update mechanisms. ECharts provides the appendData method to efficiently append new data points, and the notMerge parameter in setOption enables smooth animations. Below is a simulation of a real-time temperature monitoring scenario:

// Simulate real-time data generation
function generateRealTimeData(lastPoint) {
  return {
    date: new Date(lastPoint.date.getTime() + 3600000),
    value: lastPoint.value + (Math.random() * 2 - 1)
  };
}

// Update chart periodically
setInterval(() => {
  const lastData = timeSeriesData[timeSeriesData.length - 1];
  const newData = generateRealTimeData(lastData);
  timeSeriesData.push(newData);
  
  chart.appendData({
    seriesIndex: 0,
    data: [[new Date(newData.date).getTime(), newData.value]]
  });
}, 1000);

Enhanced Interaction Features

Time series analysis often requires detailed inspection. By configuring the toolbox toolset, the following interactive features can be added:

  • Data range zooming
  • Restore original view
  • Save as image
  • Dynamic type switching (e.g., switch to bar chart)
option.toolbox = {
  feature: {
    dataZoom: {
      yAxisIndex: 'none'
    },
    restore: {},
    saveAsImage: {},
    magicType: {
      type: ['line', 'bar']
    }
  }
};

Performance Optimization Strategies

When handling large-scale time series data (e.g., over 100,000 points), special optimization techniques are required:

  1. Enable large mode and set progressive for chunked rendering
  2. Use downsampling algorithms to reduce display density
  3. Preprocess static historical data using webWorker
// Large dataset configuration example
const bigDataOption = {
  series: [{
    type: 'line',
    large: true,
    progressive: 2000,
    data: hugeTimeSeriesData,
    sampling: 'lttb', // Use Largest-Triangle-Three-Buckets downsampling
    dimensions: ['time', 'value']
  }]
};

Special Effects Implementation

For specific analysis scenarios, mark lines and mark points can highlight key events:

  • Mark lines: Display averages, threshold lines
  • Mark points: Annotate extreme values, outliers
  • Color gradients: Reflect data intensity changes
option.series[0].markLine = {
  silent: true,
  data: [{
    type: 'average',
    name: 'Average'
  }, {
    yAxis: 30,
    name: 'High Temp Threshold'
  }]
};

option.series[0].markPoint = {
  data: [
    { type: 'max', name: 'Max' },
    { type: 'min', name: 'Min' }
  ]
};

Mobile Adaptation

Time series display on mobile devices requires special handling:

  1. Increase clickable areas
  2. Simplify tooltip display
  3. Responsive font size adjustments
function adaptMobile() {
  if (window.innerWidth < 768) {
    option.tooltip.confine = true;
    option.axisLabel.fontSize = 10;
    option.dataZoom[1].height = 20;
    chart.resize();
  }
}
window.addEventListener('resize', adaptMobile);

Server-Side Data Integration

Real-world projects typically fetch time series data from backend APIs. Below is a typical data fetching and processing workflow:

async function fetchTimeSeries() {
  try {
    const response = await fetch('/api/timeseries');
    const rawData = await response.json();
    
    // Data format conversion
    const processedData = rawData.map(item => ({
      date: new Date(item.timestamp),
      value: parseFloat(item.measurement)
    }));
    
    // Update chart
    chart.setOption({
      dataset: {
        source: processedData
      }
    });
  } catch (error) {
    console.error('Data loading failed:', error);
  }
}

Timezone Handling Solutions

Cross-timezone applications require unified time display. It is recommended to store time in UTC on the frontend and convert it to local time for display:

option.xAxis.axisLabel = {
  formatter: function(value) {
    const date = new Date(value);
    return `${date.getHours()}:${date.getMinutes()}`;
  }
};

// Or display multiple timezones in tooltip
option.tooltip.formatter = function(params) {
  const date = new Date(params[0].value[0]);
  return `
    UTC: ${date.toUTCString()}<br/>
    Local: ${date.toLocaleString()}<br/>
    Value: ${params[0].value[1]}
  `;
};

本站部分内容来自互联网,一切版权均归源网站或源作者所有。

如果侵犯了你的权益请来信告知我们删除。邮箱:cc@cccx.cn

Front End Chuan

Front End Chuan, Chen Chuan's Code Teahouse 🍵, specializing in exorcising all kinds of stubborn bugs 💻. Daily serving baldness-warning-level development insights 🛠️, with a bonus of one-liners that'll make you laugh for ten years 🐟. Occasionally drops pixel-perfect romance brewed in a coffee cup ☕.