### Link to Example Viewer with exampleViewPath
Source: https://echarts.apache.org/handbook/en/meta/edit-guide
Example showing how to use `exampleViewPath` to link to a view of an example.
```markdown
[line-simple](${exampleViewPath}scatter-exponential-regression&edit=1&reset=1)
```
--------------------------------
### Link to Example Editor with exampleEditorPath
Source: https://echarts.apache.org/handbook/en/meta/edit-guide
Example demonstrating the use of `exampleEditorPath` to create a link to an example in the editor.
```markdown
[line-simple](${exampleEditorPath}line-simple&edit=1&reset=1)
```
--------------------------------
### Format echarts.init with mainSitePath
Source: https://echarts.apache.org/handbook/en/meta/edit-guide
Example using the `mainSitePath` variable to link to the API documentation for echarts.init.
```markdown
[echarts.init](${mainSitePath}api.html#echarts.init)
```
--------------------------------
### Link to Language-Specific Page with lang Variable
Source: https://echarts.apache.org/handbook/en/meta/edit-guide
Example using the `lang` variable to create a link to a language-specific page, such as 'Get Started'.
```markdown
[Get Started](${lang}/get-started)
```
--------------------------------
### Format xAxis.type with optionPath
Source: https://echarts.apache.org/handbook/en/meta/edit-guide
Example demonstrating the use of the `optionPath` variable to reference the source code of xAxis.type.
```markdown
[xAxis.type](${optionPath}xAxis.type)
```
--------------------------------
### Format echarts.init with apiPath
Source: https://echarts.apache.org/handbook/en/meta/edit-guide
Example showing how to use the `apiPath` variable to link to the source code of echarts.init.
```markdown
[echarts.init](${apiPath}echarts.init)
```
--------------------------------
### Dual Y-Axis Example for Temperature and Precipitation
Source: https://echarts.apache.org/handbook/en/concepts/axis
A comprehensive example demonstrating a chart with two y-axes (one for precipitation on the right, one for temperature on the left) and a category x-axis for months. Includes tooltips, legends, and specific axis label formatting.
```javascript
option = {
tooltip: {
trigger: 'axis',
axisPointer: { type: 'cross' }
},
legend: {},
xAxis: [
{
type: 'category',
axisTick: {
alignWithLabel: true
},
axisLabel: {
rotate: 30
},
data: [
'January',
'February',
'March',
'April',
'May',
'June',
'July',
'August',
'September',
'October',
'November',
'December'
]
}
],
yAxis: [
{
type: 'value',
name: 'Precipitation',
min: 0,
max: 250,
position: 'right',
axisLabel: {
formatter: '{value} ml'
}
},
{
type: 'value',
name: 'Temperature',
min: 0,
max: 25,
position: 'left',
axisLabel: {
formatter: '{value} °C'
}
}
],
series: [
{
name: 'Precipitation',
type: 'bar',
yAxisIndex: 0,
data: [6, 32, 70, 86, 68.7, 100.7, 125.6, 112.2, 78.7, 48.8, 36.0, 19.3]
},
{
name: 'Temperature',
type: 'line',
smooth: true,
yAxisIndex: 1,
data: [
6.0,
10.2,
10.3,
11.5,
10.3,
13.2,
14.3,
16.4,
18.0,
16.5,
12.0,
5.2
]
}
]
};
```
--------------------------------
### Full ECharts Example with Dragging and Tooltips
Source: https://echarts.apache.org/handbook/en/how-to/interaction/drag
A complete ECharts initialization and configuration, including data points, custom tooltips, draggable graphic elements, and event handling for drag and resize.
```javascript
import echarts from 'echarts';
var symbolSize = 20;
var data = [
[15, 0],
[-50, 10],
[-56.5, 20],
[-46.5, 30],
[-22.1, 40]
];
var myChart = echarts.init(document.getElementById('main'));
myChart.setOption({
tooltip: {
triggerOn: 'none',
formatter: function(params) {
return (
'X: ' +
params.data[0].toFixed(2) +
' Y: ' +
params.data[1].toFixed(2)
);
}
},
xAxis: { min: -100, max: 80, type: 'value', axisLine: { onZero: false } },
yAxis: { min: -30, max: 60, type: 'value', axisLine: { onZero: false } },
series: [
{ id: 'a', type: 'line', smooth: true, symbolSize: symbolSize, data: data }
]
});
myChart.setOption({
graphic: echarts.util.map(data, function(item, dataIndex) {
return {
type: 'circle',
position: myChart.convertToPixel('grid', item),
shape: { r: symbolSize / 2 },
invisible: true,
draggable: true,
ondrag: echarts.util.curry(onPointDragging, dataIndex),
onmousemove: echarts.util.curry(showTooltip, dataIndex),
onmouseout: echarts.util.curry(hideTooltip, dataIndex),
z: 100
};
})
});
window.addEventListener('resize', function() {
myChart.setOption({
graphic: echarts.util.map(data, function(item, dataIndex) {
return { position: myChart.convertToPixel('grid', item) };
})
});
});
function showTooltip(dataIndex) {
myChart.dispatchAction({
type: 'showTip',
seriesIndex: 0,
dataIndex: dataIndex
});
}
function hideTooltip(dataIndex) {
myChart.dispatchAction({ type: 'hideTip' });
}
function onPointDragging(dataIndex, dx, dy) {
data[dataIndex] = myChart.convertFromPixel('grid', this.position);
myChart.setOption({
series: [
{
id: 'a',
data: data
}
]
});
}
```
--------------------------------
### Embedding an Interactive Example
Source: https://echarts.apache.org/handbook/en/meta/edit-guide
Use the custom `` component to embed interactive ECharts examples, specifying the source and dimensions.
```html
```
--------------------------------
### Install ECharts via npm
Source: https://echarts.apache.org/handbook/en/basics/download
Use this command to install ECharts as a dependency in your Node.js project. Refer to the 'Import ECharts' section for usage instructions.
```bash
npm install echarts
```
--------------------------------
### Listening to Legend Select Events
Source: https://echarts.apache.org/handbook/en/concepts/event
This example shows how to listen for the `legendselectchanged` event. It logs the selection state of the legend item that was interacted with and the state of all legends.
```javascript
// Show/hide the legend only trigger legendselectchanged event
myChart.on('legendselectchanged', function(params) {
// State if legend is selected.
var isSelected = params.selected[params.name];
// print in the console
console.log(
(isSelected ? 'Selected' : 'Not Selected') + 'legend' + params.name
);
// print for all legends.
console.log(params.selected);
});
```
--------------------------------
### Define Data Using Dataset (Array of Objects)
Source: https://echarts.apache.org/handbook/en/concepts/dataset
This example demonstrates using the `dataset` component with an 'array of objects' format, which can be more readable and easier to work with for structured data. Explicitly defining `dimensions` can clarify data mapping.
```javascript
option = {
legend: {},
tooltip: {},
dataset: {
// Define the dimension of array. In cartesian coordinate system,
// if the type of x-axis is category, map the first dimension to
// x-axis by default, the second dimension to y-axis.
// You can also specify 'series.encode' to complete the map
// without specify dimensions. Please see below.
dimensions: ['product', '2015', '2016', '2017'],
source: [
{ product: 'Matcha Latte', '2015': 43.3, '2016': 85.8, '2017': 93.7 },
{ product: 'Milk Tea', '2015': 83.1, '2016': 73.4, '2017': 55.1 },
{ product: 'Cheese Cocoa', '2015': 86.4, '2016': 65.2, '2017': 82.5 },
{ product: 'Walnut Brownie', '2015': 72.4, '2016': 53.9, '2017': 39.1 }
]
},
xAxis: { type: 'category' },
yAxis: {},
series: [{ type: 'bar' }, { type: 'bar' }, { type: 'bar' }]
};
```
--------------------------------
### Recommended ECharts Code Style
Source: https://echarts.apache.org/handbook/en/meta/edit-guide
This example shows a recommended way to write ECharts options, allowing for code formatting tools to process comments like '...'.
```javascript
option = {
series: [
{
type: 'bar'
// ...
}
]
};
```
--------------------------------
### Initialize and Render a Simple Bar Chart
Source: https://echarts.apache.org/handbook/en/get-started
Initialize an ECharts instance, configure chart options including title, tooltip, legend, axes, and series data, then render the chart. This example demonstrates a basic bar chart.
```javascript
ECharts
```
--------------------------------
### Configure Animation Delay for Staggered Animations
Source: https://echarts.apache.org/handbook/en/how-to/animation/transition
This example demonstrates how to use a callback function with `animationDelay` and `animationDelayUpdate` to create staggered animations for different data items. The `animationDelay` is set for the 'bar' series, and `animationDelayUpdate` is set for the 'bar2' series, with different delay calculations.
```javascript
var xAxisData = [];
var data1 = [];
var data2 = [];
for (var i = 0; i < 100; i++) {
xAxisData.push('A' + i);
data1.push((Math.sin(i / 5) * (i / 5 - 10) + i / 6) * 5);
data2.push((Math.cos(i / 5) * (i / 5 - 10) + i / 6) * 5);
}
option = {
legend: {
data: ['bar', 'bar2']
},
xAxis: {
data: xAxisData,
splitLine: {
show: false
}
},
yAxis: {},
series: [
{
name: 'bar',
type: 'bar',
data: data1,
emphasis: {
focus: 'series'
},
animationDelay: function(idx) {
return idx * 10;
}
},
{
name: 'bar2',
type: 'bar',
data: data2,
emphasis: {
focus: 'series'
},
animationDelay: function(idx) {
return idx * 10 + 100;
}
}
],
animationEasing: 'elasticOut',
animationDelayUpdate: function(idx) {
return idx * 5;
}
};
```
--------------------------------
### Full Example: Rich Text Effects in Scatter Plot
Source: https://echarts.apache.org/handbook/en/how-to/label/rich-text
A comprehensive example showcasing multiple rich text effects like icons, horizontal rules, title blocks, and simple tables within a scatter plot's labels. This demonstrates the integration of various rich text components.
```javascript
option = {
series: [
{
type: 'scatter',
data: [
{
value: [0, 0],
label: {
formatter: [
'{tc|Center Title}{titleBg|}',
' Content text xxxxxxxx {sunny|} xxxxxxxx {cloudy|} ',
'{hr|}',
' xxxxx {showers|} xxxxxxxx xxxxxxxxx '
].join('\n'),
rich: {
titleBg: {
align: 'right'
}
}
}
},
{
value: [0, 1],
label: {
formatter: [
'{titleBg|Left Title}',
' Content text xxxxxxxx {sunny|} xxxxxxxx {cloudy|} ',
'{hr|}',
' xxxxx {showers|} xxxxxxxx xxxxxxxxx '
].join('\n')
}
},
{
value: [0, 2],
label: {
formatter: [
'{titleBg|Right Title}',
' Content text xxxxxxxx {sunny|} xxxxxxxx {cloudy|} ',
'{hr|}',
' xxxxx {showers|} xxxxxxxx xxxxxxxxx '
].join('\n'),
rich: {
titleBg: {
align: 'right'
}
}
}
}
],
symbolSize: 1,
label: {
show: true,
backgroundColor: '#ddd',
borderColor: '#555',
borderWidth: 1,
borderRadius: 5,
color: '#000',
fontSize: 14,
rich: {
titleBg: {
backgroundColor: '#000',
height: 30,
borderRadius: [5, 5, 0, 0],
padding: [0, 10, 0, 10],
width: '100%',
color: '#eee'
},
tc: {
align: 'center',
color: '#eee'
},
hr: {
borderColor: '#777',
width: '100%',
borderWidth: 0.5,
height: 0
},
sunny: {
height: 30,
align: 'left',
backgroundColor: {
image:
'https://echarts.apache.org/examples/data/asset/img/weather/sunny_128.png'
}
},
cloudy: {
height: 30,
align: 'left',
backgroundColor: {
image:
'https://echarts.apache.org/examples/data/asset/img/weather/cloudy_128.png'
}
},
showers: {
height: 30,
align: 'left',
backgroundColor: {
image:
'https://echarts.apache.org/examples/data/asset/img/weather/showers_128.png'
}
}
}
}
}
],
xAxis: {
show: false,
min: -1,
max: 1
},
yAxis: {
show: false,
min: 0,
max: 2,
inverse: true
}
};
```
--------------------------------
### Stacked Line Chart with Area Filling
Source: https://echarts.apache.org/handbook/en/how-to/chart-types/line/stacked-line
This example shows how to enhance a stacked line chart by enabling area filling using 'areaStyle'. This improves visual distinction between stacked series.
```javascript
option = {
xAxis: {
data: ['A', 'B', 'C', 'D', 'E']
},
yAxis: {},
series: [
{
data: [10, 22, 28, 43, 49],
type: 'line',
stack: 'x',
areaStyle: {}
},
{
data: [5, 4, 3, 5, 10],
type: 'line',
stack: 'x',
areaStyle: {}
}
]
};
```
--------------------------------
### Stacked Bar Chart Example
Source: https://echarts.apache.org/handbook/en/how-to/chart-types/bar/stacked-bar
Use the 'stack' property to group series that should be stacked together in the same category. The value of 'stack' can be any string, but descriptive names improve readability.
```javascript
option = {
xAxis: {
data: ['A', 'B', 'C', 'D', 'E']
},
yAxis: {},
series: [
{
data: [10, 22, 28, 43, 49],
type: 'bar',
stack: 'x'
},
{
data: [5, 4, 3, 5, 10],
type: 'bar',
stack: 'x'
}
]
};
```
--------------------------------
### Event Handling for Graph Nodes and Edges
Source: https://echarts.apache.org/handbook/en/concepts/event
This example demonstrates how to attach click event handlers for specific data types within a graph series, distinguishing between clicks on nodes and edges using the 'dataType' property in the query object.
```javascript
chart.setOption({
series: [
{
type: 'graph',
nodes: [
{ name: 'a', value: 10 },
{ name: 'b', value: 20 }
],
edges: [{ source: 0, target: 1 }]
}
]
});
chart.on('click', { dataType: 'node' }, function() {
});
chart.on('click', { dataType: 'edge' }, function() {
});
```
--------------------------------
### Event Handling with Object Query for Series Index and Data Name
Source: https://echarts.apache.org/handbook/en/concepts/event
This example shows how to attach an event handler using an object query that specifies both the 'seriesIndex' and the 'name' of the data item. The handler will only be triggered for the data item 'xx' within the series at index 1.
```javascript
chart.setOption({
series: [
{
},
{
data: [
{ name: 'xx', value: 121 },
{ name: 'yy', value: 33 }
]
}
]
});
chart.on('mouseover', { seriesIndex: 1, name: 'xx' }, function() {
});
```
--------------------------------
### Filter Data by Date Range
Source: https://echarts.apache.org/handbook/en/concepts/data-transform
This example demonstrates filtering dataset entries to include only those within a specific date range using the 'time' parser for date comparison.
```javascript
option = {
dataset: [
{
source: [
['Product', 'Sales', 'Price', 'Date'],
['Milk Tee', 311, 21, '2012-05-12'],
['Cake', 135, 28, '2012-05-22'],
['Latte', 262, 36, '2012-06-02'],
['Milk Tee', 359, 21, '2012-06-22'],
['Cake', 121, 28, '2012-07-02'],
['Latte', 271, 36, '2012-06-22']
// ...
]
},
{
transform: {
type: 'filter',
config: {
dimension: 'Date',
'>=': '2012-05',
'<': '2012-06',
parser: 'time'
}
}
}
]
};
```
--------------------------------
### Define Series Dimensions to Override Dataset
Source: https://echarts.apache.org/handbook/en/concepts/dataset
This example demonstrates how to define dimensions specifically for a series, which can override or supplement the dataset's dimension configuration. Use `null` to skip a dimension from the dataset.
```javascript
var option2 = {
dataset: {
source: []
},
series: {
type: 'line',
// series.dimensions will cover the config in dataset.dimension
dimensions: [
null, // use null if you do not want dimension name.
'amount',
{ name: 'product', type: 'ordinal' }
]
}
// ...
};
```
--------------------------------
### Conditional Event Handling Based on Component Type
Source: https://echarts.apache.org/handbook/en/concepts/event
This example shows how to use the 'click' event to conditionally execute code based on the 'componentType' and 'seriesType' properties of the event parameters. It differentiates between clicks on mark points, graph nodes, and graph edges.
```javascript
myChart.on('click', function(params) {
if (params.componentType === 'markPoint') {
if (params.seriesIndex === 5) {
}
} else if (params.componentType === 'series') {
if (params.seriesType === 'graph') {
if (params.dataType === 'edge') {
} else {
}
}
}
});
```
--------------------------------
### Create a Basic Line Chart
Source: https://echarts.apache.org/handbook/en/how-to/interaction/drag
Initializes a line chart with sample data. This sets up the chart structure before enabling dragging.
```javascript
var symbolSize = 20;
var data = [
[15, 0],
[-50, 10],
[-56.5, 20],
[-46.5, 30],
[-22.1, 40]
];
myChart.setOption({
xAxis: {
min: -100,
max: 80,
type: 'value',
axisLine: { onZero: false }
},
yAxis: {
min: -30,
max: 60,
type: 'value',
axisLine: { onZero: false }
},
series: [
{
id: 'a',
type: 'line',
smooth: true,
// Set a big symbolSize for dragging convenience.
symbolSize: symbolSize,
data: data
}
]
});
```
--------------------------------
### Example Aria-label Description
Source: https://echarts.apache.org/handbook/en/best-practices/aria
This is an example of the aria-label attribute generated by ECharts for screen readers, describing the chart's content and data.
```text
This is a chart about "Referrer of a User" with type Pie chart named Referrer. The data is as follows: the data of Direct Visit is 335,the data of Mail Marketing is 310,the data of Union Ad is 234,the data of Video Ad is 135,the data of Search Engine is 1548.
```
--------------------------------
### Initialize Chart with v5 Theme
Source: https://echarts.apache.org/handbook/en/basics/release-note/v6-upgrade-guide
To maintain the default theme from v5, import the 'v5' theme and specify it during chart initialization.
```javascript
import 'echarts/theme/v5';
const chart = echarts.init(document.getElementById('container'), 'v5');
```
--------------------------------
### ECharts Data Transform Example
Source: https://echarts.apache.org/handbook/en/concepts/data-transform
This example demonstrates how to configure a dataset with a 'filter' transform to extract data for a specific year. The transformed dataset is then used by multiple series.
```javascript
var option = {
dataset: [
{
// This dataset is on `datasetIndex: 0`.
source: [
['Product', 'Sales', 'Price', 'Year'],
['Cake', 123, 32, 2011],
['Cereal', 231, 14, 2011],
['Tofu', 235, 5, 2011],
['Dumpling', 341, 25, 2011],
['Biscuit', 122, 29, 2011],
['Cake', 143, 30, 2012],
['Cereal', 201, 19, 2012],
['Tofu', 255, 7, 2012],
['Dumpling', 241, 27, 2012],
['Biscuit', 102, 34, 2012],
['Cake', 153, 28, 2013],
['Cereal', 181, 21, 2013],
['Tofu', 395, 4, 2013],
['Dumpling', 281, 31, 2013],
['Biscuit', 92, 39, 2013],
['Cake', 223, 29, 2014],
['Cereal', 211, 17, 2014],
['Tofu', 345, 3, 2014],
['Dumpling', 211, 35, 2014],
['Biscuit', 72, 24, 2014]
]
// id: 'a'
},
{
// This dataset is on `datasetIndex: 1`.
// A `transform` is configured to indicate that the
// final data of this dataset is transformed via this
// transform function.
transform: {
type: 'filter',
config: { dimension: 'Year', value: 2011 }
}
// There can be optional properties `fromDatasetIndex` or `fromDatasetId`
// to indicate that where is the input data of the transform from.
// For example, `fromDatasetIndex: 0` specify the input data is from
// the dataset on `datasetIndex: 0`, or `fromDatasetId: 'a'` specify the
// input data is from the dataset having `id: 'a'`.
// [DEFAULT_RULE]
// If both `fromDatasetIndex` and `fromDatasetId` are omitted,
// `fromDatasetIndex: 0` are used by default.
},
{
// This dataset is on `datasetIndex: 2`.
// Similarly, if neither `fromDatasetIndex` nor `fromDatasetId` is
// specified, `fromDatasetIndex: 0` is used by default
transform: {
// The "filter" transform filters and gets data items only match
// the given condition in property `config`.
type: 'filter',
// Transforms has a property `config`. In this "filter" transform,
// the `config` specify the condition that each result data item
// should be satisfied. In this case, this transform get all of
// the data items that the value on dimension "Year" equals to 2012.
config: { dimension: 'Year', value: 2012 }
}
},
{
// This dataset is on `datasetIndex: 3`
transform: {
type: 'filter',
config: { dimension: 'Year', value: 2013 }
}
}
],
series: [
{
type: 'pie',
radius: 50,
center: ['25%', '50%'],
// In this case, each "pie" series reference to a dataset that has
// the result of its "filter" transform.
datasetIndex: 1
},
{
type: 'pie',
radius: 50,
center: ['50%', '50%'],
datasetIndex: 2
},
{
type: 'pie',
radius: 50,
center: ['75%', '50%'],
datasetIndex: 3
}
]
};
```
--------------------------------
### Dataset Source Formats (Key-Value)
Source: https://echarts.apache.org/handbook/en/concepts/dataset
Demonstrates two common key-value formats for dataset sources: column-by-column and row-by-row. The column-by-column format is generally more common.
```javascript
dataset: [
{
// column by column key-value array is a normal format
source: [
{ product: 'Matcha Latte', count: 823, score: 95.8 },
{ product: 'Milk Tea', count: 235, score: 81.4 },
{ product: 'Cheese Cocoa', count: 1042, score: 91.2 },
{ product: 'Walnut Brownie', count: 988, score: 76.9 }
]
},
{
// row by row key-value
source: {
product: ['Matcha Latte', 'Milk Tea', 'Cheese Cocoa', 'Walnut Brownie'],
count: [823, 235, 1042, 988],
score: [95.8, 81.4, 91.2, 76.9]
}
}
];
```
--------------------------------
### Importing Lightweight Client Runtime
Source: https://echarts.apache.org/handbook/en/how-to/cross-platform/server
Import the client-side lightweight runtime for server-side rendered SVG charts. Choose either the CDN or NPM method for inclusion.
```html
```
--------------------------------
### Upgrade ECharts using npm
Source: https://echarts.apache.org/handbook/en/basics/release-note/v6-upgrade-guide
Use npm to install the latest version of ECharts (v6).
```bash
npm install echarts@6
```
--------------------------------
### Highlighting Lines and Adding Filenames in Code Snippets
Source: https://echarts.apache.org/handbook/en/meta/edit-guide
Demonstrates how to highlight specific lines and add filenames to code snippets for better clarity and organization.
```javascript
option = {
series: [
{
type: 'bar',
data: [23, 24, 18, 25, 27, 28, 25]
}
]
};
```
--------------------------------
### Registering an External Transform
Source: https://echarts.apache.org/handbook/en/concepts/data-transform
Register an external transform function with ECharts. This is a one-time setup required before using the transform.
```javascript
// Register the external transform at first.
echarts.registerTransform(ecStatTransform(ecStat).regression);
```
--------------------------------
### Unsupported SVG Text Element Example
Source: https://echarts.apache.org/handbook/en/how-to/component-types/geo/svg-base-map
Illustrates unsupported usage of the `` element with addressable characters in SVG for ECharts. The `x` attribute with multiple values is not supported.
```html
abcabc
```
--------------------------------
### Implementing Simple Tables with Text Alignment
Source: https://echarts.apache.org/handbook/en/how-to/label/rich-text
Create simple table-like structures by assigning consistent widths to text fragments across different lines within the `rich` text formatter. This allows for column alignment similar to traditional tables.
```javascript
// Example demonstrating simple table structure (refer to full example for complete implementation)
// Assigning same width to text fragments in the same column across different lines.
// formatter: [
// '{col1|Text A}{col2|Text B}',
// '{col1|More A}{col2|More B}'
// ].join('\n'),
// rich: {
// col1: { width: 100, align: 'left' },
// col2: { width: 100, align: 'left' }
// }
```
--------------------------------
### Implementing Icons with Image Background
Source: https://echarts.apache.org/handbook/en/how-to/label/rich-text
Use the `backgroundColor` property with an `image` source within the `rich` configuration to display icons. Specify `height` to control the icon size, allowing width to be auto-calculated while maintaining aspect ratio.
```javascript
rich: {
Sunny: {
backgroundColor: {
image: './data/asset/img/weather/sunny_128.png'
},
height: 30
}
}
```
--------------------------------
### Delayed Data URL Retrieval with setTimeout
Source: https://echarts.apache.org/handbook/en/how-to/animation/transition
When animations are enabled, use `setTimeout` to delay the `getDataURL` call until after the specified `animationDuration` has passed, ensuring you get the final rendered state.
```javascript
chart.setOption({
animationDuration: 1000
//...
});
setTimeout(() => {
const dataUrl = chart.getDataURL();
}, 1000);
```
--------------------------------
### Event Handling with String Query
Source: https://echarts.apache.org/handbook/en/concepts/event
Demonstrates using a string as a query to attach an event handler to a specific component type or sub-type, such as 'series' or 'series.line'.
```javascript
chart.on('click', 'series', function () {...});
chart.on('click', 'series.line', function () {...});
chart.on('click', 'dataZoom', function () {...});
chart.on('click', 'xAxis.category', function () {...});
```
--------------------------------
### Use Auto-Registering JS Theme
Source: https://echarts.apache.org/handbook/en/concepts/style
Initialize a chart with a theme provided as a JavaScript file. These themes typically auto-register themselves upon import.
```javascript
// Import the `vintage.js` file in HTML, then:
var chart = echarts.init(dom, 'vintage');
// ...
```
--------------------------------
### Server-Side Rendering with node-canvas
Source: https://echarts.apache.org/handbook/en/how-to/cross-platform/server
Use this snippet to render ECharts charts to a PNG image on the server using node-canvas. Ensure node-canvas is installed. In versions prior to 5.3.0, `echarts.setCanvasCreator` is required.
```javascript
var echarts = require('echarts');
const { createCanvas } = require('canvas');
// In versions earlier than 5.3.0, you had to register the canvas factory with setCanvasCreator.
// Not necessary since 5.3.0
echarts.setCanvasCreator(() => {
return createCanvas();
});
const canvas = createCanvas(800, 600);
// ECharts can use the Canvas instance created by node-canvas as a container directly
let chart = echarts.init(canvas);
// setOption as normal
chart.setOption({
//...
});
const buffer = canvas.toBuffer('image/png');
// If chart is no longer useful, consider disposing it to release memory.
chart.dispose();
chart = null;
// Output the PNG image via Response
res.writeHead(200, {
'Content-Type': 'image/png'
});
res.write(buffer);
res.end();
```
--------------------------------
### Step Line Chart with Different Step Types
Source: https://echarts.apache.org/handbook/en/how-to/chart-types/line/step-line
Demonstrates the three different step types ('start', 'middle', 'end') for line series in ECharts. Use this to visualize data with distinct, sudden changes.
```javascript
option = {
legend: {},
xAxis: {
type: 'category',
data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
},
yAxis: {
type: 'value'
},
series: [
{
name: 'Step Start',
type: 'line',
step: 'start',
data: [120, 132, 101, 134, 90, 230, 210]
},
{
name: 'Step Middle',
type: 'line',
step: 'middle',
data: [220, 282, 201, 234, 290, 430, 410]
},
{
name: 'Step End',
type: 'line',
step: 'end',
data: [450, 432, 401, 454, 590, 530, 510]
}
]
};
```
--------------------------------
### Referencing Multiple Datasets
Source: https://echarts.apache.org/handbook/en/concepts/dataset
Shows how to define multiple datasets and reference a specific dataset for a series using `datasetIndex`. This is useful when working with complex data structures or multiple data sources.
```javascript
var option = {
dataset: [
{
// 1st Dataset
source: []
},
{
// 2nd Dataset
source: []
},
{
// 3rd Dataset
source: []
}
],
series: [
{
// Use 2nd dataset
datasetIndex: 1
},
{
// Use 1st dataset
datasetIndex: 0
}
]
};
```
--------------------------------
### Handle Point Dragging and Update Chart
Source: https://echarts.apache.org/handbook/en/how-to/interaction/drag
Defines the `onPointDragging` function, which updates the chart's data array and re-renders the series when a point is dragged. It uses `convertFromPixel` to get the data coordinates from the circle's position.
```javascript
// This function will be called repeatly while dragging.
// The mission of this function is to update `series.data` based on
// the new points updated by dragging, and to re-render the line
// series based on the new data, by which the graphic elements of the
// line series can be synchronized with dragging.
function onPointDragging(dataIndex) {
// Here the `data` is declared in the code block in the beginning
// of this article. The `this` refers to the dragged circle.
// `this.position` is the current position of the circle.
data[dataIndex] = myChart.convertFromPixel('grid', this.position);
// Re-render the chart based on the updated `data`.
myChart.setOption({
series: [
{
id: 'a',
data: data
}
]
});
}
```
--------------------------------
### Marking Named Elements in SVG for Interaction
Source: https://echarts.apache.org/handbook/en/how-to/component-types/geo/svg-base-map
Add 'name' attributes to SVG elements (e.g., path, rect, circle) to enable interaction features like selection and emphasis in ECharts. This example shows a path with a name attribute.
```xml
```
--------------------------------
### Animating Chart Elements with dispatchAction
Source: https://echarts.apache.org/handbook/en/concepts/event
This snippet demonstrates how to use `dispatchAction` to programmatically highlight chart elements sequentially. It sets up an interval to cycle through highlighting, downplaying, and showing tooltips for pie chart sectors.
```javascript
option = {
tooltip: {
trigger: 'item',
formatter: '{a} {b} : {c} ({d}%)'
},
legend: {
orient: 'vertical',
left: 'left',
data: [
'Direct Access',
'Email Marketing',
'Affiliate Ads',
'Video Ads',
'Search Engines'
]
},
series: [
{
name: 'Access Source',
type: 'pie',
radius: '55%',
center: ['50%', '60%'],
data: [
{ value: 335, name: 'Direct Access' },
{ value: 310, name: 'Email Marketing' },
{ value: 234, name: 'Affiliate Ads' },
{ value: 135, name: 'Video Ads' },
{ value: 1548, name: 'Search Engines' }
],
emphasis: {
itemStyle: {
shadowBlur: 10,
shadowOffsetX: 0,
shadowColor: 'rgba(0, 0, 0, 0.5)'
}
}
}
]
};
let currentIndex = -1;
setInterval(function() {
var dataLen = option.series[0].data.length;
myChart.dispatchAction({
type: 'downplay',
seriesIndex: 0,
dataIndex: currentIndex
});
currentIndex = (currentIndex + 1) % dataLen;
myChart.dispatchAction({
type: 'highlight',
seriesIndex: 0,
dataIndex: currentIndex
});
myChart.dispatchAction({
type: 'showTip',
seriesIndex: 0,
dataIndex: currentIndex
});
}, 1000);
```
--------------------------------
### Using the md-alert Component (Info)
Source: https://echarts.apache.org/handbook/en/meta/edit-guide
Display informational alerts using the `` component with the 'info' type.
```html
This is an info alert.
```
--------------------------------
### Configure Dataset Row or Column Mapping to Series
Source: https://echarts.apache.org/handbook/en/concepts/dataset
This example demonstrates how to configure ECharts to map rows or columns from a dataset to chart series. It shows the use of `seriesLayoutBy` to switch between row-based and column-based mapping for different series within the same chart.
```javascript
option = {
legend: {},
tooltip: {},
dataset: {
source: [
['product', '2012', '2013', '2014', '2015'],
['Matcha Latte', 41.1, 30.4, 65.1, 53.3],
['Milk Tea', 86.5, 92.1, 85.7, 83.1],
['Cheese Cocoa', 24.1, 67.2, 79.5, 86.4]
]
},
xAxis: [
{ type: 'category', gridIndex: 0 },
{ type: 'category', gridIndex: 1 }
],
yAxis: [{ gridIndex: 0 }, { gridIndex: 1 }],
grid: [{ bottom: '55%' }, { top: '55%' }],
series: [
// These series will show in the first coordinate, each series map a row in dataset.
{ type: 'bar', seriesLayoutBy: 'row', xAxisIndex: 0, yAxisIndex: 0 },
{ type: 'bar', seriesLayoutBy: 'row', xAxisIndex: 0, yAxisIndex: 0 },
{ type: 'bar', seriesLayoutBy: 'row', xAxisIndex: 0, yAxisIndex: 0 },
// These series will show in the second coordinate, each series map a column in dataset.
{ type: 'bar', seriesLayoutBy: 'column', xAxisIndex: 1, yAxisIndex: 1 },
{ type: 'bar', seriesLayoutBy: 'column', xAxisIndex: 1, yAxisIndex: 1 },
{ type: 'bar', seriesLayoutBy: 'column', xAxisIndex: 1, yAxisIndex: 1 },
{ type: 'bar', seriesLayoutBy: 'column', xAxisIndex: 1, yAxisIndex: 1 }
]
};
```
--------------------------------
### Define Data Using Dataset (2D Array)
Source: https://echarts.apache.org/handbook/en/concepts/dataset
Using the `dataset` component allows data to be defined separately from series configurations. This promotes data reusability and simplifies management, especially for common data formats like 2D arrays.
```javascript
option = {
legend: {},
tooltip: {},
dataset: {
// Provide a set of data.
source: [
['product', '2015', '2016', '2017'],
['Matcha Latte', 43.3, 85.8, 93.7],
['Milk Tea', 83.1, 73.4, 55.1],
['Cheese Cocoa', 86.4, 65.2, 82.5],
['Walnut Brownie', 72.4, 53.9, 39.1]
]
},
// Declare an x-axis (category axis).
// The category map the first column in the dataset by default.
xAxis: { type: 'category' },
// Declare a y-axis (value axis).
yAxis: {},
// Declare several 'bar' series,
// every series will auto-map to each column by default.
series: [{ type: 'bar' }, { type: 'bar' }, { type: 'bar' }]
};
```
--------------------------------
### Asynchronous Data Loading with setOption
Source: https://echarts.apache.org/handbook/en/how-to/data/dynamic-data
Load data asynchronously using jQuery's $.get and update the chart with setOption after initialization. Ensure the data structure matches expected categories and values.
```javascript
var myChart = echarts.init(document.getElementById('main'));
$.get('data.json').done(function(data) {
// Structure of data:
// {
// categories: ["Shirt","Wool sweater","Chiffon shirt","Pants","High-heeled shoes","socks"],
// values: [5, 20, 36, 10, 10, 20]
// }
myChart.setOption({
title: {
text: 'Asynchronous Loading Example'
},
tooltip: {},
legend: {},
xAxis: {
data: data.categories
},
yAxis: {},
series: [
{
name: 'Sales',
type: 'bar',
data: data.values
}
]
});
});
```
--------------------------------
### Convert Pixel Coordinates to SVG Local Coordinates
Source: https://echarts.apache.org/handbook/en/how-to/component-types/geo/svg-base-map
Use this method to get SVG local coordinates when a user clicks on the map. This is useful for determining the exact SVG coordinates for placing data points. Attach a click listener to the ECharts ZRender instance.
```javascript
myChart.setOption({
geo: {
map: 'some_svg'
}
});
myChart.getZr().on('click', function (params) {
var pixelPoint = [params.offsetX, params.offsetY];
var dataPoint = myChart.convertFromPixel({ geoIndex: 0 }, pixelPoint);
// When click, the data in SVG local coords will be printed,
// which can be used in `series.data`.
console.log(dataPoint);
});
```
--------------------------------
### Enable Zoom and Pan for Map Series
Source: https://echarts.apache.org/handbook/en/how-to/component-types/geo/svg-base-map
Configure a 'map' series to enable interactive zoom and pan functionality. This enhances user experience by allowing map exploration.
```javascript
option = {
series: {
type: 'map',
// Enable zoom and pan.
roam: true,
...
}
};
```
--------------------------------
### Import All ECharts Functionality
Source: https://echarts.apache.org/handbook/en/basics/import
Import the entire ECharts library to make all features available. This is the simplest method but results in a larger bundle size.
```javascript
import * as echarts from 'echarts';
// Create the echarts instance
var myChart = echarts.init(document.getElementById('main'));
// Draw the chart
myChart.setOption({
title: {
text: 'ECharts Getting Started Example'
},
tooltip: {},
xAxis: {
data: ['shirt', 'cardigan', 'chiffon', 'pants', 'heels', 'socks']
},
yAxis: {},
series: [
{
name: 'sales',
type: 'bar',
data: [5, 20, 36, 10, 10, 20]
}
]
});
```
--------------------------------
### Setting Image Height and Width with HTML
Source: https://echarts.apache.org/handbook/en/meta/edit-guide
Use HTML `` tags to embed images and control their dimensions using inline styles for temporary adjustments.
```html
```