ECharts - Documentation

Getting Started

Installation

ECharts can be integrated into your project in several ways. The primary methods are via a CDN, npm, or yarn.

CDN: The easiest way to get started is by including ECharts via a CDN link. Add the following script tag to your HTML file:

<script src="https://cdn.jsdelivr.net/npm/echarts@5.4.2/dist/echarts.min.js"></script>

Replace 5.4.2 with the desired version number. You can find the latest version on the ECharts website.

npm: If you’re using npm, install ECharts using:

npm install echarts

yarn: If you prefer yarn, use:

yarn add echarts

After installation via npm or yarn, you’ll need to import ECharts into your JavaScript code (see “Including ECharts in your project” below).

Basic Example

A minimal ECharts example involves creating a DOM element for the chart and then initializing the chart instance. This example creates a simple line chart.

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>ECharts Example</title>
</head>
<body>
  <div id="main" style="width: 600px;height:400px;"></div>
  <script src="https://cdn.jsdelivr.net/npm/echarts@5.4.2/dist/echarts.min.js"></script>
  <script type="text/javascript">
    // based on prepared DOM, initialize echarts instance
    var myChart = echarts.init(document.getElementById('main'));

    // specify chart configuration item and data
    var 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' }]
    };

    // use configuration item and data specified to show chart
    myChart.setOption(option);
  </script>
</body>
</html>

Including ECharts in your project

After installation using npm or yarn, import ECharts into your project’s JavaScript file. Using ES modules:

import * as echarts from 'echarts';

// ... your chart initialization code ...

Or, using CommonJS:

const echarts = require('echarts');

// ... your chart initialization code ...

Remember to adjust the import statement based on your module system and project structure.

First Chart

The “Basic Example” provides a complete, runnable example to create your first chart. The code creates a div element to hold the chart, initializes the ECharts instance using echarts.init(), defines the chart’s options (data and configuration), and finally sets the options using myChart.setOption(). This will render a simple line chart in your browser. Remember to include the ECharts library as described in the “Installation” section.

Chart Types

Line Charts

Line charts are used to visualize data trends over time or across categories. They are ideal for showing continuous data and highlighting changes in values. ECharts’ line chart offers features like smoothing, data points, tooltips, and various customization options for axes, lines, and labels. You can specify different line styles, colors, and add markers to highlight specific data points.

Bar Charts

Bar charts represent data using rectangular bars, making it easy to compare values across different categories. ECharts supports both vertical and horizontal bar charts, allowing for flexibility in presentation. Features like stacking, grouping, and data labels enhance the chart’s readability and informativeness.

Scatter Charts

Scatter charts display data as points on a two-dimensional plane, showing the relationship between two variables. ECharts’ scatter charts allow for the visualization of large datasets, offering features like zooming, panning, and the ability to add labels and tooltips to individual data points. Different point shapes and sizes can be used to represent additional data dimensions.

Pie Charts

Pie charts represent proportions or percentages of a whole. ECharts’ pie charts provide options for labeling slices with percentages or values, adjusting slice positions, and customizing the appearance of the chart, including colors and styles. They are useful for showing the relative contribution of different categories to a total.

Map Charts

Map charts visualize data geographically on a map. ECharts integrates with various map providers and allows for the visualization of geographical data using different visual representations like heatmaps, points, and regions. You can customize the map’s appearance, add tooltips, and interact with map elements.

Radar Charts

Radar charts display multivariate data in a radial fashion. Each variable is represented by an axis, and data points are plotted in relation to these axes. ECharts supports multiple radar series, different area styles, and customization of the chart’s appearance.

Heatmaps

Heatmaps use color gradients to represent data density or magnitude in a matrix format. ECharts’ heatmaps allow for the visualization of large datasets, offering features like zooming, panning, and custom color scales. They are useful for identifying patterns and trends in data distributions.

Treemaps

Treemaps display hierarchical data using nested rectangles, where the size of each rectangle represents the value of the corresponding data element. ECharts’ treemaps allow for interactive exploration of hierarchical data, offering features like drill-down and tooltips.

Graph Charts

