### Install ECharts Examples Source: https://github.com/apache/echarts-examples/blob/gh-pages/README.md Use this command to install the necessary dependencies for ECharts examples. ```shell npm i --force ``` -------------------------------- ### Start Development Server Source: https://github.com/apache/echarts-examples/blob/gh-pages/README.md Run this command to start the development server and view the ECharts examples website locally. ```shell npm run dev ``` -------------------------------- ### Build ECharts Example Thumbnails Source: https://context7.com/apache/echarts-examples/llms.txt Builds example thumbnails by starting a local server, taking screenshots with Puppeteer, and converting to WebP. Supports flags for GL examples, themes, patterns, and skipping thumbnails. ```shell # Build thumbnails for all standard examples (default + dark themes) npm run build:example > result.log 2>&1 # Skip thumbnails, only regenerate chart-list-data.js npm run build:examplelist # Build only one example node tool/build-example.js --pattern bar-race # Build GL examples only node tool/build-example.js --gl # Build with a specific theme node tool/build-example.js -t dark ``` -------------------------------- ### Example File Metadata Block Source: https://context7.com/apache/echarts-examples/llms.txt Every example source file must begin with a JSDoc-style metadata comment block. The fields 'title' and 'category' are required for an example to appear in the exploration page. ```ts /* title: Bar Race titleCN: 动态排序柱状图 category: bar difficulty: 5 since: 5.0.0 videoStart: 1000 videoEnd: 6000 */ // Example code follows... option = { /* ... */ }; ``` -------------------------------- ### Example Metadata Structure Source: https://github.com/apache/echarts-examples/blob/gh-pages/README.md The first JavaScript comment block in an example file serves as metadata. Ensure 'title' and 'category' are provided for inclusion in the example exploration page. ```js /* title: Area Pieces titleCN: 折线图区域高亮 category: 'line, visualMap' since: 6.0.0 */ ``` -------------------------------- ### Generate Thumbnail for a Specific Doc Example Source: https://github.com/apache/echarts-examples/blob/gh-pages/README.md Build the thumbnail for a specific example that is part of the documentation, identified by its path and base name. ```javascript node tool/build-example.js --pattern doc-example/my-example-basename ``` -------------------------------- ### Update Example List for Testing Source: https://github.com/apache/echarts-examples/blob/gh-pages/README.md Before running end-to-end tests, update the list of examples. This ensures all examples are accounted for in the testing process. ```shell npm run build:examplelist ``` -------------------------------- ### Install Puppeteer Source: https://github.com/apache/echarts-examples/blob/gh-pages/README.md Install Puppeteer as a development dependency if it's not already installed. Puppeteer is used for end-to-end testing. ```shell npm i puppeteer -D ``` -------------------------------- ### Generate Thumbnail for a Specific Example Source: https://github.com/apache/echarts-examples/blob/gh-pages/README.md Build the thumbnail for a single, specific example by providing its base name. This is useful for quick updates or testing. ```javascript node tool/build-example.js --pattern my-example-basename ``` -------------------------------- ### Enable Controller Panel for Examples Source: https://github.com/apache/echarts-examples/blob/gh-pages/README.md Configure `app.config` and `app.configParameters` to add interactive widgets (selection, range, button) to an ECharts example, with callbacks for changes. ```js app.config = { aNameForTheSelectionWidget: 'This is the initial value' aNameForTheRangeWidget: 45, aNameForTheButtonWidget: function () { // Do something on button click. }, onChange: function () { // Do something on SelectionWidget or RangeWidget changed. // Read the current value. console.log(app.config.aNameForTheRangeWidget) console.log(app.config.aNameForTheSelectionWidget) } }; app.configParameters = { // The keys below must exist in `app.config`. aNameForTheSelectionWidget: { options: [ 'This is the initial value', 'This is another value', 'This is the third value' 333, // value other than string is supported. false, // value other than string is supported. ] // // options can also be: // options: { /// // `text`: to display. // // `value`: write to `app.config` when option is switched. // text1: value1, // text2: value2, // text3: 333, // value other than string is supported. // text3: false, // value other than string is supported. // } }, aNameForTheRangeWidget: { min: -90, max: 90 } }; ``` -------------------------------- ### Generate Example Thumbnails Source: https://github.com/apache/echarts-examples/blob/gh-pages/README.md Generate thumbnails for all examples. This process can be time-consuming and also calls `build:examplelist` internally. Ensure your Puppeteer version is correct and no local version exists in `echarts-examples/tool`. ```shell npm run build:example > result.log 2>&1 ``` -------------------------------- ### Compile ECharts TypeScript Examples Source: https://context7.com/apache/echarts-examples/llms.txt Uses `npm run compile:example` to transpile TypeScript examples to JavaScript. Can compile all examples or a single file, outputting to `public/examples/js/`. ```shell # Compile all examples npm run compile:example # Compile a single file npm run compile:example -- area-basic.ts # Output: public/examples/js/area-basic.js ``` -------------------------------- ### Compile ECharts Examples Source: https://github.com/apache/echarts-examples/blob/gh-pages/README.md Commands to compile all ECharts examples or a single example. Ensure TypeScript interfaces are up-to-date if compilation errors occur. ```shell # Compile all examples npm run compile:example # Compile a single example npm run compile:example -- area-basic.ts ``` -------------------------------- ### Metadata Properties for Exploration Page Source: https://github.com/apache/echarts-examples/blob/gh-pages/README.md Properties like 'title', 'category', and absence of 'noExplore: true' are required for an example to be included in the exploration page. Examples should be directly under `public/examples/ts/`. ```js /* title: Bar Race titleCN: 动态排序柱状图 category: bar difficulty: 5 videoStart: 1000 videoEnd: 6000 */ ``` -------------------------------- ### Load Example Script and Initialize Chart Source: https://github.com/apache/echarts-examples/blob/gh-pages/tool/screenshot.html Dynamically loads an ECharts example script based on the 'c' URL parameter. It also handles chart initialization, animation recording, and setting the option. ```javascript if (params.c) { if (!window.ROOT_PATH) { // When visiting `screenshot.html` In browser. console.error('No ROOT_PATH specified. Use default ROOT_PATH "."'); window.ROOT_PATH = '.'; } const scriptTag = document.createElement('script'); scriptTag.async = false; scriptTag.src = `../public/examples/js${'gl' in params ? '/gl' : ''}/${ params.c }.js`; document.body.appendChild(scriptTag); let videoRecorder; scriptTag.onload = function () { if (isAnimated) { videoRecorder = new VideoRecorder(myChart); setTimeout(() => { videoRecorder.start(); }, +params.start); setTimeout(() => { videoRecorder.stop(); }, +params.end); } if (typeof option !== 'undefined' && option) { myChart.setOption(option); } }; } ``` -------------------------------- ### Generate Thumbnail for a Specific GL Example Source: https://github.com/apache/echarts-examples/blob/gh-pages/README.md Build the thumbnail for a single, specific ECharts GL example by providing its base name and the --gl flag. ```javascript node tool/build-example.js --pattern my-gl-example-basename --gl ``` -------------------------------- ### Download Example as Standalone HTML (JavaScript) Source: https://context7.com/apache/echarts-examples/llms.txt Assembles a self-contained HTML page embedding ECharts source code, build, and optional themes. The output filename is derived from the URL parameter 'c'. ```javascript import { download } from './downloadExample'; // Called when user clicks the download button in the editor download('title: Bar Race category: bar'); // Produces a file named after URL param `c` (e.g. "bar-race.html") containing: // // ``` -------------------------------- ### Generate Thumbnails Excluding ECharts GL Source: https://github.com/apache/echarts-examples/blob/gh-pages/README.md Build example thumbnails, but skip generating them for ECharts GL components. This can be useful if ECharts GL thumbnails are not needed or are causing issues. ```shell npm run build:example:nogl ``` -------------------------------- ### Run ECharts End-to-End Tests Source: https://context7.com/apache/echarts-examples/llms.txt Executes end-to-end tests by bundling examples with webpack or esbuild, running them in a headless browser, and validating screenshots. Supports remote/local dependencies and skipping stages. ```shell # Run e2e tests with remote repos + webpack npm run test:e2e > result.log 2>&1 # Run e2e tests with remote repos + esbuild (faster) npm run test:e2e:esbuild > result.log 2>&1 # Use local checkouts of echarts/zrender (must have `npm run release` already built) npm run test:e2e:local > result.log 2>&1 # Skip the bundle stage, run only matched tests node e2e/main.js --skip bundle --tests bar3D* # Skip npm install stage node e2e/main.js --skip npm ``` -------------------------------- ### Import Third-Party Libraries and Data Source: https://github.com/apache/echarts-examples/blob/gh-pages/README.md Use jQuery's `when` and `getScript` to load external JavaScript files or `get` to fetch JSON data for ECharts maps. ```js $.when( $.getScript(ROOT_PATH + '/data/asset/js/xxxx.js'), $.getScript( 'https://cdn.jsdelivr.net/npm/d3-contour@2.0.0/dist/d3-contour.js' ) ).done(function () { // ... // Set echarts option to the global variable `option`. option = {/*...*/}; // The global variable `myChart` can be used there. myChart.setOption(option); }); $.get(ROOT_PATH + '/data/asset/geo/iceland.geo.json', function (geoJSON) { echarts.registerMap('iceland', geoJSON); // ... // Set echarts option to the global variable `option`. option = {/*...*/}; // The global variable `myChart` can be used there. myChart.setOption(option); }); ``` -------------------------------- ### Local ECharts Dependency Source: https://github.com/apache/echarts-examples/blob/gh-pages/README.md If TypeScript errors occur due to local modifications of ECharts interfaces, install your local ECharts to pass compilation. ```shell cd your/echarts-examples npm i --force your/local/echarts ``` -------------------------------- ### Get Chart Dimensions Source: https://github.com/apache/echarts-examples/blob/gh-pages/README.md Retrieve the current width and height of the ECharts chart rendering area using `getWidth()` and `getHeight()` methods. ```js var width = myChart.getWidth(); var height = myChart.getHeight(); ``` -------------------------------- ### Initialize Vue App and Fetch Report Data Source: https://github.com/apache/echarts-examples/blob/gh-pages/e2e/report.html Initializes a Vue application and fetches JSON data for test results. It then processes this data to populate type checking and screenshot comparison results, sorting them by error counts and diff ratios respectively. ```javascript const app = new Vue({ el: '#app', data() { return { typeCheckingResult: [], screenshotsCompareResult: [], SCREENSHOT_ROOT: './tmp/screenshots/', tab: 'screenshots', splitterModel: 10 }; } }); fetch('./tmp/result.json') .then((response) => response.json()) .then((json) => { const result = []; function getCompilerErrorsCount({ full, minimal, minimalLegacy }) { return full.length + minimal.length + minimalLegacy.length; } function getScreenshotDiffRatio({ minimal, minimalLegacy }) { return minimal.ratio + minimalLegacy.ratio; } Object.keys(json).forEach((key) => { result.push({ ...json[key], compileErrorsCount: getCompilerErrorsCount( json[key].compileErrors ), screenshotDiffRatio: getScreenshotDiffRatio( json[key].screenshotDiff ), testName: key }); }); app.typeCheckingResult = result.slice().sort((a, b) => { return b.compileErrorsCount - a.compileErrorsCount; }); app.screenshotsCompareResult = result.slice().sort((a, b) => { return b.screenshotDiffRatio - a.screenshotDiffRatio; }); }); ``` -------------------------------- ### Build and Copy Release Resources Source: https://github.com/apache/echarts-examples/blob/gh-pages/README.md Build all necessary resources and copy them to the `echarts-website` directory. This command is typically handled by a GitHub workflow and not run manually. ```shell npm run release ``` -------------------------------- ### Run E2E Tests with Local Dependencies (esbuild) Source: https://github.com/apache/echarts-examples/blob/gh-pages/README.md Execute end-to-end tests using local versions of ECharts and ZRender dependencies, processed with esbuild for faster execution. Ensure local repositories are built. ```shell npm run test:e2e:esbuild:local > result.log 2>&1 ``` -------------------------------- ### Basic CSS for Sandbox Layout Source: https://github.com/apache/echarts-examples/blob/gh-pages/src/editor/sandbox/srcdoc.html This CSS sets up the basic layout and styling for the sandbox page, ensuring content is centered and scrollable. It also includes styles for debugging visual artifacts. ```css * { margin: 0; padding: 0; } body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif; } #chart-container { position: relative; height: 100vh; overflow: hidden; /* keep content centered on resize: */ display:flex; justify-content:center; align-items:center; } .ec-debug-dirty-rect { background-color: rgba(255, 0, 0, 0.2) !important; border: 1px solid red !important; box-sizing: border-box; } .dg.main * { box-sizing: content-box; } .dg.main input { line-height: normal; } .dg.main.a { overflow-x: visible; } .dg.main .c select { color: #000; } ``` -------------------------------- ### Run E2E Tests with Remote Dependencies (esbuild) Source: https://github.com/apache/echarts-examples/blob/gh-pages/README.md Execute end-to-end tests using remote ECharts and ZRender dependencies, processed with esbuild for faster execution. Dependencies will be downloaded to a temporary folder. ```shell npm run test:e2e:esbuild > result.log 2>&1 ``` -------------------------------- ### Initialize ECharts with Options Source: https://github.com/apache/echarts-examples/blob/gh-pages/public/en/view.html Initializes ECharts on a specific DOM element with custom configuration including locale, CDN root, and version. ```javascript echartsExample.init(document.querySelector('#main'), { locale: 'en', cdnRoot: '../', page: 'view', version: Date.now() }); ``` -------------------------------- ### Initialize ECharts Instance Source: https://github.com/apache/echarts-examples/blob/gh-pages/public/en/index.html Initializes an ECharts instance with specified options and attaches it to a DOM element. Configure locale, CDN root, and page context. The version is dynamically set using Date.now(). ```javascript echartsExample.init(document.querySelector('#main'), { locale: 'en', cdnRoot: '../', page: 'explore', version: Date.now() }); ``` -------------------------------- ### Run E2E Tests with Local Dependencies (Webpack) Source: https://github.com/apache/echarts-examples/blob/gh-pages/README.md Execute end-to-end tests using local versions of ECharts and ZRender dependencies, processed with Webpack. Ensure local repositories are built. ```shell npm run test:e2e:local > result.log 2>&1 ``` -------------------------------- ### Run E2E Tests with Remote Dependencies (Webpack) Source: https://github.com/apache/echarts-examples/blob/gh-pages/README.md Execute end-to-end tests using remote ECharts and ZRender dependencies, processed with Webpack. Dependencies will be downloaded to a temporary folder. ```shell npm run test:e2e > result.log 2>&1 ``` -------------------------------- ### Initialize ECharts Editor Source: https://github.com/apache/echarts-examples/blob/gh-pages/public/en/editor.html Initializes ECharts for an editor interface. Configure locale, CDN root, and dynamically set the version. ```javascript echartsExample.init(document.querySelector('#main'), { locale: 'en', cdnRoot: '../', page: 'editor', version: Date.now() }); ``` -------------------------------- ### Initialize ECharts and Parse Params Source: https://github.com/apache/echarts-examples/blob/gh-pages/tool/screenshot.html Initializes the ECharts instance and parses URL parameters for customization. Supports theme selection and animation control. ```javascript var params = {}; (location.search || '') .substr(1) .split('&') .forEach(function (item) { var kv = item.split('='); params[kv[0]] = kv[1]; }); var myChart = echarts.init( document.getElementById('viewport'), params.t || null ); var _getEChartsOption = function () { return myChart.getOption(); }; var app = {}; const myrng = new Math.seedrandom('echarts'); Math.random = function () { return myrng(); }; ``` -------------------------------- ### Configure Local ECharts Build Source: https://github.com/apache/echarts-examples/blob/gh-pages/README.md Create a local configuration file to point to your local ECharts build. This is useful for testing changes to ECharts itself. ```javascript exports.SCRIPT_URLS = { // This is your own web server to visit the echarts dist files. localEChartsDir: 'http://localhost:8001/echarts', localEChartsGLDir: 'http://localhost:8001/echarts-gl', // Then the echarts will be fetched by URL // http://localhost:8001/echarts/dist/echarts.js // (if `local=1` exists in the entry URL) }; ``` -------------------------------- ### Simple Pie Chart Source: https://context7.com/apache/echarts-examples/llms.txt A basic pie chart configuration using `type: 'pie'` with `radius: '50%'`. Data is provided as `{ value, name }` objects. `emphasis.itemStyle.shadowBlur` adds a hover effect. ```ts /* title: Referer of a Website category: pie difficulty: 0 */ option = { title: { text: 'Referer of a Website', subtext: 'Fake Data', left: 'center' }, tooltip: { trigger: 'item' }, legend: { orient: 'vertical', left: 'left' }, series: [{ name: 'Access From', type: 'pie', radius: '50%', data: [ { value: 1048, name: 'Search Engine' }, { value: 735, name: 'Direct' }, { value: 580, name: 'Email' }, { value: 484, name: 'Union Ads' }, { value: 300, name: 'Video Ads' } ], emphasis: { itemStyle: { shadowBlur: 10, shadowOffsetX: 0, shadowColor: 'rgba(0,0,0,0.5)' } } }] }; ``` -------------------------------- ### Generate Thumbnails for Default Theme Source: https://github.com/apache/echarts-examples/blob/gh-pages/README.md Build thumbnails specifically for the default theme. This is a more targeted approach than generating all thumbnails. ```javascript node tool/build-example.js -t default ``` -------------------------------- ### Line Chart with DataZoom and Tooltip on Mobile Source: https://context7.com/apache/echarts-examples/llms.txt Configures `triggerOn: 'none'` for tooltips and uses `axisPointer.handle` for manual positioning, suitable for touch screens. Includes pinch-zoom via `dataZoom.type: 'inside'` and gradient area fill. ```ts /* title: Tooltip and DataZoom on Mobile category: 'line, dataZoom' difficulty: 10 */ option = { tooltip: { triggerOn: 'none', position: (pt) => [pt[0], 130] }, xAxis: { type: 'time', axisPointer: { snap: true, lineStyle: { color: '#7581BD', width: 2 }, label: { show: true, formatter: (params: any) => echarts.format.formatTime('yyyy-MM-dd', params.value), backgroundColor: '#7581BD' }, handle: { show: true, color: '#7581BD' } } }, yAxis: { type: 'value' }, dataZoom: [{ type: 'inside', throttle: 50 }], series: [{ type: 'line', smooth: true, areaStyle: { color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [ { offset: 0, color: 'rgba(58,77,233,0.8)' }, { offset: 1, color: 'rgba(58,77,233,0.3)' } ]) }, data: [/* [dateStr, value], ... */] }] }; ``` -------------------------------- ### Bar Race (Animated Realtime Sort) Source: https://context7.com/apache/echarts-examples/llms.txt `realtimeSort: true` on a bar series enables live animated reordering. `myChart.setOption()` is called on a timer to push new data; `animationEasingUpdate: 'linear'` keeps transitions smooth. ```ts /* title: Bar Race category: bar difficulty: 5 videoStart: 1000 videoEnd: 6000 */ const data: number[] = []; for (let i = 0; i < 5; ++i) data.push(Math.round(Math.random() * 200)); option = { xAxis: { max: 'dataMax' }, yAxis: { type: 'category', data: ['A', 'B', 'C', 'D', 'E'], inverse: true, animationDurationUpdate: 300, max: 2 }, series: [{ realtimeSort: true, type: 'bar', data, label: { show: true, position: 'right', valueAnimation: true } }], animationDuration: 0, animationDurationUpdate: 3000, animationEasingUpdate: 'linear' }; setInterval(() => { for (let i = 0; i < data.length; i++) data[i] += Math.round(Math.random() * 200); myChart.setOption({ series: [{ type: 'bar', data }] }); }, 3000); ``` -------------------------------- ### Simple Gauge Chart Source: https://context7.com/apache/echarts-examples/llms.txt Renders a filled arc for gauge charts with `progress.show: true`. Enables smooth animation for the numeric label using `detail.valueAnimation: true`. ```typescript /* title: Simple Gauge category: gauge difficulty: 1 */ option = { tooltip: { formatter: '{a}
{b} : {c}%' }, series: [{ name: 'Pressure', type: 'gauge', progress: { show: true }, detail: { valueAnimation: true, formatter: '{value}' }, data: [{ value: 50, name: 'SCORE' }] }] }; ``` -------------------------------- ### Mock Browser Storage and Cookies Source: https://github.com/apache/echarts-examples/blob/gh-pages/src/editor/sandbox/srcdoc.html This JavaScript snippet mocks `localStorage`, `sessionStorage`, and `document.cookie` to prevent errors in environments where these are not available or restricted. It defines no-operation functions for storage methods. ```javascript (() => { const noop = () => {}; const fakeStorage = { clear: noop, setItem: noop, removeItem: noop, getItem: noop, key: noop, length: 0 }; Object.defineProperties(window, { localStorage: { value: fakeStorage }, sessionStorage: { value: fakeStorage } }); Object.defineProperty(document, 'cookie', { value: '' }); })(); ``` -------------------------------- ### Specify Matched Tests in E2E Source: https://github.com/apache/echarts-examples/blob/gh-pages/README.md Run the E2E test script, skipping certain stages and specifying a pattern to match the tests to be executed. This allows for targeted testing. ```javascript node e2e/main.js --skip npm --tests bar3D* ``` -------------------------------- ### Simple Candlestick Chart Source: https://context7.com/apache/echarts-examples/llms.txt Renders a financial K-line chart using `type: 'candlestick'`. Data is provided as tuples of `[open, close, lowest, highest]` values. ```ts /* title: Basic Candlestick category: candlestick difficulty: 0 */ option = { xAxis: { data: ['2017-10-24', '2017-10-25', '2017-10-26', '2017-10-27'] }, yAxis: {}, series: [{ type: 'candlestick', data: [ [20, 34, 10, 38], // [open, close, low, high] [40, 35, 30, 50], [31, 38, 33, 44], [38, 15, 5, 42] ] }] }; ``` -------------------------------- ### TypeScript Transform for Live Editor (JavaScript) Source: https://context7.com/apache/echarts-examples/llms.txt Performs zero-latency TypeScript to JavaScript conversion in the browser using Sucrase for the live editor. Avoids the overhead of a full tsc compile. ```javascript import transformTs from './transformTs'; const jsCode = transformTs( ` const data: number[] = [1, 2, 3]; option = { series: [{ type: 'bar', data }] }; `); // Output: "const data = [1, 2, 3];\noption = { series: [{ type: 'bar', data }] };" ``` -------------------------------- ### Animation and Progressive Rendering Preprocessor Source: https://github.com/apache/echarts-examples/blob/gh-pages/tool/screenshot.html Applies preprocessor logic to disable or control animation and progressive rendering based on URL parameters. It also ensures components have padding. ```javascript const isAnimated = !isNaN(params.start) && !isNaN(params.end) && +params.end > +params.start; echarts.registerPreprocessor(function (option) { if (!isAnimated) { option.animation = false; if (option.series) { if (!(option.series instanceof Array)) { option.series = [option.series]; } option.series.forEach(function (seriesOpt) { if (seriesOpt.type === 'graph') { seriesOpt.force = seriesOpt.force || {}; seriesOpt.force.layoutAnimation = false; } seriesOpt.progressive = 1e5; seriesOpt.animation = false; }); } } addComponentPadding(option.title); addComponentPadding(option.legend); addComponentPadding(option.toolbox); }); ``` -------------------------------- ### Skip Stages in E2E Tests Source: https://github.com/apache/echarts-examples/blob/gh-pages/README.md Run the E2E test script while skipping specific stages, such as the bundling process. This requires having run the full test suite at least once. ```javascript node e2e/main.js --skip bundle ``` -------------------------------- ### Save Command Output to Log File Source: https://github.com/apache/echarts-examples/blob/gh-pages/README.md Redirect the standard output and standard error of a command to a log file. Useful for debugging test runs. ```shell exe_something > 1.log 2>&1 ``` -------------------------------- ### Simple Graph (Network) Chart Source: https://context7.com/apache/echarts-examples/llms.txt Displays a graph with `layout: 'none'` for fixed node positions. `links` can reference nodes by index or name. `edgeSymbol` and `lineStyle.curveness` customize edge appearance. ```typescript /* title: Simple Graph category: graph difficulty: 2 */ option = { title: { text: 'Basic Graph' }, tooltip: {}, animationDurationUpdate: 1500, animationEasingUpdate: 'quinticInOut', series: [{ type: 'graph', layout: 'none', symbolSize: 50, roam: true, label: { show: true }, edgeSymbol: ['circle', 'arrow'], edgeSymbolSize: [4, 10], data: [ { name: 'Node 1', x: 300, y: 300 }, { name: 'Node 2', x: 800, y: 300 }, { name: 'Node 3', x: 550, y: 100 }, { name: 'Node 4', x: 550, y: 500 } ], links: [ { source: 0, target: 1, lineStyle: { width: 5, curveness: 0.2 } }, { source: 'Node 2', target: 'Node 1', lineStyle: { curveness: 0.2 } }, { source: 'Node 1', target: 'Node 3' } ], lineStyle: { opacity: 0.9, width: 2 } }] }; ``` -------------------------------- ### Heatmap on Cartesian Grid Source: https://context7.com/apache/echarts-examples/llms.txt Creates a heatmap using `type: 'heatmap'` with data points as `[x-index, y-index, value]` triples. `visualMap` is used for color mapping on a `splitArea` grid. ```typescript /* title: Heatmap on Cartesian category: heatmap difficulty: 0 */ const hours = ['12a','1a','2a','3a','4a','5a','6a','7a','8a','9a','10a','11a', '12p','1p','2p','3p','4p','5p','6p','7p','8p','9p','10p','11p']; const days = ['Saturday','Friday','Thursday','Wednesday','Tuesday','Monday','Sunday']; const data = [[0,0,5],[0,1,1],[/* ... */]].map(([d,h,v]) => [h, d, v || '-']); option = { tooltip: { position: 'top' }, grid: { height: '50%', top: '10%' }, xAxis: { type: 'category', data: hours, splitArea: { show: true } }, yAxis: { type: 'category', data: days, splitArea: { show: true } }, visualMap: { min: 0, max: 10, calculable: true, orient: 'horizontal', left: 'center', bottom: '15%' }, series: [{ name: 'Punch Card', type: 'heatmap', data, label: { show: true }, emphasis: { itemStyle: { shadowBlur: 10, shadowColor: 'rgba(0,0,0,0.5)' } } }] }; ``` -------------------------------- ### VideoRecorder Class for Capturing Animations Source: https://github.com/apache/echarts-examples/blob/gh-pages/tool/screenshot.html Implements a VideoRecorder class to capture ECharts animations as video. It overrides the chart's refresh mechanism to composite canvas elements and record the stream. ```javascript function VideoRecorder(chart) { this.start = startRecording; this.stop = stopRecording; var recorder = null; var oldRefreshImmediately = chart.getZr().refreshImmediately; function startRecording() { // Normal resolution or high resolution? var compositeCanvas = document.createElement('canvas'); var width = chart.getWidth(); var height = chart.getHeight(); compositeCanvas.width = width; compositeCanvas.height = height; var compositeCtx = compositeCanvas.getContext('2d'); chart.getZr().refreshImmediately = function () { var ret = oldRefreshImmediately.apply(this, arguments); var canvasList = chart.getDom().querySelectorAll('canvas'); compositeCtx.fillStyle = '#fff'; compositeCtx.fillRect(0, 0, width, height); for (var i = 0; i < canvasList.length; i++) { compositeCtx.drawImage(canvasList[i], 0, 0, width, height); } return ret; }; var stream = compositeCanvas.captureStream(25); recorder = new MediaRecorder(stream, { mimeType: 'video/webm' }); var videoData = []; recorder.ondataavailable = function (event) { if (event.data && event.data.size) { videoData.push(event.data); } }; recorder.onstop = function () { var url = URL.createObjectURL( new Blob(videoData, { type: 'video/webm' }) ); var a = document.createElement('a'); a.href = url; a.download = `${params.c}.webm`; a.click(); setTimeout(function () { window.URL.revokeObjectURL(url); }, 100); }; recorder.start(); } function stopRecording() { if (recorder) { chart.getZr().refreshImmediately = oldRefreshImmediately; recorder.stop(); } } } ``` -------------------------------- ### Basic Sankey Diagram Source: https://context7.com/apache/echarts-examples/llms.txt Visualizes flows between nodes using `type: 'sankey'`. `emphasis.focus: 'adjacency'` highlights connected paths on hover. Requires `data` for nodes and `links` for flows. ```typescript /* title: Basic Sankey category: sankey difficulty: 0 */ option = { series: { type: 'sankey', layout: 'none', emphasis: { focus: 'adjacency' }, data: [{ name: 'a' }, { name: 'b' }, { name: 'a1' }, { name: 'a2' }, { name: 'b1' }, { name: 'c' }], links: [ { source: 'a', target: 'a1', value: 5 }, { source: 'a', target: 'a2', value: 3 }, { source: 'b', target: 'b1', value: 8 }, { source: 'b1', target: 'c', value: 2 } ] } }; ``` -------------------------------- ### Stacked Bar Chart Source: https://context7.com/apache/echarts-examples/llms.txt Multiple bar series can be stacked by assigning the same `stack` key. `markLine` with `min`/`max` adds statistical annotations. The `emphasis.focus: 'series'` option dims other series on hover. ```ts /* title: Stacked Column Chart category: bar difficulty: 3 */ option = { tooltip: { trigger: 'axis', axisPointer: { type: 'shadow' } }, legend: {}, xAxis: [{ type: 'category', data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'] }], yAxis: [{ type: 'value' }], series: [ { name: 'Direct', type: 'bar', emphasis: { focus: 'series' }, data: [320, 332, 301, 334, 390, 330, 320] }, { name: 'Email', type: 'bar', stack: 'Ad', emphasis: { focus: 'series' }, data: [120, 132, 101, 134, 90, 230, 210] }, { name: 'Search Engine', type: 'bar', data: [862, 1018, 964, 1026, 1679, 1600, 1570], markLine: { lineStyle: { type: 'dashed' }, data: [[{ type: 'min' }, { type: 'max' }]] } } ] }; ``` -------------------------------- ### Handle Chart Resizing Source: https://github.com/apache/echarts-examples/blob/gh-pages/README.md Implement the `app.onresize` function to execute custom logic when the ECharts chart area is resized. ```js app.onresize = function () { // Do something. }; ``` -------------------------------- ### Basic Sunburst Chart Source: https://context7.com/apache/echarts-examples/llms.txt Visualizes hierarchical data using concentric arcs. `radius` defines the chart's inner and outer radii. `label.rotate: 'radial'` rotates text labels along the arc. ```typescript /* title: Basic Sunburst category: sunburst difficulty: 1 */ option = { series: { type: 'sunburst', radius: [0, '90%'], label: { rotate: 'radial' }, data: [ { name: 'Grandpa', children: [ { name: 'Uncle Leo', value: 15, children: [{ name: 'Cousin Jack', value: 2 }] }, { name: 'Father', value: 10, children: [{ name: 'Me', value: 5 }] } ] } ] } }; ``` -------------------------------- ### Basic Treemap Source: https://context7.com/apache/echarts-examples/llms.txt Represents hierarchical data with nested `children` arrays. Node size is proportional to its `value`. Built-in drill-down functionality is enabled by default. ```typescript /* title: Basic Treemap category: treemap */ option = { series: [{ type: 'treemap', data: [ { name: 'nodeA', value: 10, children: [ { name: 'nodeAa', value: 4 }, { name: 'nodeAb', value: 6 } ] }, { name: 'nodeB', value: 20, children: [{ name: 'nodeBa', value: 20, children: [{ name: 'nodeBa1', value: 20 }] }] } ] }] }; ``` -------------------------------- ### Basic Bar Chart Source: https://context7.com/apache/echarts-examples/llms.txt The simplest column chart: a categorical x-axis paired with a value y-axis. The globally available `option` variable is assigned and picked up by the ECharts editor runner, which calls `myChart.setOption(option)`. ```ts /* title: Basic Bar category: bar difficulty: 0 */ option = { xAxis: { type: 'category', data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'] }, yAxis: { type: 'value' }, series: [ { data: [120, 200, 150, 80, 70, 110, 130], type: 'bar' } ] }; ``` -------------------------------- ### Bar Chart with Gradient and Click Zoom Source: https://context7.com/apache/echarts-examples/llms.txt Uses echarts.graphic.LinearGradient for a vertical gradient fill. Handles click events to programmatically zoom into the clicked bar. ```ts /* title: Clickable Column Chart with Gradient category: bar difficulty: 3 */ const data = [220, 182, 191, 234, 290, 330, 310, 123, 442, 321]; option = { xAxis: { data: data.map((_, i) => `item${i}`) }, yAxis: {}, dataZoom: [{ type: 'inside' }], series: [{ type: 'bar', itemStyle: { color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [ { offset: 0, color: '#83bff6' }, { offset: 0.5, color: '#188df0' }, { offset: 1, color: '#188df0' } ]) }, data }] }; const zoomSize = 6; myChart.on('click', function (params) { myChart.dispatchAction({ type: 'dataZoom', startValue: data[Math.max(params.dataIndex - zoomSize / 2, 0)], endValue: data[Math.min(params.dataIndex + zoomSize / 2, data.length - 1)] }); }); ``` -------------------------------- ### Generate Calendar Heatmap Data Source: https://context7.com/apache/echarts-examples/llms.txt Generates daily data for a calendar heatmap. Uses ECharts' built-in time parsing and formatting utilities. Ensure `echarts.time` is available. ```typescript /* title: Simple Calendar category: calendar difficulty: 0 */ function getVirtualData(year: string): [string, number][] { const start = +echarts.time.parse(year + '-01-01'); const end = +echarts.time.parse(year + '-12-31'); const dayMs = 3600 * 24 * 1000; const result: [string, number][] = []; for (let t = start; t <= end; t += dayMs) { result.push([echarts.time.format(t, '{yyyy}-{MM}-{dd}', false), Math.floor(Math.random() * 10000)]); } return result; } option = { visualMap: { show: false, min: 0, max: 10000 }, calendar: { range: '2017' }, series: { type: 'heatmap', coordinateSystem: 'calendar', data: getVirtualData('2017') } }; ``` -------------------------------- ### Simple Scatter Chart Source: https://context7.com/apache/echarts-examples/llms.txt A basic scatter plot using `type: 'scatter'` where data is represented as `[x, y]` pairs. `symbolSize` controls the radius of the plotted points. ```ts /* title: Basic Scatter Chart category: scatter difficulty: 0 */ option = { xAxis: {}, yAxis: {}, series: [{ symbolSize: 20, data: [ [10.0, 8.04], [8.07, 6.95], [13.0, 7.58], [9.05, 8.81], [11.0, 8.33], [14.0, 7.66], [13.4, 6.81], [10.0, 6.33], [14.0, 8.96], [3.03, 4.23], [12.2, 7.83], [2.02, 4.47] ], type: 'scatter' }] }; ``` -------------------------------- ### Add Component Padding Preprocessor Source: https://github.com/apache/echarts-examples/blob/gh-pages/tool/screenshot.html Registers a preprocessor to automatically add padding to ECharts components like title, legend, and toolbox if not already defined. This ensures consistent spacing. ```javascript function addComponentPadding(componentOpt) { if (!componentOpt) { return; } if (!(componentOpt instanceof Array)) { componentOpt = [componentOpt]; } componentOpt.forEach(function (opt) { if (!opt.padding) { opt.padding = 15; } }); } ``` -------------------------------- ### Basic Area Chart Source: https://context7.com/apache/echarts-examples/llms.txt Fills the area below a line series by adding `areaStyle: {}`. `boundaryGap: false` removes the gap between data points and axis edges. ```ts /* title: Basic area chart category: line difficulty: 1 */ option = { xAxis: { type: 'category', boundaryGap: false, data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'] }, yAxis: { type: 'value' }, series: [{ data: [820, 932, 901, 934, 1290, 1330, 1320], type: 'line', areaStyle: {} }] }; ``` -------------------------------- ### Render Custom Error Bars with ECharts Source: https://context7.com/apache/echarts-examples/llms.txt Implements custom series for rendering error bars on a Cartesian coordinate system. Requires `type: 'custom'` and a `renderItem` callback. The `encode` property maps data to axes. ```typescript /* title: Error Bar on Cartesian category: custom difficulty: 3 */ option = { tooltip: { trigger: 'axis', axisPointer: { type: 'shadow' } }, dataZoom: [{ type: 'slider', start: 50, end: 70 }, { type: 'inside', start: 50, end: 70 }], xAxis: { data: ['cat0', 'cat1' /* ... */] }, yAxis: {}, series: [ { type: 'bar', name: 'bar', data: [/* barData */] }, { type: 'custom', name: 'error', itemStyle: { borderWidth: 1.5 }, renderItem(params, api) { const xValue = api.value(0); const highPoint = api.coord([xValue, api.value(1)]); const lowPoint = api.coord([xValue, api.value(2)]); const halfWidth = (api.size!([1, 0]) as number[])[0] * 0.1; const style = api.style({ stroke: api.visual('color') as string, fill: undefined }); return { type: 'group', children: [ { type: 'line', transition: ['shape'], shape: { x1: highPoint[0]-halfWidth, y1: highPoint[1], x2: highPoint[0]+halfWidth, y2: highPoint[1] }, style }, { type: 'line', transition: ['shape'], shape: { x1: highPoint[0], y1: highPoint[1], x2: lowPoint[0], y2: lowPoint[1] }, style }, { type: 'line', transition: ['shape'], shape: { x1: lowPoint[0]-halfWidth, y1: lowPoint[1], x2: lowPoint[0]+halfWidth, y2: lowPoint[1] }, style } ] }; }, encode: { x: 0, y: [1, 2] }, data: [/* [index, lowErr, highErr] */], z: 100 } ] }; ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.