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).
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
.setOption(option);
myChart</script>
</body>
</html>
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.
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.
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 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 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 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 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 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 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 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 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 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 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 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 (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 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 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.
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 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 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 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.
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 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 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 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 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 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.
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 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 => {
.setOption({
myChartseries: [{ data: data }]
;
}); })
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);
.setOption({ series: [{ data: filteredData }] }); myChart
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);
.setOption({ series: [{ data: transformedData }] }); myChart
For large datasets, performance optimization is crucial. Techniques include:
dataZoom
that can help with this.Remember to consult the ECharts documentation and examples for optimal performance strategies tailored to your specific chart type and dataset size.
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.
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.
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.
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.
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:
.on('click', params => {
myChartconsole.log('Chart clicked at:', params);
// Your custom logic here...
; })
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).
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.
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.
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 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.
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.
The ECharts instance, obtained via echarts.init()
, exposes several methods for interacting with and controlling the chart. Key methods include:
setOption(option, notMerge)
: Sets or updates the chart options. notMerge
(boolean) controls whether to merge the new options with existing ones or replace them entirely.getOption()
: Retrieves the current chart options.resize()
: Resizes the chart to fit its container. Useful when the container’s dimensions change dynamically.dispose()
: Destroys the chart instance, releasing resources. Important for cleanup when the chart is no longer needed.on(eventName, eventHandler)
: Registers an event listener for a specific event.off(eventName, eventHandler)
: Removes an event listener.getDataURL(opts)
: Returns a data URL of the chart image. Allows saving the chart as an image.convertToPixel(seriesIndex, dataIndex)
: Converts data coordinates to pixel coordinates. Useful for custom annotations or interactions.convertFromPixel(seriesIndex, dataIndex)
: Converts pixel coordinates to data coordinates.The complete list of instance methods and their detailed descriptions can be found in the official ECharts API documentation.
The option
object passed to setOption()
defines the chart’s appearance, behavior, and data. This object is hierarchical, with properties controlling various aspects like:
title
: Chart title settings.legend
: Legend settings.tooltip
: Tooltip settings.grid
: Grid layout settings.xAxis
, yAxis
: Axis settings.series
: Data series configuration. Each series has its own options, depending on the chart type (e.g., line, bar, pie).visualMap
: Visual map settings for encoding data values to colors or sizes.dataZoom
: Data zoom settings.timeline
: Timeline settings.Detailed descriptions and available properties for each option are thoroughly documented in the official ECharts API reference.
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.
ECharts provides utility functions that are helpful for various tasks:
echarts.number.format()
: Formats numbers according to specified patterns.echarts.util.each()
: Iterates over arrays or objects.echarts.graphic.Group()
: Creates a graphic group for custom rendering.echarts.graphic.Text()
: Creates a text element.echarts.graphic.Rect()
: Creates a rectangle element. (These are examples from the graphic component)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.
Several common issues arise when working with ECharts:
Chart not rendering: This often stems from incorrect library inclusion, missing or incorrectly formatted data, or typos in configuration options. Double-check your HTML for the correct script inclusion, verify your data structure, and carefully review your option
object for errors. Using your browser’s developer console to check for JavaScript errors is essential.
Incorrect chart appearance: Unexpected visual results may be due to misconfigured options. Check the axis types, scales, data ranges, and series configurations. Consult the ECharts documentation for the correct options for your chart type.
Performance issues: Large datasets or complex chart configurations can lead to slow rendering. Consider optimizing your data (downsampling, lazy loading), simplifying chart elements, and using ECharts’ performance optimization features.
Unexpected behavior: Unforeseen behavior might indicate issues in event handling or interaction configurations. Carefully review your event handlers and ensure they correctly interact with the chart’s state.
Effective debugging techniques for ECharts include:
Browser developer tools: Use your browser’s developer console to check for JavaScript errors, inspect the chart’s DOM structure, and debug your code step-by-step. The console often provides clues about the source of errors.
Simplify your code: Break down complex charts into smaller, simpler components to isolate the source of problems. This makes it easier to identify the problem area.
Check the ECharts documentation: Carefully review the relevant sections of the ECharts documentation for your chart type and the options you’re using. The documentation provides detailed explanations of options and expected behavior.
Inspect the option
object: Log your option
object to the console before setting it to the chart. This helps verify that the configuration is correct and as intended.
Use a code editor with debugging tools: Modern code editors have debugging features that allow setting breakpoints, stepping through code, and inspecting variables. These tools significantly aid in identifying the root causes of problems.
ECharts error messages often provide valuable clues for resolving issues. Pay close attention to:
Specific error messages: The error messages themselves usually provide information about the nature of the problem (e.g., missing data, invalid configuration, etc.).
Line numbers and file names: These help locate the specific part of your code causing the error.
Stack traces: In more complex cases, the stack trace can help trace the execution path that led to the error, showing the sequence of function calls.
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.
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.
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.
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.
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.