Graph charts visualize relationships between nodes and edges in a network. ECharts supports various graph layouts, node styles, and edge types, enabling the representation of complex network structures. Interactive features like node highlighting and path tracing enhance the analysis of network relationships.

Gauge Charts

Gauge charts display a single value relative to a range, often used for monitoring metrics like speed, temperature, or progress. ECharts’ gauge charts provide customizable ranges, pointers, and labels, allowing for clear representation of a single key value within a defined context.

Funnel Charts

Funnel charts represent a process or stages of a workflow, showing the flow of data through different steps. ECharts’ funnel charts allow for visualization of the number of items or data points at each stage, highlighting drop-offs or bottlenecks in the process.

Candlestick Charts

Candlestick charts are commonly used in financial analysis to visualize price movements over time. Each candlestick represents the opening, closing, high, and low prices for a given period. ECharts provides tools to create and customize these charts effectively.

Boxplot Charts

Boxplot charts (also known as box and whisker plots) show the distribution of data through quartiles. They visually represent the median, quartiles, and outliers, providing a quick understanding of the data’s spread and central tendency.

Parallel Charts

Parallel charts are used to compare multiple data attributes simultaneously. Each attribute is represented on a separate axis, and data points are linked across the axes. This allows for identifying patterns and correlations among different attributes.

Sankey Diagrams

Sankey diagrams visualize the flow of data or resources between different nodes. The width of the links between nodes represents the magnitude of the flow, making it easy to identify major flows and bottlenecks within a system.

Chart Components

Titles

Titles provide context and a clear description for your charts. ECharts allows you to add main titles, sub-titles, and link titles to your charts. You can customize their text, font, position, and styling to suit your needs. Multiple titles can be added for richer descriptions.

Legends

Legends provide a visual key to interpret the different series and data within your chart. ECharts lets you customize the legend’s position (top, bottom, left, right), orientation (vertical, horizontal), and item appearance (colors, labels, etc.). Interactive legends allow users to selectively show or hide series.

Tooltips

Tooltips provide interactive data information upon hovering over chart elements. ECharts allows for extensive customization of tooltip content, formatting, position, and trigger behavior (item, axis). You can display various data fields and format them dynamically.

Grids

Grids organize and layout multiple charts or chart components within a single container. ECharts allows you to create multiple grids on a canvas, positioning them to create complex dashboard layouts. Grids define the coordinate system for the charts they contain.

Axis

Axes define the coordinate system for your chart and provide scaling and labeling for your data. ECharts offers both cartesian (x, y) axes and polar axes. You can customize axis types (value, category, time, log), labels, scales, and appearances.

Data Zoom

Data zoom components enable users to interactively zoom in and out of large datasets. ECharts provides both inside and outside zoom controls, allowing for fine-grained control over the visible data range. Different zoom modes (slider, inside, etc.) provide flexibility in user interaction.

Visual Map

Visual maps provide a visual representation of a data range, often used to encode data values to colors or sizes. ECharts’ visual maps allow you to create color gradients or size scales linked to a data series or dimension, helping visualize data magnitude.

Timelines

Timelines allow for the sequential display of charts across time. ECharts’ timelines facilitate the creation of animated transitions and the selection of different time periods within a larger dataset. They are excellent for visualizing changes over time.

Data Browsing

Data browsing allows users to explore data interactively through a series of controls. ECharts provides various features, such as data selection, filtering, and pagination for navigating large datasets and focusing on specific aspects of your data.

Marklines and Markpoints

Marklines and markpoints add annotations directly onto the chart, highlighting specific data points or trends. Marklines draw lines across the chart while markpoints add special visual markers to individual data points. These components enhance the chart’s ability to communicate specific information.

Data Handling

Data Formats

ECharts accepts data in various formats, primarily arrays and objects. The most common format is an array of arrays, where each inner array represents a data item. For example, for a line chart:

[
    [10, 20],
    [20, 30],
    [30, 40]
]

Alternatively, you can use an array of objects, especially useful when you have multiple dimensions:

[
    {value: 10, name: 'A'},
    {value: 20, name: 'B'},
    {value: 30, name: 'C'}
]

