阿里云主机折上折
  • 微信号
Current Site:Index > Line Chart

Line Chart

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

Line Chart Implementation

The line chart is one of the most common chart types in data visualization, used to display trends in data over time or other continuous variables. ECharts provides rich configuration options to customize the appearance and behavior of line charts, from basic line styles to complex data interactions, all of which can be easily implemented.

Basic Line Chart Implementation

The simplest line chart only requires x-axis data and corresponding y-axis data. Here is a basic example:

option = {
    xAxis: {
        type: 'category',
        data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
    },
    yAxis: {
        type: 'value'
    },
    series: [{
        data: [820, 932, 901, 934, 1290, 1330, 1320],
        type: 'line'
    }]
};

This code generates a line chart showing numerical changes over a week. The xAxis type is set to 'category' to represent discrete categorical data, while the yAxis type is set to 'value' for continuous numerical data.

Multi-Series Line Chart

In practical applications, it is often necessary to compare multiple data series simultaneously:

option = {
    xAxis: {
        type: 'category',
        data: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun']
    },
    yAxis: {
        type: 'value'
    },
    series: [
        {
            name: 'Product A',
            type: 'line',
            data: [120, 132, 101, 134, 90, 230]
        },
        {
            name: 'Product B',
            type: 'line',
            data: [220, 182, 191, 234, 290, 330]
        }
    ]
};

This example compares sales data for two products over six months. By setting different name properties for each series, they can be distinguished in the legend.

Line Chart Style Customization

ECharts offers a variety of style configuration options:

series: [{
    name: 'Email Marketing',
    type: 'line',
    stack: 'Total',
    data: [120, 132, 101, 134, 90, 230, 210],
    itemStyle: {
        color: '#c23531',
        borderColor: '#c23531',
        borderWidth: 2
    },
    lineStyle: {
        width: 3,
        type: 'dashed'
    },
    symbol: 'circle',
    symbolSize: 8,
    areaStyle: {
        color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: 'rgba(194, 53, 49, 0.5)' },
            { offset: 1, color: 'rgba(194, 53, 49, 0.1)' }
        ])
    }
}]

This code configures:

  • Line color and width
  • Data point symbol shape and size
  • Dashed line style
  • Gradient-filled area

Smooth Curves and Step Lines

ECharts supports various line representations:

series: [
    {
        name: 'Smooth Curve',
        type: 'line',
        smooth: true,
        data: [12, 15, 11, 14, 19, 23, 21]
    },
    {
        name: 'Step Line',
        type: 'line',
        step: 'middle', // Options: 'start', 'middle', 'end'
        data: [22, 25, 21, 24, 29, 33, 31]
    }
]

Setting smooth to true generates a smooth curve, while the step property creates a step-like line chart, suitable for displaying discrete state changes.

Dynamic Data Updates

Line charts often require dynamic data updates. ECharts provides a simple API:

// Initialize the chart
const myChart = echarts.init(document.getElementById('main'));
myChart.setOption(option);

// Simulate real-time data updates
setInterval(function() {
    const oldData = option.series[0].data;
    // Remove the first data point and add a new random data point
    const newData = oldData.slice(1);
    newData.push(Math.round(Math.random() * 1000));
    
    option.series[0].data = newData;
    myChart.setOption(option);
}, 2000);

This code removes the oldest data point and adds a new random data point every 2 seconds, creating a dynamic scrolling effect.

Large Data Optimization

When dealing with a large number of data points, performance optimization is necessary:

option = {
    xAxis: {
        type: 'value',
        min: 0,
        max: 10000
    },
    yAxis: {
        type: 'value'
    },
    series: [{
        type: 'line',
        data: generateLargeData(10000), // Generate 10,000 data points
        progressive: 200,
        progressiveThreshold: 3000,
        animation: false
    }]
};

function generateLargeData(count) {
    const data = [];
    for (let i = 0; i < count; i++) {
        data.push([i, Math.sin(i / 100) * 100 + Math.random() * 10]);
    }
    return data;
}

Key optimization parameters:

  • progressive: Chunk size for progressive rendering
  • progressiveThreshold: Threshold to enable progressive rendering
  • animation: Disable animations to improve performance

Enhanced Interaction Features

ECharts offers rich interactive features:

option = {
    tooltip: {
        trigger: 'axis',
        axisPointer: {
            type: 'cross',
            label: {
                backgroundColor: '#6a7985'
            }
        }
    },
    toolbox: {
        feature: {
            dataZoom: {
                yAxisIndex: 'none'
            },
            restore: {},
            saveAsImage: {}
        }
    },
    dataZoom: [
        {
            type: 'inside',
            start: 0,
            end: 100
        },
        {
            start: 0,
            end: 100
        }
    ],
    series: [
        {
            data: [120, 132, 101, 134, 90, 230, 210],
            type: 'line',
            markPoint: {
                data: [
                    { type: 'max', name: 'Max' },
                    { type: 'min', name: 'Min' }
                ]
            },
            markLine: {
                data: [
                    { type: 'average', name: 'Average' }
                ]
            }
        }
    ]
};