ECharts also supports other formats, including those compatible with common data formats like CSV or JSON. Consult the ECharts documentation for the most comprehensive list of supported data formats.

Data Loading

Data can be loaded directly into the chart options or loaded asynchronously. For simpler charts, direct data inclusion is sufficient. For complex or large datasets, asynchronous loading via $.get, fetch, or other AJAX methods is recommended. This avoids blocking the rendering process.

Example of asynchronous loading (using fetch):

fetch('data.json')
  .then(response => response.json())
  .then(data => {
    myChart.setOption({
      series: [{ data: data }]
    });
  });

Data Filtering

ECharts doesn’t directly handle data filtering within its core functionality. Data filtering should be performed before passing the data to the chart. You can use JavaScript’s built-in array methods like filter to pre-process your data:

const filteredData = originalData.filter(item => item.value > 15);
myChart.setOption({ series: [{ data: filteredData }] });

Data Transformation

Similar to filtering, data transformation is best handled before passing data to ECharts. You can use JavaScript functions to reshape or modify your data as needed. This might involve calculating new values, aggregating data, or reformatting it for better chart representation.

For example, calculating a moving average:

function calculateMovingAverage(data, windowSize) {
  // ...Implementation to calculate moving average...
  return transformedData;
}
const transformedData = calculateMovingAverage(originalData, 3);
myChart.setOption({ series: [{ data: transformedData }] });

Working with Large Datasets

For large datasets, performance optimization is crucial. Techniques include:

Remember to consult the ECharts documentation and examples for optimal performance strategies tailored to your specific chart type and dataset size.

Customization

Themes

ECharts provides built-in themes that alter the overall look and feel of your charts. You can select a theme when initializing the chart or apply a theme later using setOption(). Themes modify aspects like colors, fonts, and component styles. ECharts also allows creating and using custom themes by defining a JSON configuration object. This allows for a consistent visual style across your applications.

Styling Charts

Beyond themes, fine-grained styling is achieved by directly manipulating the chart’s options. You can customize virtually every visual element, from colors and fonts to axis labels, data point shapes, and tooltip appearances. ECharts’ extensive API documentation provides details on the properties you can adjust for each chart component. This includes using CSS directly within certain aspects of the charts.

Custom Components

For extending ECharts’ functionality, you can create and integrate custom components. This allows adding entirely new visual elements or extending existing ones to match your specific needs. The process involves registering a custom component and configuring it within your chart options. ECharts provides clear documentation on the required structure and methods for developing custom components.

Advanced Configuration Options

ECharts offers numerous advanced configuration options that allow fine-tuning chart behavior and performance. These options control aspects like animation, data interaction, event handling, and rendering performance. Exploring these advanced options allows for creating highly customized and optimized charts, catering to specific application requirements. Areas like performance optimization for large datasets and custom interactions often fall under these advanced configurations.

Events and Interactions

Event Handling

ECharts provides a rich set of events that trigger on various user interactions and chart updates. You can register event listeners to respond to these events and implement custom actions. Common events include click, mouseover, mouseout, legendselectchanged, and others specific to chart types and components. Event handlers are typically attached using the on method of the chart instance. The event object passed to the handler contains information about the event.

Example:

myChart.on('click', params => {
  console.log('Chart clicked at:', params);
  // Your custom logic here...
});

Chart Interactions

ECharts offers several built-in chart interactions, such as:

These interactions are usually enabled by default, but their behavior can be customized (see “Customizing Interactions” below).

Customizing Interactions

ECharts allows extensive customization of interactions. You can:

Customizing interactions requires a good understanding of ECharts’ event system and its API for manipulating chart components. This often involves combining event handling with direct manipulation of chart options.

Advanced Techniques

Dynamic Chart Updates

Updating charts dynamically is crucial for creating responsive and interactive visualizations. ECharts allows for efficient updates using setOption(). For incremental updates, use the setOption method with the notMerge option set to true to replace the entire option object. For merging updates, leave notMerge as false (default) to merge new options with existing ones. This allows selective modification of chart data or configuration without redrawing the entire chart. Efficient update strategies are key for maintaining a smooth user experience, especially with large datasets.