This code implements:

  • Crosshair tooltip
  • Data zoom
  • Max/min markers
  • Average reference line
  • Toolbox (save image, reset, etc.)

Multi-Axis Line Chart

When displaying data with different units, multiple y-axes can be used:

option = {
    tooltip: {
        trigger: 'axis',
        axisPointer: {
            type: 'cross'
        }
    },
    xAxis: {
        type: 'category',
        data: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun']
    },
    yAxis: [
        {
            type: 'value',
            name: 'Temperature',
            position: 'left',
            axisLabel: {
                formatter: '{value} °C'
            }
        },
        {
            type: 'value',
            name: 'Precipitation',
            position: 'right',
            axisLabel: {
                formatter: '{value} ml'
            }
        }
    ],
    series: [
        {
            name: 'Temperature',
            type: 'line',
            yAxisIndex: 0,
            data: [12, 15, 11, 14, 19, 23, 21]
        },
        {
            name: 'Precipitation',
            type: 'line',
            yAxisIndex: 1,
            data: [120, 132, 101, 134, 90, 230, 210]
        }
    ]
};

This example displays temperature and precipitation data with different units, using left and right y-axes respectively.

Timeline Line Chart

For time-series data, ECharts provides specialized timeline support:

function randomData() {
    now = new Date(+now + oneDay);
    value = Math.random() * 1000 - 500;
    return {
        name: now.toString(),
        value: [
            [now.getFullYear(), now.getMonth() + 1, now.getDate()].join('/'),
            Math.round(value)
        ]
    };
}

let now = new Date(2023, 0, 1);
const oneDay = 24 * 3600 * 1000;
const data = [];
for (let i = 0; i < 100; i++) {
    data.push(randomData());
}

option = {
    tooltip: {
        trigger: 'axis',
        formatter: function(params) {
            return params[0].name + '<br/>' + 
                   params[0].seriesName + ': ' + params[0].value[1];
        }
    },
    xAxis: {
        type: 'time',
        boundaryGap: false
    },
    yAxis: {
        type: 'value',
        boundaryGap: [0, '30%']
    },
    series: [{
        name: 'Simulated Data',
        type: 'line',
        showSymbol: false,
        data: data
    }]
};

This code creates a dynamically generated time-series line chart. Setting the xAxis type to 'time' automatically handles time data formatting and scaling.

Responsive Design

Ensure the line chart displays correctly on different screen sizes:

const chartDom = document.getElementById('main');
const myChart = echarts.init(chartDom);

function resizeChart() {
    myChart.resize();
}

window.addEventListener('resize', resizeChart);

// Initial setup
option = {
    // ... Chart configuration
    grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        containLabel: true
    }
};
myChart.setOption(option);

Key points:

  • Listen for window resize events and call the resize method
  • Use percentages for grid margins instead of fixed pixels
  • Set containLabel: true to prevent label overflow

Themes and Custom Rendering

ECharts supports theme customization and custom series rendering:

// Register a theme
echarts.registerTheme('my_theme', {
    color: ['#dd6b66', '#759aa0', '#e69d87', '#8dc1a9', '#ea7e53'],
    backgroundColor: '#f5f5f5',
    textStyle: {
        fontFamily: 'Arial, sans-serif'
    }
});

// Initialize with the theme
const myChart = echarts.init(document.getElementById('main'), 'my_theme');

// Custom series
option = {
    series: [{
        type: 'custom',
        renderItem: function(params, api) {
            const coord = api.coord([api.value(0), api.value(1)]);
            return {
                type: 'circle',
                shape: {
                    cx: coord[0],
                    cy: coord[1],
                    r: 5
                },
                style: {
                    fill: api.visual('color')
                }
            };
        },
        data: [[10, 20], [30, 40], [50, 60]]
    }]
};

This example demonstrates how to:

  1. Register and use a custom theme
  2. Use the custom series to implement fully custom rendering logic

Combining Line Charts with Other Chart Types

Line charts are often combined with other chart types:

option = {
    tooltip: {
        trigger: 'axis',
        axisPointer: {
            type: 'cross'
        }
    },
    legend: {
        data: ['Evaporation', 'Precipitation', 'Average Temperature']
    },
    xAxis: [
        {
            type: 'category',
            data: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun']
        }
    ],
    yAxis: [
        {
            type: 'value',
            name: 'Water Volume',
            min: 0,
            max: 250,
            interval: 50
        },
        {
            type: 'value',
            name: 'Temperature',
            min: 0,
            max: 25,
            interval: 5
        }
    ],
    series: [
        {
            name: 'Evaporation',
            type: 'bar',
            data: [50, 70, 60, 80, 75, 90]
        },
        {
            name: 'Precipitation',
            type: 'bar',
            data: [120, 132, 101, 134, 90, 230]
        },
        {
            name: 'Average Temperature',
            type: 'line',
            yAxisIndex: 1,
            data: [12, 15, 11, 14, 19, 23]
        }
    ]
};

This combined chart displays both bar and line charts, sharing the x-axis but using different y-axes, making it suitable for displaying related but differently scaled data.

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

如果侵犯了你的权益请来信告知我们删除。邮箱: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 ☕.