Chart Animations

ECharts provides built-in animation capabilities for visually engaging charts. Animations can be enabled or disabled globally or on a per-series basis. You can customize animation duration, easing functions, and other properties to fine-tune the visual effect. Well-designed animations improve the user experience by making changes more apparent and understandable. However, excessive or poorly implemented animations can negatively impact performance.

Interactive Elements

Interactive elements enhance user engagement and allow for deeper data exploration. Techniques include:

These features require combining ECharts’ event handling and API to update chart options in response to user interactions.

Performance Optimization

Optimizing performance is critical for smooth visualizations, especially with large datasets. Techniques include:

These optimizations often involve balancing visual fidelity with performance to achieve the best user experience. Profiling your code can help identify performance bottlenecks. The techniques used often depend on the scale and nature of your data and the complexity of your chart.

API Reference

ECharts Instance Methods

The ECharts instance, obtained via echarts.init(), exposes several methods for interacting with and controlling the chart. Key methods include:

The complete list of instance methods and their detailed descriptions can be found in the official ECharts API documentation.

Option Configuration Details

The option object passed to setOption() defines the chart’s appearance, behavior, and data. This object is hierarchical, with properties controlling various aspects like:

Detailed descriptions and available properties for each option are thoroughly documented in the official ECharts API reference.

Component APIs

ECharts components (like axes, legends, tooltips) often have their own APIs for more granular control. These APIs are usually accessed through properties within the main option object. For example, to configure the x-axis labels:

option = {
  xAxis: {
    type: 'category',
    data: ['Mon', 'Tue', 'Wed'],
    axisLabel: { // Component-specific API
      rotate: 45,
      formatter: '{value} days'
    }
  }
};

Consult the official API documentation to find component-specific APIs and their parameters.

Utility Functions

ECharts provides utility functions that are helpful for various tasks:

These utility functions are used for tasks like data processing, graphic element creation, and other common operations. The specific set of utility functions is documented in the official ECharts API. The echarts namespace houses many of these utility functions, offering a range of options for common development tasks.

Troubleshooting

Common Issues

Several common issues arise when working with ECharts:

Debugging Tips

Effective debugging techniques for ECharts include:

Error Messages

ECharts error messages often provide valuable clues for resolving issues. Pay close attention to:

If an error message isn’t immediately clear, use a search engine to find potential solutions or consult ECharts’ issue tracker or community forums. Providing the error message and relevant code snippets when seeking assistance will help others diagnose your problem more effectively.

Examples and Tutorials

Basic Chart Examples

The ECharts website and documentation provide a wealth of basic chart examples covering various chart types. These examples showcase the fundamental usage of ECharts, demonstrating how to create simple charts with basic configurations. They are excellent starting points for learning the core concepts and syntax of ECharts. These usually include simple line charts, bar charts, pie charts, and scatter charts, demonstrating basic data input and minimal configurations.

Advanced Chart Examples

Beyond basic charts, ECharts offers examples showcasing advanced features and techniques. These examples demonstrate more complex configurations, including custom components, interactive elements, data transformations, and animations. They provide insights into creating more sophisticated and feature-rich visualizations. Advanced examples might involve combining multiple chart types, creating custom visual maps, utilizing data zooming and panning, incorporating tooltips with custom content, and more.

Real-World Applications

To illustrate practical usage, ECharts provides examples demonstrating how the library can be applied in real-world scenarios. These examples showcase diverse applications of ECharts, providing inspiration and practical guidance for integrating ECharts into various projects. They might demonstrate examples in dashboards, data analysis tools, or even specific industry applications, providing realistic contexts and implementation approaches. These can range from simple dashboards showing key metrics to complex interactive data explorations.

Code Examples

Throughout the ECharts documentation and website, numerous code examples are provided. These examples are written in JavaScript and demonstrate various aspects of ECharts, from basic chart creation to advanced customization. The examples are typically concise and well-commented, making them easy to understand and adapt to specific needs. They often accompany explanations, making them effective learning tools and practical references for implementing specific features or configurations within your projects. The examples showcase both the declarative option setting and the imperative API interaction approaches.