ECharts is an open source visualization library implemented in JavaScript that covers industry charts for a variety of needs.

ECharts is free to use under the Apache-2.0 open source license.

ECharts is compatible with most current browsers (IE8/9/10/11, Chrome, Firefox, Safari, etc.) and a wide range of devices, and can be displayed anytime, anywhere.

directory

 

ECharts profile

ECharts installation

ECharts configuration syntax

ECharts pie chart

ECharts style Settings

ECharts loads data asynchronously

ECharts Dataset (DATASET)

ECharts Interactive components

ECharts responsive

Visual mapping of ECharts data

ECharts event processing

ECharts sun figure


ECharts profile

ECharts includes the following features:

  • Rich visualization types: Provides regular line chart, histogram, scatter plot, the pie chart, the chart, box for statistical charts, used for geographic data visualization map, heat map, chart, diagram for relational data visualization, figure treemap, the rising sun, multidimensional data visualization parallel coordinates, figure, with a funnel for BI dashboard, It also supports mash-ups between graphs.
  • Multiple data formats can be directly used without conversion: the built-in dataset attribute (4.0+) supports direct input of multiple data sources, including 2d tables, key-values and other formats, as well as TypedArray format data.
  • Front-end rendering of tens of millions of data: With incremental rendering technology (4.0+), ECharts can display tens of millions of data volumes with various fine-tuning.
  • Mobile terminal optimization: Detailed optimization is made for mobile terminal interaction. For example, the small screen on the mobile terminal is suitable for zooming and panning in the coordinate system with fingers. PC can also use the mouse to zoom (mouse wheel), pan, etc.
  • Multi-rendering scheme, cross-platform use: support to Canvas, SVG (4.0+), VML form rendering chart.
  • In-depth interactive data exploration: Provides legends, visual mapping, data area scaling, tooltip, data swipe and other out-of-the-box interactive components, which can perform multi-dimensional data sifting, view scaling, and display details.
  • Multi-dimensional data support and rich visual coding means: for traditional scatter graphs, the incoming data can also be multi-dimensional.
  • Dynamic data: Changes in data drive changes in chart presentation.
  • Gorgeous special effects: Visualizations of geographic data such as line data and point data provide eye-catching special effects.
  • Achieve more powerful and gorgeous 3D visualization through GL: achieve 3D visualization effects in VR and large screen scenes.
  • Barrier free access (4.0+) : support automatic intelligent description generation according to the chart configuration items, so that the blind can understand the chart content with the help of reading equipment, so that the chart can be accessed by more people!

The sample

<! DOCTYPE html><html>
<head>
    <meta charset="utf-8">
    <title>Sun Calls beast to demonstrate ECharts instance</title>
    <! Echarts.js -->
    <script src="https://cdn.staticfile.org/echarts/4.3.0/echarts.min.js"></script>
</head>
<body>
    <! -- Prepare a Dom with size (width and height) for ECharts
    <div id="main" style="width: 600px; height:400px;"></div>
    <script type="text/javascript">
        // Initializes the echarts instance based on the prepared DOM
        var myChart = echarts.init(document.getElementById('main'));
 
        // Specify the chart configuration items and data
        var option = {
            title: {
                text: 'Sun Call Beast Demo ECharts instance'
            },
            tooltip: {},
            legend: {
                data: ['sales']},xAxis: {
                data: ["Sun calls a beast."."1_bit"."AoBing"."Three Prince"."Which zha"."games"]},yAxis: {},
            series: [{
                name: 'sales'.type: 'bar'.data: [5.20.36.10.10.20]]}};// Display the chart using the configuration items and data you just specified.
        myChart.setOption(option);
    </script>
</body>
</html>
Copy the code

Effect:

ECharts installation

Download echarts.min.js directly and import it with the

Production environment echarts.min.js

The development environment can use the source version echarts.js imported with the

Development version echarts. Js

ECharts website directly download more rich version, contains different subjects and language, download address: www.echartsjs.com/zh/download… .

NPM method

Once installed, ECharts and Zrender will be placed in node_modules, which we can use directly in the project code using require(‘ ECharts ‘).

var echarts = require('echarts');
 
// Initializes the echarts instance based on the prepared DOM
var myChart = echarts.init(document.getElementById('main'));
// Draw a diagram
myChart.setOption({
    title: {
        text: 'Getting started with ECharts'
    },
    tooltip: {},
    xAxis: {
        data: ['shirt'.'Cardigan'.'Chiffon shirt'.'pants'.'High heels'.'socks']},yAxis: {},
    series: [{
        name: 'sales'.type: 'bar'.data: [5.20.36.10.10.20]}});Copy the code

ECharts configuration syntax

Step 1: Create an HTML page

Create an HTML page and import echarts.min.js:

<! DOCTYPEhtml>
<html>
<head>
    <meta charset="utf-8">
    <! ECharts -->
    <script src="echarts.min.js"></script>
</head>
</html>
Copy the code

Step 2: Prepare a DOM container with height and width for ECharts

The div with id main in the instance is used to contain the diagram drawn by ECharts:

<body>
    <! -- Prepare a DOM with size (width and height) for ECharts
    <div id="main" style="width: 600px; height:400px;"></div>
</body>
Copy the code

Step 3: Set the configuration information

The ECharts library is configured using json format.

echarts.init(document.getElementById('main')).setOption(option);
Copy the code

Here option means to draw the chart using a configuration in json data format. The steps are as follows:

The title

Configure a title for the chart:

Title: {text: 'Demo ECharts instance'}Copy the code

Prompt information

Configuration prompt:

tooltip: {},
Copy the code

Legend component

The legend component displays different sets of symbols, colors, and names. You can control which series are not shown by clicking on the legend.

legend: {
    data: [{
        name: Series of '1'.// Force the graph to be a circle.
        icon: 'circle'.// Set the text to red
        textStyle: {
            color: 'red'}}}]Copy the code

The X axis

Configure the items to display on the X axis:

xAxis: {
    data: ["Shirt"."Cardigan"."Chiffon shirt."."Pants"."High heels"."Socks"]}Copy the code

Y

Configure the items to display on the Y-axis.

yAxis: {}
Copy the code

Series list

Each series determines its own chart type by type:

series: [{
    name: 'sales'.// Series name
    type: 'bar'.// Series of chart types
    data: [5.20.36.10.10.20]  // The data content of the series
}]
Copy the code

Each series determines its own chart type by type:

  • Type: ‘bar’ : bar/bar graph
  • Type: ‘line’ : line/area diagram
  • Type: ‘pie’ : indicates the pie chart
  • Type: ‘scatter’ : shows the air bubbles
  • Type: ‘effectScatter’ : Scatter with ripple effect animation
  • Type: ‘radar’
  • Type: ‘tree’ : indicates the tree diagram
  • Type: ‘treemap’ : indicates the tree view
  • Type: ‘sunburst’ : sunrise
  • Type: ‘boxplot’ : boxplot
  • Type: ‘Candlestick’ : k-line graph
  • Type: ‘heatmap’ : indicates the heatmap
  • Type: ‘map’ : map
  • Type: ‘parallel’ : series of parallel coordinate systems
  • Type: ‘lines’ : line graph
  • Type: ‘graph’ : graph
  • Type: ‘sankey’ : Sankey diagram
  • Type: ‘funnel’ : funnel plot
  • Type: ‘gauge’ : indicates the dashboard
  • Type: ‘pictorialBar’ : pictograph
  • Type: ‘themeRiver’ : themeRiver
  • Type: ‘custom’ : indicates a custom series

Summary of Configuration Items

theme = {
    // The default background of the full image
    / / backgroundColor: 'rgba (0,0,0,0)',

    // Default palette
    color: ['#ff7f50'.'#87cefa'.'#da70d6'.'#32cd32'.'#6495ed'.'#ff69b4'.'#ba55d3'.'#cd5c5c'.'#ffa500'.'#40e0d0'.'#1e90ff'.'#ff6347'.'#7b68ee'.'#00fa9a'.'#ffd700'.'#6699FF'.'#ff6666'.'#3cb371'.'#b8860b'.'#30e0e0'].// Chart title
    title: {
        x: 'left'.// Horizontal position, default left alignment, optional:
                                   // 'center' takes 'right'
                                   // D {number} (x coordinates, unit: px)
        y: 'top'.// Vertical position, default is the top of the full picture, optional:
                                   // 'top' l 'base' l 'center'
                                   // D {number} (y, unit: px)
        //textAlign: null // Horizontal alignment, automatically adjusted by default based on x Settings
        backgroundColor: 'rgba (0,0,0,0)'.borderColor: '#ccc'.// Title border color
        borderWidth: 0.// Title border line width, unit px, default 0 (no border)
        padding: 5.// Title margin, unit: px, default margin 5 in each direction,
                                   // Accept arrays with upper, right, lower, and left margins, as with CSS
        itemGap: 10.// Vertical spacing of main and subtitle, unit px, default is 10,
        textStyle: {
            fontSize: 18.fontWeight: 'bolder'.color: '# 333'          // Main heading text color
        },
        subtextStyle: {
            color: '#aaa'          // Subtitle text color}},/ / legend
    legend: {
        orient: 'horizontal'.// The layout mode is horizontal by default. The options are:
                                   / / 'horizontal' ¦ 'vertical'
        x: 'center'.// Horizontal position, default is the full image center, optional:
                                   // 'center' takes 'right'
                                   // D {number} (x coordinates, unit: px)
        y: 'top'.// Vertical position, default is the top of the full picture, optional:
                                   // 'top' l 'base' l 'center'
                                   // D {number} (y, unit: px)
        backgroundColor: 'rgba (0,0,0,0)'.borderColor: '#ccc'.// Legend border color
        borderWidth: 0.// The width of the border, in px, defaults to 0 (no border)
        padding: 5.// Inner margin of legend, unit: px, default inner margin of each direction is 5,
                                   // Accept arrays with upper, right, lower, and left margins, as with CSS
        itemGap: 10.// The interval between items, in px, defaults to 10,
                                   // In a horizontal layout, the spacing is horizontal; in a vertical layout, the spacing is vertical
        itemWidth: 20.// Legend graphic width
        itemHeight: 14.// Figure height
        textStyle: {
            color: '# 333'          // Legend text color}},/ / domain
    dataRange: {
        orient: 'vertical'.// The layout mode is vertical by default. The options are:
                                   / / 'horizontal' ¦ 'vertical'
        x: 'left'.// Horizontal position, default is left aligned, optional:
                                   // 'center' takes 'right'
                                   // D {number} (x coordinates, unit: px)
        y: 'bottom'.// Vertical position, default is the bottom of the whole image, optional:
                                   // 'top' l 'base' l 'center'
                                   // D {number} (y, unit: px)
        backgroundColor: 'rgba (0,0,0,0)'.borderColor: '#ccc'.// Range border color
        borderWidth: 0.// Range border line width, unit px, default 0 (no border)
        padding: 5.// The unit is px. The default value is 5.
                                   // Accept arrays with upper, right, lower, and left margins, as with CSS
        itemGap: 10.// The interval between items, in px, defaults to 10,
                                   // In a horizontal layout, the spacing is horizontal; in a vertical layout, the spacing is vertical
        itemWidth: 20.// The width of the field graph, linear gradient horizontal layout width of this value * 10
        itemHeight: 14.// The height of the linear gradient vertical layout is this value * 10
        splitNumber: 5.// Number of segments, default is 5, 0 is a linear gradient
        color: ['#1e90ff'.'#f0ffff']./ / color
        //text:[' high ',' low '], //text, numeric text by default
        textStyle: {
            color: '# 333'          // Range text color}},toolbox: {
        orient: 'horizontal'.// The layout mode is horizontal by default. The options are:
                                   / / 'horizontal' ¦ 'vertical'
        x: 'right'.// Horizontal position, default to the right of the full picture, optional:
                                   // 'center' takes 'right'
                                   // D {number} (x coordinates, unit: px)
        y: 'top'.// Vertical position, default is the top of the full picture, optional:
                                   // 'top' l 'base' l 'center'
                                   // D {number} (y, unit: px)
        color : ['#1e90ff'.'#22bb22'.'#4b0082'.'#d2691e'].backgroundColor: 'rgba (0,0,0,0)'.// Toolbox background color
        borderColor: '#ccc'.// Toolbox border color
        borderWidth: 0.// Box border width, unit: px, default: 0 (no border)
        padding: 5.// Box margin, unit: px, default margin in each direction is 5,
                                   // Accept arrays with upper, right, lower, and left margins, as with CSS
        itemGap: 10.// The interval between items, in px, defaults to 10,
                                   // In a horizontal layout, the spacing is horizontal; in a vertical layout, the spacing is vertical
        itemSize: 16.// Toolbox graphic width
        featureImageIcon : {},     // Custom picture icon
        featureTitle : {
            mark : 'Auxiliary wire switch'.markUndo : 'Delete guides'.markClear : 'Clear the guides'.dataZoom : 'Region scaling'.dataZoomReset : 'Region scaling back'.dataView : 'Data view'.lineChart : 'Line chart Switch'.barChart : 'Bar chart switch'.restore : 'reduction'.saveAsImage : 'Save as picture'}},/ / prompt dialog box
    tooltip: {
        trigger: 'item'.// Trigger type, default data trigger, optional: 'item' axis
        showDelay: 20.// Display delay, add display delay to avoid frequent switching, unit ms
        hideDelay: 100.// Hide delay in ms
        transitionDuration : 0.4.// Animation transform time, unit s
        backgroundColor: 'rgba (0,0,0,0.7)'.// Prompts the background color, which defaults to black with transparency of 0.7
        borderColor: '# 333'.// Prompts the border color
        borderRadius: 4.// Display a rounded border, unit px, default 4
        borderWidth: 0.// Prompt border line width, unit px, default 0 (no border)
        padding: 5.// The unit is px. The default value is 5 in all directions.
                                   // Accept arrays with upper, right, lower, and left margins, as with CSS
        axisPointer : {            // Axis indicator. Axis trigger works
            type : 'line'./ / the default value is linear, optional: 'the line' | 'shadow'
            lineStyle : {          // Line indicator style Settings
                color: '#48b'.width: 2.type: 'solid'
            },
            shadowStyle : {                       // Shadow indicator style Settings
                width: 'auto'.// Shadow size
                color: 'rgba (150150150,0.3)'  // Shadow color}},textStyle: {
            color: '#fff'}},// Area scaling controller
    dataZoom: {
        orient: 'horizontal'.// The layout mode is horizontal by default. The options are:
                                   / / 'horizontal' ¦ 'vertical'
        // x: {number}, // horizontal position, default according to the grid parameter adaptation, optional:
                                   // {number} (x coordinates, unit px)
        // y: {number}, // vertical position, default based on grid parameters, optional:
                                   // {number} (y coordinates, unit px)
        // width: {number}, // specify the width, landscape layout default according to the grid parameters
        // height: {number}, // Specify the height
        backgroundColor: 'rgba (0,0,0,0)'.// Background color
        dataBackgroundColor: '#eee'.// Data background color
        fillerColor: 'rgba (144197237,0.2)'.// Fill the color
        handleColor: 'rgba (70130180,0.8)'     // Handle color
    },

    / / grid
    grid: {
        x: 80.y: 60.x2: 80.y2: 60.// width: {totalWidth} - x - x2,
        // height: {totalHeight} - y - y2,
        backgroundColor: 'rgba (0,0,0,0)'.borderWidth: 1.borderColor: '#ccc'
    },

    / / category axis
    categoryAxis: {
        position: 'bottom'./ / position
        nameLocation: 'end'./ / axis name position, support 'start' | 'end'
        boundaryGap: true.// Blank policies at the start and end of categories
        axisLine: {            // Coordinate axis
            show: true.// Default display, the property show controls whether to display
            lineStyle: {       // The property lineStyle controls line styles
                color: '#48b'.width: 2.type: 'solid'}},axisTick: {            // The axis is small
            show: true.// The property show controls whether to display
            interval: 'auto'.// onGap: null,
            inside : false.// Controls whether the small tags are in the grid
            length :5.// attribute length Specifies the length of the control line
            lineStyle: {       // The property lineStyle controls line styles
                color: '# 333'.width: 1}},axisLabel: {           // Axis text label, see axis.axisLabel
            show: true.interval: 'auto'.rotate: 0.margin: 8.// formatter: null,
            textStyle: {       // the rest of the attributes default to the global TEXTSTYLE, as shown in TEXTSTYLE
                color: '# 333'}},splitLine: {           / / separation line
            show: true.// Default display, the property show controls whether to display
            // onGap: null,
            lineStyle: {       The lineStyle attribute (see lineStyle for details) controls line styles
                color: ['#ccc'].width: 1.type: 'solid'}},splitArea: {           // Separate the area
            show: false.// No display by default. The show property controls whether to display
            // onGap: null,
            areaStyle: {       // the property areaStyle (see areaStyle) controls the areaStyle
                color: ['rgba (250250250,0.3)'.'rgba (200200200,0.3)']}}},// The default value of the numeric axis
    valueAxis: {
        position: 'left'./ / position
        nameLocation: 'end'./ / axis name position, support 'start' | 'end'
        nameTextStyle: {},     // The axis text style is global by default
        boundaryGap: [0.0].// Blank policy at the start and end of the value
        splitNumber: 5.// The number of segments to split. The default value is 5
        axisLine: {            // Coordinate axis
            show: true.// Default display, the property show controls whether to display
            lineStyle: {       // The property lineStyle controls line styles
                color: '#48b'.width: 2.type: 'solid'}},axisTick: {            // The axis is small
            show: false.// The property show controls whether to display
            inside : false.// Controls whether the small tags are in the grid
            length :5.// attribute length Specifies the length of the control line
            lineStyle: {       // The property lineStyle controls line styles
                color: '# 333'.width: 1}},axisLabel: {           // Axis text label, see axis.axisLabel
            show: true.rotate: 0.margin: 8.// formatter: null,
            textStyle: {       // the rest of the attributes default to the global TEXTSTYLE, as shown in TEXTSTYLE
                color: '# 333'}},splitLine: {           / / separation line
            show: true.// Default display, the property show controls whether to display
            lineStyle: {       The lineStyle attribute (see lineStyle for details) controls line styles
                color: ['#ccc'].width: 1.type: 'solid'}},splitArea: {           // Separate the area
            show: false.// No display by default. The show property controls whether to display
            areaStyle: {       // the property areaStyle (see areaStyle) controls the areaStyle
                color: ['rgba (250250250,0.3)'.'rgba (200200200,0.3)']}}},polar : {
        center : ['50%'.'50%'].// Global center by default
        radius : '75%'.startAngle : 90.splitNumber : 5.name : {
            show: true.textStyle: {       // the rest of the attributes default to the global TEXTSTYLE, as shown in TEXTSTYLE
                color: '# 333'}},axisLine: {            // Coordinate axis
            show: true.// Default display, the property show controls whether to display
            lineStyle: {       // The property lineStyle controls line styles
                color: '#ccc'.width: 1.type: 'solid'}},axisLabel: {           // Axis text label, see axis.axisLabel
            show: false.textStyle: {       // the rest of the attributes default to the global TEXTSTYLE, as shown in TEXTSTYLE
                color: '# 333'}},splitArea : {
            show : true.areaStyle : {
                color: ['rgba (250250250,0.3)'.'rgba (200200200,0.3)']}},splitLine : {
            show : true.lineStyle : {
                width : 1.color : '#ccc'}}},// Bar chart default parameters
    bar: {
        barMinHeight: 0.// Change the minimum height to 0
        // barWidth: null, // default adaptive
        barGap: '30%'.// The distance between columns, default is 30% of the width of the column, can be fixed value
        barCategoryGap : '20%'.// Column distance between categories, default is 20% of category spacing, can be fixed value
        itemStyle: {
            normal: {
                // color: 'different ',
                barBorderColor: '#fff'.// Bar edge lines
                barBorderRadius: 0.// The column edges are rounded, in px, and the default is 0
                barBorderWidth: 1.// The width of the sidebar, in px, defaults to 1
                label: {
                    show: false
                    // position: default adaptive, horizontal layout is 'top', vertical layout is 'right', optional
                    // 'inside'|'left'|'right'|'top'|'bottom'
                    // textStyle: null // the global textStyle is used by default. See textStyle}},emphasis: {
                // color: 'different ',
                barBorderColor: 'rgba (0,0,0,0)'.// Bar edge lines
                barBorderRadius: 0.// The column edges are rounded, in px, and the default is 0
                barBorderWidth: 1.// The width of the sidebar, in px, defaults to 1
                label: {
                    show: false
                    // position: default adaptive, horizontal layout is 'top', vertical layout is 'right', optional
                    // 'inside'|'left'|'right'|'top'|'bottom'
                    // textStyle: null // the global textStyle is used by default. See textStyle}}}},// Default line chart parameters
    line: {
        itemStyle: {
            normal: {
                // color: different,
                label: {
                    show: false
                    // position: default adaptive, horizontal layout is 'top', vertical layout is 'right', optional
                    // 'inside'|'left'|'right'|'top'|'bottom'
                    // textStyle: null // the global textStyle is used by default. See textStyle
                },
                lineStyle: {
                    width: 2.type: 'solid'.shadowColor : 'rgba (0,0,0,0)'.// Transparent by default
                    shadowBlur: 5.shadowOffsetX: 3.shadowOffsetY: 3}},emphasis: {
                // color: different,
                label: {
                    show: false
                    // position: default adaptive, horizontal layout is 'top', vertical layout is 'right', optional
                    // 'inside'|'left'|'right'|'top'|'bottom'
                    // textStyle: null // the global textStyle is used by default. See textStyle}}},//smooth : false,
        //symbol: null, // Inflection point graphic type
        symbolSize: 2.// Graph size of inflection point
        //symbolRotate: null, // Inflection point graphics rotation control
        showAllSymbol: false    // By default, only the main axis is displayed.
    },

    // Default parameters for the k-line graph
    k: {
        // barWidth: null // Default adaptive
        // barMaxWidth: null // Default adaptive
        itemStyle: {
            normal: {
                color: '#fff'.// Fill the color of the positive line
                color0: '#00aa11'.// The negative line fills the color
                lineStyle: {
                    width: 1.color: '#ff3200'.// The color of the frame
                    color0: '#00aa11'   // The color of the shadow border}},emphasis: {
                // color: different,
                / / color0: each different}}},// Scatterplot default parameters
    scatter: {
        //symbol: null, // graphic type
        symbolSize: 4.// Figure size, half-width (radius) parameter, and total width for direction or diamond figure is symbolSize * 2
        //symbolRotate: null, // Graphics rotate control
        large: false.// Large scale scatter diagram
        largeThreshold: 2000.// Large mode is enabled only when large is true and the amount of data >largeThreshold
        itemStyle: {
            normal: {
                // color: different,
                label: {
                    show: false
                    // position: default adaptive, horizontal layout is 'top', vertical layout is 'right', optional
                    // 'inside'|'left'|'right'|'top'|'bottom'
                    // textStyle: null // the global textStyle is used by default. See textStyle}},emphasis: {
                // color: 'different'
                label: {
                    show: false
                    // position: default adaptive, horizontal layout is 'top', vertical layout is 'right', optional
                    // 'inside'|'left'|'right'|'top'|'bottom'
                    // textStyle: null // the global textStyle is used by default. See textStyle}}}},// Default radar diagram parameters
    radar : {
        itemStyle: {
            normal: {
                // color: different,
                label: {
                    show: false
                },
                lineStyle: {
                    width: 2.type: 'solid'}},emphasis: {
                // color: different,
                label: {
                    show: false}}},//symbol: null, // Inflection point graphic type
        symbolSize: 2           // Computable feature parameters, empty data drag prompt graph size
        //symbolRotate: null, // Graphics rotate control
    },

    // Default pie chart parameters
    pie: {
        center : ['50%'.'50%'].// Global center by default
        radius : [0.'75%'].clockWise : false.// Counterclockwise by default
        startAngle: 90.minAngle: 0.// Change the minimum Angle to 0
        selectedOffset: 10.// Select the sector offset
        itemStyle: {
            normal: {
                // color: different,
                borderColor: '#fff'.borderWidth: 1.label: {
                    show: true.position: 'outer'
                    // textStyle: null // the global textStyle is used by default. See textStyle
                },
                labelLine: {
                    show: true.length: 20.lineStyle: {
                        // color: different,
                        width: 1.type: 'solid'}}},emphasis: {
                // color: different,
                borderColor: 'rgba (0,0,0,0)'.borderWidth: 1.label: {
                    show: false
                    // position: 'outer'
                    // textStyle: null // the global textStyle is used by default. See textStyle
                },
                labelLine: {
                    show: false.length: 20.lineStyle: {
                        // color: different,
                        width: 1.type: 'solid'}}}}},map: {
        mapType: 'china'.// All mapTypes are in Chinese for now
        mapLocation: {
            x : 'center'.y : 'center'
            // width // adaptive
            // height // adaptive
        },
        showLegendSymbol : true.// Display the legend color identifier (small dots of the series identifier), only when legend exists
        itemStyle: {
            normal: {
                // color: different,
                borderColor: '#fff'.borderWidth: 1.areaStyle: {
                    color: '#ccc'/ / rgba (135206250,0.8)
                },
                label: {
                    show: false.textStyle: {
                        color: 'rgba (139,69,19,1)'}}},emphasis: {                 // Also selected style
                // color: different,
                borderColor: 'rgba (0,0,0,0)'.borderWidth: 1.areaStyle: {
                    color: 'rgba(255,215,0,0.8)'
                },
                label: {
                    show: false.textStyle: {
                        color: 'rgba (139,69,19,1)'}}}}},force : {
        // The minimum and maximum radius of the data map to the circle
        minRadius : 10.maxRadius : 20.density : 1.0.attractiveness : 1.0.// Initialize the random size position
        initSize : 300.// The greater the centripetal force, the greater the centripetal force
        centripetal : 1.// Cooling factor
        coolDown : 0.99.// If there is a style in the category, it overrides the node default style
        itemStyle: {
            normal: {
                // color: different,
                label: {
                    show: false
                    // textStyle: null // the global textStyle is used by default. See textStyle
                },
                nodeStyle : {
                    brushType : 'both'.color : '#f08c2e'.strokeColor : '#5182ab'
                },
                linkStyle : {
                    strokeColor : '#5182ab'}},emphasis: {
                // color: different,
                label: {
                    show: false
                    // textStyle: null // the global textStyle is used by default. See textStyle
                },
                nodeStyle : {},
                linkStyle: {}}}},chord : {
        radius : ['65%'.'75%'].center : ['50%'.'50%'].padding : 2.sort : 'none'.// can be 'none', 'ascending', 'descending'
        sortSub : 'none'.// can be 'none', 'ascending', 'descending'
        startAngle : 90.clockWise : false.showScale : false.showScaleText : false.itemStyle : {
            normal : {
                label : {
                    show : true
                    // textStyle: null // the global textStyle is used by default. See textStyle
                },
                lineStyle : {
                    width : 0.color : '# 000'
                },
                chordStyle : {
                    lineStyle : {
                        width : 1.color : '# 666'}}},emphasis : {
                lineStyle : {
                    width : 0.color : '# 000'
                },
                chordStyle : {
                    lineStyle : {
                        width : 2.color : '# 333'}}}}},island: {
        r: 15.calculateStep: 0.1  // The roller can calculate step size 0.1 = 10%
    },

    markPoint : {
        symbol: 'pin'.// Annotate the type
        symbolSize: 10.// Specify the size, half-width (radius) parameter, and the total width of the graphic is symbolSize * 2 when the graphic is directional or diamond
        //symbolRotate: null, //symbolRotate control
        itemStyle: {
            normal: {
                // color: different,
                // borderColor: Different, // line color, priority over color
                borderWidth: 2.// Mark the width of the edge line, in px. Default is 1
                label: {
                    show: true.position: 'inside' / / can be selected as the 'left' | 'right' | 'top' | 'bottom'
                    // textStyle: null // the global textStyle is used by default. See textStyle}},emphasis: {
                / / color: different
                label: {
                    show: true
                    // position: 'inside' // 'left'|'right'|'top'|'bottom'
                    // textStyle: null // the global textStyle is used by default. See textStyle}}}},markLine : {
        // The symbol at the beginning and end of the line describes the type. If both are the same, you can pass string
        symbol: ['circle'.'arrow'].// Start and end symbol sizes, half-width (radius) parameters, and total width * symbolSize 2 for directional or diamond shapes
        symbolSize: [2.4].// Symbol rotation control at the beginning and end of the line
        //symbolRotate : null,
        itemStyle: {
            normal: {
                // color: different, // line color, line color, symbol color
                // borderColor: follows the color, // line symbol the borderColor, precedes the color
                borderWidth: 2.// line symbol Width of the border, in px. Default is 2
                label: {
                    show: false./ / can be selected as the 'start' | 'end' | 'left' | 'right' | 'top' | 'bottom'
                    position: 'inside'.textStyle: {         // the global TEXTSTYLE is used by default, as shown in TEXTSTYLE
                        color: '# 333'}},lineStyle: {
                    // color: With borderColor, // Main color, line color, priority over borderColor and color
                    // width: follows the borderWidth, // precedes the borderWidth
                    type: 'solid'.shadowColor : 'rgba (0,0,0,0)'.// Transparent by default
                    shadowBlur: 5.shadowOffsetX: 3.shadowOffsetY: 3}},emphasis: {
                / / color: different
                label: {
                    show: false
                    // position: 'inside' // 'left'|'right'|'top'|'bottom'
                    // textStyle: null // the global textStyle is used by default. See textStyle
                },
                lineStyle: {}}}},textStyle: {
        decoration: 'none'.fontFamily: 'Arial, Verdana, sans-serif'.fontFamily2: Microsoft Yahei.// IE8- Font is fuzzy and does not support mixing of different fonts, specify an extra copy
        fontSize: 12.fontStyle: 'normal'.fontWeight: 'normal'
    },

    // List of default flag graphic types
    symbolList : [
      'circle'.'rectangle'.'triangle'.'diamond'.'emptyCircle'.'emptyRectangle'.'emptyTriangle'.'emptyDiamond'].loadingText : 'Loading... '.// Computable feature configuration, island, prompt color
    calculable: false.// Computability is disabled by default
    calculableColor: 'rgba(255,165,0,0.6)'.// Drag and drop to indicate the border color
    calculableHolderColor: '#ccc'.// Computable placeholder prompt color
    nameConnector: '&'.valueConnector: ':'.animation: true.animationThreshold: 2500.// Animation element threshold, generated graphics elements over 2500 can not be animated
    addDataAnimation: true.// Whether to animate the dynamic data interface
    animationDuration: 2000.animationEasing: 'ExponentialOut'    //BounceOut
}
Copy the code

ECharts pie chart

The pie chart mainly shows the proportion of data of different kinds in the sum through the radian of the sector. Its data format is simpler than the bar chart, with only one-dimensional values and no categories required. Because we’re not in rectangular coordinates, we don’t need xAxis, yAxis.

Example:

<! DOCTYPE html><html>
<head>
    <meta charset="utf-8">
    <title>Example of an ECharts histogram</title>
    <! Echarts.js -->
    <script src="https://cdn.staticfile.org/echarts/4.3.0/echarts.min.js"></script>
</head>
<body>
    <! -- Prepare a Dom with size (width and height) for ECharts
    <div id="main" style="width: 600px; height:400px;"></div>
    <script type="text/javascript">
        // Initializes the echarts instance based on the prepared DOM
        var myChart = echarts.init(document.getElementById('main'));
 
        myChart.setOption({
            series: [{name: 'Access source'.type: 'pie'.// Set the chart type to pie chart
                    radius: '60%'.// The radius of the pie chart. The outer radius is 55% of the size of the visible area (the smaller of the height and width).
                    data: [// Data array, name is the data item name, value is the data item value
                        {value:100.name:'Video advertising'},
                        {value:274.name:'Affiliate advertising'},
                        {value:310.name:'Email marketing'},
                        {value:335.name:'Direct access'},
                        {value:400.name:'Search engines'}]}]})</script>
</body>
</html>
Copy the code

Effect:

Shadow configuration

The itemStyle parameter can set things like shadow, transparency, color, border color, border width, and so on:

<! DOCTYPEhtml>
<html>
<head>
    <meta charset="utf-8">
    <title>Sun Jiaolong demonstrates the ECharts histogram shadow example</title>
    <! Echarts.js -->
    <script src="https://cdn.staticfile.org/echarts/4.3.0/echarts.min.js"></script>
</head>
<body>
    <! -- Prepare a Dom with size (width and height) for ECharts
    <div id="main" style="width: 600px; height:400px;"></div>
    <script type="text/javascript">
        // Initializes the echarts instance based on the prepared DOM
        var myChart = echarts.init(document.getElementById('main'));
 
        // Specify the chart configuration items and data
        var option = {
                series: [{name: 'Access source'.type: 'pie'.radius: '55%'.data:[
                            {value:235.name:'Video advertising'},
                            {value:274.name:'Affiliate advertising'},
                            {value:310.name:'Email marketing'},
                            {value:335.name:'Direct access'},
                            {value:400.name:'Search engines'}].roseType: 'angle'.itemStyle: {
                            normal: {
                                shadowBlur: 200.shadowColor: 'rgba (0, 0, 0, 0.5)'}}}]};// Display the chart using the configuration items and data you just specified.
        myChart.setOption(option);
    </script>
</body>
</html>
Copy the code

Effect:

ECharts style Settings

ECharts can change the color, shade, size, and so on of graphic elements or text through style Settings.

Color theme

ECharts4 starts with two built-in themes, light and Dark, in addition to the default theme.

var chart = echarts.init(dom, 'light'); orvar chart = echarts.init(dom, 'dark');
Copy the code

Other themes download: echarts.apache.org/zh/theme-bu…

Theme downloads are currently available in JS and JSON versions.

If you use the JS version, you can save the JS theme code in a theme.js file, reference that file in your HTML, and finally use the theme in your code.

<! -- Introducing topic --><script src="https://sunmenglei.blog.csdn.net/static/js/wonderland.js"></script>.// HTML is called at initialization after importing wonderland.js
var myChart = echarts.init(dom, 'wonderland');
// ...
Copy the code

palette

The palette can be set in Option.

The palette is given a set of colors, from which the graphic or series automatically selects colors.

You can set the global palette, you can also set a series of their own palette.

option = {
    // Global palette.
    color: ['#c23531'.'#2f4554'.'#61a0a8'.'#d48265'.'#91c7ae'.'#749f83'.'#ca8622'.'#bda29a'.'#6e7074'.'# 546570'.'#c4ccd3'].series: [{
        type: 'bar'.// This series has its own palette.
        color: ['#dd6b66'.'#759aa0'.'#e69d87'.'#8dc1a9'.'#ea7e53'.'#eedd78'.'#73a373'.'#73b9bc'.'#7289ab'.'#91ca8c'.'#f49f42'],... }, {type: 'pie'.// This series has its own palette.
        color: ['#37A2DA'.'#32C5E9'.'#67E0E3'.'#9FE6B8'.'#FFDB5C'.'#ff9f7f'.'#fb7293'.'#E062AE'.'#E690D1'.'#e7bcf3'.'#9d96f5'.'#8378EA'.'#96BFFF'],... }}]Copy the code

Direct styles to itemStyle, lineStyle, areaStyle, label…

Here you can directly set the color of the graphic elements, line width, dot size, label text, label style, and so on.

Highlight style: Emphasis

When the mouse hovers over a graphic element, a highlighted style usually appears. By default, highlighted styles are automatically generated from normal styles.

Customizing the highlighting style can be done using the Emphasis attribute:

<! DOCTYPE html><html>
<head>
    <meta charset="utf-8">
    <title>First instance of ECharts</title>
    <! Echarts.js -->
    <script src="https://cdn.staticfile.org/echarts/4.3.0/echarts.min.js"></script>
</head>
<body>
    <! -- Prepare a Dom with size (width and height) for ECharts
    <div id="main" style="width: 600px; height:400px;"></div>
    <script type="text/javascript">
        // Initializes the echarts instance based on the prepared DOM
        var myChart = echarts.init(document.getElementById('main'));
 
        myChart.setOption({
            series: [{name: 'Access source'.type: 'pie'.// Set the chart type to pie chart
                    radius: '55%'.// The radius of the pie chart. The outer radius is 55% of the size of the visible area (the smaller of the height and width).
        // Highlight style.
        emphasis: {
            itemStyle: {
                // Highlight the color of the dot
                color: 'red'
            },
            label: {
                show: true.// Highlight the text of the label
                formatter: 'Label content when highlighted'}},data: [// Data array, name is the data item name, value is the data item value
                        {value:235.name:'Video advertising'},
                        {value:274.name:'Affiliate advertising'},
                        {value:310.name:'Email marketing'},
                        {value:335.name:'Direct access'},
                        {value:400.name:'Search engines'}]}]})</script>
</body>
</html>
Copy the code

ECharts loads data asynchronously

ECharts data is usually set in setOption. If we need to load data asynchronously, we can use jQuery and other tools to load data asynchronously and fill in data and configuration items through setOption.

Echarts_test_data. Json data:

{
    "data_pie": [{"value":235."name":"Video advertising"},
    {"value":274."name":"Affiliate advertising"},
    {"value":310."name":"Email marketing"},
    {"value":335."name":"Direct access"},
    {"value":400."name":"Search engine"}}]Copy the code
<! DOCTYPEhtml>
<html>
<head>
    <meta charset="utf-8">
    <title>First instance of ECharts</title>
    <script src="https://cdn.staticfile.org/jquery/2.2.4/jquery.min.js"></script>
    <! Echarts.js -->
    <script src="https://cdn.staticfile.org/echarts/4.3.0/echarts.min.js"></script>
</head>
<body>
    <! -- Prepare a Dom with size (width and height) for ECharts
    <div id="main" style="width: 600px; height:400px;"></div>
    <script type="text/javascript">
        // Initializes the echarts instance based on the prepared DOM
        var myChart = echarts.init(document.getElementById('main'));
        $.get('https://sunmenglei.blog.csdn.net/static/js/echarts_test_data.json'.function (data) {
            myChart.setOption({
                series: [{name: 'Access source'.type: 'pie'.// Set the chart type to pie chart
                        radius: '55%'.// The radius of the pie chart. The outer radius is 55% of the size of the visible area (the smaller of the height and width).
                        data:data.data_pie
                    }
                ]
            })
        }, 'json')
    </script>
</body>
Copy the code

If asynchronous loading takes a while, you can add a loading effect. ECharts provides a simple loading animation by default. Simply call the showLoading method to display. Call the hideLoading method to hide the loading animation after the data is loaded:

<! DOCTYPEhtml>
<html>
<head>
    <meta charset="utf-8">
    <title>First instance of ECharts</title>
    <script src="https://cdn.staticfile.org/jquery/2.2.4/jquery.min.js"></script>
    <! Echarts.js -->
    <script src="https://cdn.staticfile.org/echarts/4.3.0/echarts.min.js"></script>
</head>
<body>
    <! -- Prepare a Dom with size (width and height) for ECharts
    <div id="main" style="width: 600px; height:400px;"></div>
    <script type="text/javascript">
        // Initializes the echarts instance based on the prepared DOM
        var myChart = echarts.init(document.getElementById('main'));
		myChart.showLoading();  // Enable the loading effect
	
        $.get('https://sunmenglei.blog.csdn.net/static/js/echarts_test_data.json'.function (data) {
            alert("You can see loading."); // Test the code to see the loading effect
			myChart.hideLoading();  // Hide the loading effect
			myChart.setOption({
                series: [{name: 'Access source'.type: 'pie'.// Set the chart type to pie chart
                        radius: '55%'.// The radius of the pie chart. The outer radius is 55% of the size of the visible area (the smaller of the height and width).
                        data:data.data_pie
                    }
                ]
            })
        }, 'json');
    </script>
</body>
Copy the code

Dynamic update of data

ECharts is driven by data, and changes in data drive changes in the diagram presentation, making dynamic data extremely easy to implement.

All data updates are done through setOption, you just need to get the data periodically, setOption fills in the data, regardless of what changes are made to the data, ECharts will find the difference between the two sets of data and use the appropriate animation to represent the data changes.

<! DOCTYPEhtml>
<html>
<head>
    <meta charset="utf-8">
    <title>First instance of ECharts</title>
    <script src="https://cdn.staticfile.org/jquery/2.2.4/jquery.min.js"></script>
    <! Echarts.js -->
    <script src="https://cdn.staticfile.org/echarts/4.3.0/echarts.min.js"></script>
</head>
<body>
    <! -- Prepare a Dom with size (width and height) for ECharts
    <div id="main" style="width: 600px; height:400px;"></div>
    <script type="text/javascript">
        var base = +new Date(2014.9.3);
		var oneDay = 24 * 3600 * 1000;
		var date = [];

		var data = [Math.random() * 150];
		var now = new Date(base);

		function addData(shift) {
		    now = [now.getFullYear(), now.getMonth() + 1, now.getDate()].join('/');
		    date.push(now);
		    data.push((Math.random() - 0.4) * 10 + data[data.length - 1]);

		    if (shift) {
		        date.shift();
		        data.shift();
		    }

		    now = new Date(+new Date(now) + oneDay);
		}

		for (var i = 1; i < 100; i++) {
		    addData();
		}

		option = {
		    xAxis: {
		        type: 'category'.boundaryGap: false.data: date
		    },
		    yAxis: {
		        boundaryGap: [0.'50%'].type: 'value'
		    },
		    series: [{name:'transaction'.type:'line'.smooth:true.symbol: 'none'.stack: 'a'.areaStyle: {
		                normal: {}},data: data
		        }
		    ]
		};

		setInterval(function () {
		    addData(true);
		    myChart.setOption({
		        xAxis: {
		            data: date
		        },
		        series: [{
		            name:'transaction'.data: data
		        }]
		    });
		}, 500);
		
        // Initializes the echarts instance based on the prepared DOM
        var myChart = echarts.init(document.getElementById('main'));
        myChart.setOption(option)
    </script>
</body>
Copy the code

ECharts Dataset (DATASET)

ECharts uses the dataset to manage data.

Dataset components are used for separate dataset declarations so that data can be managed separately, reused by multiple components, and data-to-visual mappings can be specified based on the data.

Here is an example of the simplest dataset:

<! DOCTYPEhtml>
<html>
<head>
    <meta charset="utf-8">
    <title>First instance of ECharts</title>
    <! Echarts.js -->
    <script src="https://cdn.staticfile.org/echarts/4.3.0/echarts.min.js"></script>
</head>
<body>
    <! -- Prepare a Dom with size (width and height) for ECharts
    <div id="main" style="width: 600px; height:400px;"></div>
    <script type="text/javascript">
        // Initializes the echarts instance based on the prepared DOM
        var myChart = echarts.init(document.getElementById('main'));
 
        // Specify the chart configuration items and data
        var option = {
            legend: {},
            tooltip: {},
            dataset: {
                // Provide a piece 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 (category). By default, the category axis corresponds to the first column of the dataset.
            xAxis: {type: 'category'},
            // Declare a Y-axis, a numeric axis.
            yAxis: {},
            // Declare multiple bar series. By default, each series automatically corresponds to each column of the dataset.
            series: [{type: 'bar'},
                {type: 'bar'},
                {type: 'bar'}};// Display the chart using the configuration items and data you just specified.
        myChart.setOption(option);
    </script>
</body>
</html>
Copy the code

Effect:

Example:

<! DOCTYPEhtml>
<html>
<head>
    <meta charset="utf-8">
    <title>A data set in object array format</title>
    <! Echarts.js -->
    <script src="./js/echarts.js"></script>
</head>
<body>
    <! -- Prepare a Dom with size (width and height) for ECharts
    <div id="main" style="width: 600px; height:400px;"></div>
    <script type="text/javascript">
        // Initializes the echarts instance based on the prepared DOM
        var myChart = echarts.init(document.getElementById('main'));
 
        // Specify the chart configuration items and data
        var option = {
                legend: {},
                tooltip: {},
                dataset: {
                    // The order of dimension names is specified so that the default dimension to axis mapping can be used.
                    // If you do not specify dimensions, you can also do the mapping by specifying series.encode, see below.
                    dimensions: ['product'.'2019'.'2020'.'2021'].source: [{product: 'Matcha Latte'.'2019': 43.3.'2020': 85.8.'2021': 93.7},
                        {product: 'Milk Tea'.'2019': 83.1.'2020': 73.4.'2021': 55.1},
                        {product: 'Cheese Cocoa'.'2019': 86.4.'2020': 65.2.'2021': 82.5},
                        {product: 'Walnut Brownie'.'2019': 72.4.'2020': 53.9.'2021': 39.1}},xAxis: {type: 'category'},
                yAxis: {},
                series: [{type: 'bar'},
                    {type: 'bar'},
                    {type: 'bar'}};// Display the chart using the configuration items and data you just specified.
        myChart.setOption(option);
    </script>
</body>
</html>
Copy the code

Mapping of data to graphics

We can map data to graphs in configuration items.

SeriesLayoutBy we can use the series.seriesLayoutby property to configure whether the dataset maps columns or rows to series. By default, the mapping is by column.

In the following example, we will use the seriesLayoutBy property to configure whether data is displayed in columns or rows.

Effect:

Example:

<! DOCTYPEhtml>
<html>
<head>
    <meta charset="utf-8">
    <title>Data to graph mapping of ECharts instances</title>
    <! Echarts.js -->
    <script src="./js/echarts.js"></script>
</head>
<body>
    <! -- Prepare a Dom with size (width and height) for ECharts
    <div id="main" style="width: 600px; height:400px;"></div>
    <script type="text/javascript">
        // Initializes the echarts instance based on the prepared DOM
        var myChart = echarts.init(document.getElementById('main'));
 
        // Specify the chart configuration items and data
        var option = {
                legend: {},// Explain
                tooltip: {},// Prompt message
                dataset: {/ / data set
                    source: [['product'.'2018'.'2019'.'2020'.'2021'],
                        ['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: [/ / the X axis
                    {type: 'category'.gridIndex: 0},
                    {type: 'category'.gridIndex: 1}].yAxis: [/ / y
                    {gridIndex: 0},
                    {gridIndex: 1}].grid: [/ / coordinates
                    {bottom: '55%'},
                    {top: '55%'}].series: [
                    // These series will be in the first cartesian coordinate system, each series corresponds to each row of the dataset.
                    {type: 'bar'.seriesLayoutBy: 'row'},
                    {type: 'bar'.seriesLayoutBy: 'row'},
                    {type: 'bar'.seriesLayoutBy: 'row'},
                    // These series will be in the second cartesian coordinate system, each series corresponds to each column of the dataset.
                    {type: 'bar'.xAxisIndex: 1.yAxisIndex: 1},
                    {type: 'bar'.xAxisIndex: 1.yAxisIndex: 1},
                    {type: 'bar'.xAxisIndex: 1.yAxisIndex: 1},
                    {type: 'bar'.xAxisIndex: 1.yAxisIndex: 1}}]// Display the chart using the configuration items and data you just specified.
        myChart.setOption(option);
    </script>
</body>
</html>
Copy the code

Most of the data described in common charts are “two-dimensional tables” structure, we can use the series.encode attribute to map the corresponding data to coordinate axes (such as X and Y axes) :

Example:

<! DOCTYPEhtml>
<html>
<head>
    <meta charset="utf-8">
    <title>The series.encode attribute maps the corresponding data to coordinate axes (such as X and Y axes) : ECharts instances</title>
    <! Echarts.js -->
    <script src="https://cdn.staticfile.org/echarts/4.3.0/echarts.min.js"></script>
</head>
<body>
    <! -- Prepare a Dom with size (width and height) for ECharts
    <div id="main" style="width: 600px; height:400px;"></div>
    <script type="text/javascript">
        // Initializes the echarts instance based on the prepared DOM
        var myChart = echarts.init(document.getElementById('main'));
 
        // Specify the chart configuration items and data
        var option = {
                dataset: {
                    source: [['score'.'amount'.'product'],
                        [89.3.58212.'Matcha Latte'],
                        [57.1.78254.'Milk Tea'],
                        [74.4.41032.'Cheese Cocoa'],
                        [50.1.12755.'Cheese Brownie'],
                        [89.7.20145.'Matcha Cocoa'],
                        [68.1.79146.'Tea'],
                        [19.6.91852.'Orange Juice'],
                        [10.6.101852.'Lemon Juice'],
                        [32.7.20112.'Walnut Brownie']]},grid: {containLabel: true},
                xAxis: {},
                yAxis: {type: 'category'},
                series: [{type: 'bar'.encode: {
                            Map the "amount" column to the X-axis.
                            x: 'amount'.// Map the "product" column to the Y-axis.
                            y: 'product'}}};// Display the chart using the configuration items and data you just specified.
        myChart.setOption(option);
    </script>
</body>
</html>
Copy the code

Effect:

The basic structure of the encode declaration is as follows, where the left side of the colon is the coordinate system, the specific name of the label, such as ‘x’, ‘y’, ‘tooltip’, etc., and the right side of the colon is the dimension name (string format) or the serial number of the dimension in the data (number format, counting from 0). You can specify one or more dimensions (using arrays). In general, you don’t need to include all of the following information, just as needed.

Here are the attributes that Encode supports:

// In any coordinate system and series, support: encode: {// Display tooltip in tooltip with values of "dimension named product" and "dimension named score" : ['product', 'score'] // Use the dimension names of 'dimension 1' and 'dimension 3' to concatenate the series names. SeriesName: [1, 3], // indicates that the value of dimension 2 is used as the ID. This is useful when using setOption to update data dynamically, matching old and new data with ids to generate appropriate data update animations. ItemId: 2, // Specify the name of the data item. Using "dimension 3" is useful in charts such as pie charts and can make the name appear in legend. ItemName: 3} // map 'dimension 1', 'dimension 5', 'dimension named score' to X-axis: X: [1, 5, 'score'], // map dimension 0 to the Y-axis. Y: 0} // encode: {single: 3} // polar: {radius: 3, Angle: Encode: {LNG: 3, lat: 2} // For some charts without coordinates, such as pie charts, funnel charts, etc., it can be: encode: {value: 3}Copy the code
<! DOCTYPEhtml>
<html>
<head>
    <meta charset="utf-8">
    <title>ECharts instance</title>
	<script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js"></script>
    <! Echarts.js -->
    <script src="https://cdn.staticfile.org/echarts/4.3.0/echarts.min.js"></script>
</head>
<body>
    <! -- Prepare a Dom with size (width and height) for ECharts
    <div id="main" style="width: 600px; height:400px;"></div>
    <script type="text/javascript">
        // Initializes the echarts instance based on the prepared DOM
        var myChart = echarts.init(document.getElementById('main'));
 
        // Specify the chart configuration items and data
        $.get('https://www.sunjiaoshou.top/static/js/life-expectancy-table.json'.function (data) {

        var sizeValue = '57%';
        var symbolSize = 2.5;
        option = {
            legend: {},
            tooltip: {},
            toolbox: {
                left: 'center'.feature: {
                    dataZoom: {}}}.grid: [{right: sizeValue, bottom: sizeValue},
                {left: sizeValue, bottom: sizeValue},
                {right: sizeValue, top: sizeValue},
                {left: sizeValue, top: sizeValue}
            ],
            xAxis: [{type: 'value'.gridIndex: 0.name: 'Income'.axisLabel: {rotate: 50.interval: 0}},
                {type: 'category'.gridIndex: 1.name: 'Country'.boundaryGap: false.axisLabel: {rotate: 50.interval: 0}},
                {type: 'value'.gridIndex: 2.name: 'Income'.axisLabel: {rotate: 50.interval: 0}},
                {type: 'value'.gridIndex: 3.name: 'Life Expectancy'.axisLabel: {rotate: 50.interval: 0}}].yAxis: [{type: 'value'.gridIndex: 0.name: 'Life Expectancy'},
                {type: 'value'.gridIndex: 1.name: 'Income'},
                {type: 'value'.gridIndex: 2.name: 'Population'},
                {type: 'value'.gridIndex: 3.name: 'Population'}].dataset: {
                dimensions: [
                    'Income'.'Life Expectancy'.'Population'.'Country',
                    {name: 'Year'.type: 'ordinal'}].source: data
            },
            series: [{type: 'scatter'.symbolSize: symbolSize,
                    xAxisIndex: 0.yAxisIndex: 0.encode: {
                        x: 'Income'.y: 'Life Expectancy'.tooltip: [0.1.2.3.4]}}, {type: 'scatter'.symbolSize: symbolSize,
                    xAxisIndex: 1.yAxisIndex: 1.encode: {
                        x: 'Country'.y: 'Income'.tooltip: [0.1.2.3.4]}}, {type: 'scatter'.symbolSize: symbolSize,
                    xAxisIndex: 2.yAxisIndex: 2.encode: {
                        x: 'Income'.y: 'Population'.tooltip: [0.1.2.3.4]}}, {type: 'scatter'.symbolSize: symbolSize,
                    xAxisIndex: 3.yAxisIndex: 3.encode: {
                        x: 'Life Expectancy'.y: 'Population'.tooltip: [0.1.2.3.4}}]}; myChart.setOption(option); });</script>
</body>
</html>
Copy the code

Mapping of visual channels (color, size, etc.)

We can map visual channels using the visualMap component.

Visual elements can be:

  • Symbol: Graphic type of a symbol.
  • SymbolSize: The size of the symbol.
  • Color: indicates the color of the primitive.
  • ColorAlpha: Transparency of the pixel’s color.
  • Opacity: the transparency of primitives and their appendages, such as text tags.
  • ColorLightness: the brightness or shade of a color.
  • ColorSaturation: saturation of colors.
  • ColorHue: indicates the hue of a color.

The visualMap component can define more than one to visually map multiple dimensions in the data simultaneously.

<! DOCTYPEhtml>
<html>
<head>
    <meta charset="utf-8">
    <title>ECharts instance</title>
    <! Echarts.js -->
    <script src="https://cdn.staticfile.org/echarts/4.3.0/echarts.min.js"></script>
</head>
<body>
    <! -- Prepare a Dom with size (width and height) for ECharts
    <div id="main" style="width: 600px; height:400px;"></div>
    <script type="text/javascript">
        // Initializes the echarts instance based on the prepared DOM
        var myChart = echarts.init(document.getElementById('main'));
 
        var option = {
                dataset: {
                    source: [['score'.'amount'.'product'],
                        [89.3.58212.'Matcha Latte'],
                        [57.1.78254.'Milk Tea'],
                        [74.4.41032.'Cheese Cocoa'],
                        [50.1.12755.'Cheese Brownie'],
                        [89.7.20145.'Matcha Cocoa'],
                        [68.1.79146.'Tea'],
                        [19.6.91852.'Orange Juice'],
                        [10.6.101852.'Lemon Juice'],
                        [32.7.20112.'Walnut Brownie']]},grid: {containLabel: true},
                xAxis: {name: 'amount'},
                yAxis: {type: 'category'},
                visualMap: {
                    orient: 'horizontal'.left: 'center'.min: 10.max: 100.text: ['High Score'.'Low Score'].// Map the score column to color
                    dimension: 0.inRange: {
                        color: ['#D7DA8B'.'#E15457']}},series: [{type: 'bar'.encode: {
                            // Map the "amount" column to X axis.
                            x: 'amount'.// Map the "product" column to Y axis
                            y: 'product'}}}; myChart.setOption(option);</script>
</body>
</html>
Copy the code

Effect:

The interaction between

In the following example, multiple charts share a dataset with linkage interactions

<! DOCTYPEhtml>
<html>
<head>
    <meta charset="utf-8">
    <title>Linkage interaction ECharts instance</title>
    <! Echarts.js -->
    <script src="https://cdn.staticfile.org/echarts/4.3.0/echarts.min.js"></script>
</head>
<body>
    <! -- Prepare a Dom with size (width and height) for ECharts
    <div id="main" style="width: 600px; height:400px;"></div>
    <script type="text/javascript">
        // Initializes the echarts instance based on the prepared DOM
        var myChart = echarts.init(document.getElementById('main'));
 
        
        setTimeout(function () {

            option = {
                legend: {},
                tooltip: {
                    trigger: 'axis'.showContent: false
                },
                dataset: {
                    source: [['product'.'2017'.'2018'.'2019'.'2020'.'2021'.'2022'],
                        ['Matcha Latte'.41.1.30.4.65.1.53.3.83.8.98.7],
                        ['Milk Tea'.86.5.92.1.85.7.83.1.73.4.55.1],
                        ['Cheese Cocoa'.24.1.67.2.79.5.86.4.65.2.82.5],
                        ['Walnut Brownie'.55.2.67.1.69.2.72.4.53.9.39.1]]},xAxis: {type: 'category'},
                yAxis: {gridIndex: 0},
                grid: {top: '55%'},
                series: [{type: 'line'.smooth: true.seriesLayoutBy: 'row'},
                    {type: 'line'.smooth: true.seriesLayoutBy: 'row'},
                    {type: 'line'.smooth: true.seriesLayoutBy: 'row'},
                    {type: 'line'.smooth: true.seriesLayoutBy: 'row'},
                    {
                        type: 'pie'.id: 'pie'.radius: '30%'.center: ['50%'.'25%'].label: {
                            formatter: '{b}: {@2012} ({d}%)'
                        },
                        encode: {
                            itemName: 'product'.value: '2012'.tooltip: '2012'}}}; myChart.on('updateAxisPointer'.function (event) {
                var xAxisInfo = event.axesInfo[0];
                if (xAxisInfo) {
                    var dimension = xAxisInfo.value + 1;
                    myChart.setOption({
                        series: {
                            id: 'pie'.label: {
                                formatter: '{b}: {@[' + dimension + ']} ({d}%)'
                            },
                            encode: {
                                value: dimension,
                                tooltip: dimension } } }); }}); myChart.setOption(option); });</script>
</body>
</html>
Copy the code

Effect:

ECharts Interactive components

ECharts provides many interactive components: Legend, title, visualMap, dataZoom and Timeline.

Next we’ll show you how to scale the dataZoom using the data area component.

The dataZoom component allows you to zoom in and out of charts by scrolling through the mouse wheel.

By default, the dataZoom controls the X-axis by scaling and panning the X-axis.

<! DOCTYPEhtml>
<html>
<head>
    <meta charset="utf-8">
    <title>DataZoom component ECharts instance</title>
    <! Echarts.js -->
    <script src="js/echarts.js"></script>
</head>
<body>
    <! -- Prepare a Dom with size (width and height) for ECharts
    <div id="main" style="width: 600px; height:400px;"></div>
    <script type="text/javascript">
        // Initializes the echarts instance based on the prepared DOM
        var myChart = echarts.init(document.getElementById('main'));
 
        // Specify the chart configuration items and data
        var option = {
                xAxis: {
                    type: 'value'
                },
                yAxis: {
                    type: 'value'
                },
                dataZoom: [{// This dataZoom component controls the X axis by default.
                        type: 'slider'.// The dataZoom component is slider dataZoom
                        start: 10.// The left side is at 10%.
                        end: 60         // The right side is at 60%.}].series: [{type: 'scatter'.// This is a "scatter plot"
                        itemStyle: {
                            opacity: 0.8
                        },
                        symbolSize: function (val) {
                            return val[2] * 40;
                        },
                        data: [["14.616"."7.241"."0.896"], ["3.958"."5.701"."0.955"], ["2.768"."8.971"."0.669"], ["9.051"."9.710"."0.171"], ["14.046"."4.182"."0.536"], ["12.295"."1.429"."0.962"], ["4.417"."8.167"."0.113"], ["0.492"."4.771"."0.785"], ["7.632"."2.605"."0.645"], ["14.242"."5.042"."0.368"]]]}}// Display the chart using the configuration items and data you just specified.
        myChart.setOption(option);
    </script>
</body>
</html>
Copy the code

Effect:

The above example can only drag the dataZoom component to shrink or enlarge the chart. If you want to drag around the coordinate system and zoom with the mouse wheel (or move the touch screen with a two-finger swipe), you need to add an inside-type dataZoom component.

Add type: ‘inside’ to this example:

  dataZoom: [
                    {   // This dataZoom component controls the X axis by default.
                        type: 'slider'.// The dataZoom component is slider dataZoom
                        start: 10.// The left side is at 10%.
                        end: 60         // The right side is at 60%.
                    },
					{   // This dataZoom component also controls the X axis.
					            type: 'inside'.// This dataZoom component is an inside dataZoom component
					            start: 10.// The left side is at 10%.
					            end: 60         // The right side is at 60%.}].Copy the code

You can specify which or which number lines are controlled by dataZoom. XAxisIndex or dataZoom. YAxisIndex.

<! DOCTYPEhtml>
<html>
<head>
    <meta charset="utf-8">
    <title>ECharts instance</title>
    <! Echarts.js -->
    <script src="./js/echarts.min.js"></script>
</head>
<body>
    <! -- Prepare a Dom with size (width and height) for ECharts
    <div id="main" style="width: 600px; height:400px;"></div>
    <script type="text/javascript">
        // Initializes the echarts instance based on the prepared DOM
        var myChart = echarts.init(document.getElementById('main'));
 
        // Specify the chart configuration items and data
        var data1 = [];
        var data2 = [];
        var data3 = [];

        var random = function (max) {
            return (Math.random() * max).toFixed(3);
        };

        for (var i = 0; i < 500; i++) {
            data1.push([random(15), random(10), random(1)]);
            data2.push([random(10), random(10), random(1)]);
            data3.push([random(15), random(10), random(1)]);
        }

        option = {
            animation: false.legend: {
                data: ['scatter'.'scatter2'.'scatter3']},tooltip: {},xAxis: {
                type: 'value'.min: 'dataMin'.max: 'dataMax'.splitLine: {
                    show: true}},yAxis: {
                type: 'value'.min: 'dataMin'.max: 'dataMax'.splitLine: {
                    show: true}},dataZoom: [{type: 'slider'.show: true.xAxisIndex: [0].start: 1.end: 35
                },
                {
                    type: 'slider'.show: true.yAxisIndex: [0].left: '93%'.start: 29.end: 36
                },
                {
                    type: 'inside'.xAxisIndex: [0].start: 1.end: 35
                },
                {
                    type: 'inside'.yAxisIndex: [0].start: 29.end: 36}].series: [{name: 'scatter'.type: 'scatter'.itemStyle: {
                        normal: {
                            opacity: 0.8}},symbolSize: function (val) {
                        return val[2] * 40;
                    },
                    data: data1
                },
                {
                    name: 'scatter2'.type: 'scatter'.itemStyle: {
                        normal: {
                            opacity: 0.8}},symbolSize: function (val) {
                        return val[2] * 40;
                    },
                    data: data2
                },
                {
                    name: 'scatter3'.type: 'scatter'.itemStyle: {
                        normal: {
                            opacity: 0.8,}},symbolSize: function (val) {
                        return val[2] * 40;
                    },
                    data: data3
                }
            ]
        }
 
        // Display the chart using the configuration items and data you just specified.
        myChart.setOption(option);
    </script>
</body>
</html>
Copy the code

Effect:

ECharts responsive

The ECharts diagram is displayed in a DOM node (container) of specified height and width.

Sometimes we want to be able to display the content of a chart on both PC and mobile devices, and to achieve responsive design, ECharts has improved the positioning of components and implemented adaptive capabilities.

Positioning and layout of ECharts components

Most “components” and “families” follow one of two directions.

Left/right/top/bottom/width/height positioning way

Each of these six quantities can be “absolute value” or “percentage” or “positional description”.

  • The absolute value

    The units are browser pixels (px), written as numbers (no units). For example {left: 23, height: 400}.

  • The percentage

    Represents the percentage of the height and width of the DOM container, written as a string. For example {right: ‘30%’, bottom: ‘40%’}.

  • Position description

    • You can set theleft: 'center', indicating that the level is in the middle.
    • You can set thetop: 'middle'Is vertically centered.

The concepts of these six quantities are similar to those of CSS:

  • Left: the distance from the left edge of the DOM container.
  • Right: distance from the right edge of the DOM container.
  • Top: the distance from the top edge of the DOM container.
  • Bottom: Distance from the bottom edge of the DOM container.
  • Width: indicates the width.
  • Height:

In landscape, only two of the three variables left, right, and width need to have values, because any two variables can determine the position and size of the component, such as left and right or right and width. Vertical, top, bottom, height vertical, top, bottom, height

Center/RADIUS locating mode

  • center

    Is an array representing [x, y], where x and y can be “absolute value” or “percentage”, meaning the same as before.

  • radius

    Is an array representing [inner radius, outer radius], where the inner radius can be “absolute value” or “percentage”, which has the same meaning as above.

    Percentage Settings are useful when it comes to adaptive container sizes.

Horizontal and vertical

ECharts’ “long and narrow” components (legend, visualMap, dataZoom, Timeline, etc.) mostly provide “landscape” and “vertical” options. For example, on a thin mobile screen, it might be appropriate to use “vertical layout”; On a PC widescreen, a “landscape layout” may be appropriate.

Horizontal and vertical layout Settings are generally set to ‘horizontal’ or ‘vertical’ on the Orient or Layout TAB of a component or series.

<! DOCTYPEhtml>
<html>
<head>
    <meta charset="utf-8">
    <title>ECharts instance</title>
	<script src="https://cdn.staticfile.org/jquery/2.2.4/jquery.min.js"></script>
    <! Echarts.js -->
    <script src="https://cdn.staticfile.org/echarts/4.3.0/echarts.min.js"></script>
</head>
<body>
    <! -- Prepare a Dom with size (width and height) for ECharts
    <div id="main" style="width: 600px; height:400px;"></div>
    <script type="text/javascript">
        // Initializes the echarts instance based on the prepared DOM
        var myChart = echarts.init(document.getElementById('main'));
 
        $.when(
            $.getScript('https://www.sunjia0shou.com/static/js/timelineGDP.js'),
            $.getScript('https://www.sunjiaoshou.com/static/js/draggable.js')
        ).done(function () {

            draggable.init(
                $('div[_echarts_instance_]') [0],
                myChart,
                {
                    width: 700.height: 400.throttle: 70}); myChart.hideLoading(); option = {baseOption: {
                    title : {
                        text: 'Nightingale roses'.subtext: 'Pure fiction'.x:'center'
                    },
                    tooltip : {
                        trigger: 'item'.formatter: "{a} <br/>{b} : {c} ({d}%)"
                    },
                    legend: {
                        data: ['rose1'.'rose2'.'rose3'.'rose4'.'rose5'.'rose6'.'rose7'.'rose8']},toolbox: {
                        show : true.feature : {
                            mark : {show: true},
                            dataView : {show: true.readOnly: false},
                            magicType : {
                                show: true.type: ['pie'.'funnel']},restore : {show: true},
                            saveAsImage : {show: true}}},calculable : true.series: [{name:'Radius mode'.type:'pie'.roseType : 'radius'.label: {
                                normal: {
                                    show: false
                                },
                                emphasis: {
                                    show: true}},lableLine: {
                                normal: {
                                    show: false
                                },
                                emphasis: {
                                    show: true}},data:[
                                {value:10.name:'rose1'},
                                {value:5.name:'rose2'},
                                {value:15.name:'rose3'},
                                {value:25.name:'rose4'},
                                {value:20.name:'rose5'},
                                {value:35.name:'rose6'},
                                {value:30.name:'rose7'},
                                {value:40.name:'rose8'}]}, {name:'Area model'.type:'pie'.roseType : 'area'.data:[
                                {value:10.name:'rose1'},
                                {value:5.name:'rose2'},
                                {value:15.name:'rose3'},
                                {value:25.name:'rose4'},
                                {value:20.name:'rose5'},
                                {value:35.name:'rose6'},
                                {value:30.name:'rose7'},
                                {value:40.name:'rose8'}]}]},media: [{option: {
                            legend: {
                                right: 'center'.bottom: 0.orient: 'horizontal'
                            },
                            series: [{radius: [20.'50%'].center: ['25%'.'50%'] {},radius: [30.'50%'].center: ['75%'.'50%']}]}}, {query: {
                            minAspectRatio: 1
                        },
                        option: {
                            legend: {
                                right: 'center'.bottom: 0.orient: 'horizontal'
                            },
                            series: [{radius: [20.'50%'].center: ['25%'.'50%'] {},radius: [30.'50%'].center: ['75%'.'50%']}]}}, {query: {
                            maxAspectRatio: 1
                        },
                        option: {
                            legend: {
                                right: 'center'.bottom: 0.orient: 'horizontal'
                            },
                            series: [{radius: [20.'50%'].center: ['50%'.'30%'] {},radius: [30.'50%'].center: ['50%'.'70%']}]}}, {query: {
                            maxWidth: 500
                        },
                        option: {
                            legend: {
                                right: 10.top: '15%'.orient: 'vertical'
                            },
                            series: [{radius: [20.'50%'].center: ['50%'.'30%'] {},radius: [30.'50%'].center: ['50%'.'75%'[}]}}]}; myChart.setOption(option); });</script>
</body>
</html>
Copy the code

To set Media Query in option, follow the following format:

Option = {baseOption: {// Here is the basic "atomic option". title: {... }, legend: {... }, series: [{...}, {...}, ...] . }, media: [// this defines the media Query rule by rule. {query: {...}, // this defines the rule by rule. Option: {// this defines the rule by rule. {...},...}}, {query: {...}, / / the second rule. Option: {/ / the second rule corresponding option. Legend: {...},...}}, {/ / there is no written rules, this article says the "default", option: {/ / that all rules are not met, adopt this option. Legend: {...},...}}};Copy the code

In the above example, baseOption, media each option is an “atomic option”, that is, a common option with component and family definitions. The whole option composed of “atomic options” is called “compound options”. BaseOption is necessarily used, and when a query condition is met, the corresponding option is merged using chart.mergeOption().

query

Each query looks like this:

{
    minWidth: 200.maxHeight: 300.minAspectRatio: 1.3
}
Copy the code

Three properties are now supported: width, height, and aspectRatio. Each attribute can be prefixed with min or Max. For example, minWidth: 200 means “more than or equal to 200px width”. {minWidth: 200, maxHeight: 300} means “more than or equal to 200px width and less than or equal to 300px height”.

option

Since options in media are “atomic options”, they can theoretically write configuration items for any option. But generally we only write things that are related to layout positioning, such as intercepting some of the query options in the above example:

Media: [..., {query: {maxAspectRatio: 1 // When the aspect ratio is less than 1.}, option: {legend: {// Legend is placed in the bottom middle. 'center', bottom: 0, Orient: 'horizontal' // legend, series: [// radius: [20, '50%'], center: 0 ['50%', '30%'] }, { radius: [30, '50%'], center: ['50%', '70%'] } ] } }, { query: { maxWidth: 500 // When the container width is less than 500.}, option: {legend: {right: 10, // Legend is placed in the middle of the right. 'vertical' / / longitudinal layout.}, series: [/ / two pie charts and layout. {radius: [20, '50%'], center: [' 50% ', '30%']}, {radius: [30, '50%'], center: ['50%', '75%'] } ] } }, ... ]Copy the code

Priority when multiple queries are satisfied

Note that more than one query can be merged, defined by mergeOption, at the same time.

The default query

If a certain item in the media does not write query, it indicates the default value. That is, if all rules are not met, this option is adopted.

Precautions when container size changes in real time

In many cases, the container DOM nodes do not need to be arbitrarily sized by drag and drop, but simply set a few typical sizes for different terminals.

However, if container DOM nodes need to be able to vary in size with drag and drop, there is one thing that needs to be noted in current use: if a configuration item appears in one Query Option, it must also appear in other Query Options, otherwise it cannot revert to its original state. (left/right/top/bottom/width/height is not subject to this restriction.)

Media in Compound Option does not support Merge

That is, when the second (or third, fourth, fifth…) When chart.setoption (rawOption) is executed, if rawOption is a compound option, the new rawoption. media list does not merge with the old media list. It’s a simple substitution. Of course, rawOption.baseOption will still merge with the old option normally. In fact, there are very few scenarios that require multiple setoptions using “compound Options”. Instead, we recommend using “compound Options” for the first setOption and only “atomic Options” for subsequent setoptions using mediaQuery. That is, only setOption is used to change baseOption.

In the following example, we used jQuery to load external data. To do so, we need to import the jQuery library. This example is an example combined with a timeline:

<! DOCTYPEhtml>
<html>
<head>
    <meta charset="utf-8">
    <title>ECharts instance</title>
	<script src="https://cdn.staticfile.org/jquery/2.2.4/jquery.min.js"></script>
    <! Echarts.js -->
    <script src="https://cdn.staticfile.org/echarts/4.3.0/echarts.min.js"></script>
</head>
<body>
    <! -- Prepare a Dom with size (width and height) for ECharts
    <div id="main" style="width: 600px; height:400px;"></div>
    <script type="text/javascript">
        // Initializes the echarts instance based on the prepared DOM
        var myChart = echarts.init(document.getElementById('main'));
 
        $.when(
            $.getScript('https://www.sunjiaoshou.com/static/js/timelineGDP.js'),
            $.getScript('https://www.sunjiaoshou.com/static/js/draggable.js')
        ).done(function () {

            draggable.init(
                $('div[_echarts_instance_]') [0],
                myChart,
                {
                    width: 700.height: 630.lockY: true.throttle: 70}); myChart.hideLoading();var categoryData = [
                'Beijing'.'tianjin'.'hebei'.'the shanxi'.Inner Mongolia.'the liaoning'.'jilin'.'Heilongjiang'.'Shanghai'.'jiangsu'.'zhejiang'.'anhui'.'fujian'.'jiangxi'.'shandong'.'henan'.'hubei'.'in hunan province'.'in guangdong'.'the guangxi'.'hainan'.'chongqing'.'sichuan'.'guizhou'.'yunnan'.'Tibet'.'the shaanxi'.'gansu'.'the qinghai'.'the ningxia'.'the xinjiang'
            ];


            option = {
                baseOption: {
                    timeline: {
                        axisType: 'category'.autoPlay: true.playInterval: 1000.data: [
                            '2012-01-01'.'2013-01-01'.'2014-01-01'.'2015-01-01'.'2016-01-01'.'2017-01-01'.'2018-01-01'.'2019-01-01'.'2020-01-01'.'2021-01-01'].label: {
                            formatter : function(s) {
                                return (new Date(s)).getFullYear(); }}},title: {
                        subtext: 'Media Query example '
                    },
                    tooltip: {
                        trigger:'axis'.axisPointer: {
                            type: 'shadow'}},xAxis: {
                        type: 'value'.name: 'GDP (100 million Yuan) '.max: 30000.data: null
                    },
                    yAxis: {
                        type: 'category'.data: categoryData,
                        axisLabel: {interval: 0},
                        splitLine: {show: false}},legend: {
                        data: ['Primary industry'.'Secondary industry'.'Tertiary industry'.'GDP'.'financial'.Real estate].selected: {
                            'GDP': false.'financial': false.Real estate: false}},calculable : true.series: [{name: 'GDP'.type: 'bar'},
                        {name: 'financial'.type: 'bar'},
                        {name: Real estate.type: 'bar'},
                        {name: 'Primary industry'.type: 'bar'},
                        {name: 'Secondary industry'.type: 'bar'},
                        {name: 'Tertiary industry'.type: 'bar'},
                        {name: 'GDP'.type: 'pie'}},media: [{option: {
                            legend: {
                                orient: 'horizontal'.left: 'right'.itemGap: 10
                            },
                            grid: {
                                left: '10%'.top: 80.right: 90.bottom: 100
                            },
                            xAxis: {
                                nameLocation: 'end'.nameGap: 10.splitNumber: 5.splitLine: {
                                    show: true}},timeline: {
                                orient: 'horizontal'.inverse: false.left: '20%'.right: '20%'.bottom: 10.height: 40
                            },
                            series: [{name: 'GDP'.center: ['75%'.'30%'].radius: '28%'}]}}, {query: {maxWidth: 670.minWidth: 550},
                        option: {
                            legend: {
                                orient: 'horizontal'.left: 200.itemGap: 5
                            },
                            grid: {
                                left: '10%'.top: 80.right: 90.bottom: 100
                            },
                            xAxis: {
                                nameLocation: 'end'.nameGap: 10.splitNumber: 5.splitLine: {
                                    show: true}},timeline: {
                                orient: 'horizontal'.inverse: false.left: '20%'.right: '20%'.bottom: 10.height: 40
                            },
                            series: [{name: 'GDP'.center: ['75%'.'30%'].radius: '28%'}]}}, {query: {maxWidth: 550},
                        option: {
                            legend: {
                                orient: 'vertical'.left: 'right'.itemGap: 5
                            },
                            grid: {
                                left: 55.top: '32%'.right: 100.bottom: 50
                            },
                            xAxis: {
                                nameLocation: 'middle'.nameGap: 25.splitNumber: 3
                            },
                            timeline: {
                                orient: 'vertical'.inverse: true.right: 10.top: 150.bottom: 10.width: 55
                            },
                            series: [{name: 'GDP'.center: ['45%'.'20%'].radius: '28%'}]}}],options: [{title: {text: National Macroeconomic Indicators 2012},
                        series: [{data: dataMap.dataGDP['2012'] {},data: dataMap.dataFinancial['2012'] {},data: dataMap.dataEstate['2012'] {},data: dataMap.dataPI['2012'] {},data: dataMap.dataSI['2012'] {},data: dataMap.dataTI['2012'] {},data: [{name: 'Primary industry'.value: dataMap.dataPI['2012sum'] {},name: 'Secondary industry'.value: dataMap.dataSI['2012sum'] {},name: 'Tertiary industry'.value: dataMap.dataTI['2012sum'}]}]}, {title : {text: '2013 National Macroeconomic Indicators'},
                        series: [{data: dataMap.dataGDP['2013'] {},data: dataMap.dataFinancial['2013'] {},data: dataMap.dataEstate['2013'] {},data: dataMap.dataPI['2013'] {},data: dataMap.dataSI['2013'] {},data: dataMap.dataTI['2013'] {},data: [{name: 'Primary industry'.value: dataMap.dataPI['2013sum'] {},name: 'Secondary industry'.value: dataMap.dataSI['2013sum'] {},name: 'Tertiary industry'.value: dataMap.dataTI['2013sum'}]}]}, {title : {text: National Macroeconomic Indicators 2004},
                        series: [{data: dataMap.dataGDP['2004'] {},data: dataMap.dataFinancial['2004'] {},data: dataMap.dataEstate['2004'] {},data: dataMap.dataPI['2004'] {},data: dataMap.dataSI['2004'] {},data: dataMap.dataTI['2004'] {},data: [{name: 'Primary industry'.value: dataMap.dataPI['2004sum'] {},name: 'Secondary industry'.value: dataMap.dataSI['2004sum'] {},name: 'Tertiary industry'.value: dataMap.dataTI['2004sum'}]}]}, {title : {text: National Macroeconomic Indicators 2005},
                        series: [{data: dataMap.dataGDP['2005'] {},data: dataMap.dataFinancial['2005'] {},data: dataMap.dataEstate['2005'] {},data: dataMap.dataPI['2005'] {},data: dataMap.dataSI['2005'] {},data: dataMap.dataTI['2005'] {},data: [{name: 'Primary industry'.value: dataMap.dataPI['2005sum'] {},name: 'Secondary industry'.value: dataMap.dataSI['2005sum'] {},name: 'Tertiary industry'.value: dataMap.dataTI['2005sum'}]}]}, {title : {text: National Macroeconomic Indicators 2006},
                        series: [{data: dataMap.dataGDP['2006'] {},data: dataMap.dataFinancial['2006'] {},data: dataMap.dataEstate['2006'] {},data: dataMap.dataPI['2006'] {},data: dataMap.dataSI['2006'] {},data: dataMap.dataTI['2006'] {},data: [{name: 'Primary industry'.value: dataMap.dataPI['2006sum'] {},name: 'Secondary industry'.value: dataMap.dataSI['2006sum'] {},name: 'Tertiary industry'.value: dataMap.dataTI['2006sum'}]}]}, {title : {text: National Macroeconomic Indicators 2007},
                        series: [{data: dataMap.dataGDP['2007'] {},data: dataMap.dataFinancial['2007'] {},data: dataMap.dataEstate['2007'] {},data: dataMap.dataPI['2007'] {},data: dataMap.dataSI['2007'] {},data: dataMap.dataTI['2007'] {},data: [{name: 'Primary industry'.value: dataMap.dataPI['2007sum'] {},name: 'Secondary industry'.value: dataMap.dataSI['2007sum'] {},name: 'Tertiary industry'.value: dataMap.dataTI['2007sum'}]}]}, {title : {text: National Macroeconomic Indicators 2008},
                        series: [{data: dataMap.dataGDP['2008'] {},data: dataMap.dataFinancial['2008'] {},data: dataMap.dataEstate['2008'] {},data: dataMap.dataPI['2008'] {},data: dataMap.dataSI['2008'] {},data: dataMap.dataTI['2008'] {},data: [{name: 'Primary industry'.value: dataMap.dataPI['2008sum'] {},name: 'Secondary industry'.value: dataMap.dataSI['2008sum'] {},name: 'Tertiary industry'.value: dataMap.dataTI['2008sum'}]}]}, {title : {text: National Macroeconomic Indicators 2009},
                        series: [{data: dataMap.dataGDP['2009'] {},data: dataMap.dataFinancial['2009'] {},data: dataMap.dataEstate['2009'] {},data: dataMap.dataPI['2009'] {},data: dataMap.dataSI['2009'] {},data: dataMap.dataTI['2009'] {},data: [{name: 'Primary industry'.value: dataMap.dataPI['2009sum'] {},name: 'Secondary industry'.value: dataMap.dataSI['2009sum'] {},name: 'Tertiary industry'.value: dataMap.dataTI['2009sum'}]}]}, {title : {text: National Macroeconomic Indicators 2010},
                        series: [{data: dataMap.dataGDP['2010'] {},data: dataMap.dataFinancial['2010'] {},data: dataMap.dataEstate['2010'] {},data: dataMap.dataPI['2010'] {},data: dataMap.dataSI['2010'] {},data: dataMap.dataTI['2010'] {},data: [{name: 'Primary industry'.value: dataMap.dataPI['2010sum'] {},name: 'Secondary industry'.value: dataMap.dataSI['2010sum'] {},name: 'Tertiary industry'.value: dataMap.dataTI['2010sum'}]}]}, {title : {text: National Macroeconomic Indicators 2011},
                        series: [{data: dataMap.dataGDP['2011'] {},data: dataMap.dataFinancial['2011'] {},data: dataMap.dataEstate['2011'] {},data: dataMap.dataPI['2011'] {},data: dataMap.dataSI['2011'] {},data: dataMap.dataTI['2011'] {},data: [{name: 'Primary industry'.value: dataMap.dataPI['2011sum'] {},name: 'Secondary industry'.value: dataMap.dataSI['2011sum'] {},name: 'Tertiary industry'.value: dataMap.dataTI['2011sum'[}]}]}; myChart.setOption(option); });</script>
</body>
</html>
Copy the code

Visual mapping of ECharts data

Data visualization is simply to display data in the form of charts. The professional way of expression is the mapping process of data to visual elements.

Each ECharts chart has this mapping process built into it. The bar chart we learned earlier maps data to length.

In addition, ECharts provides a visualMap component to provide generic visual mappings. Visual elements that can be used in the visualMap component are:

  • Type of figure (Symbol)
  • symbolSize
  • Color
  • Opacity
  • Color transparency (colorAlpha)
  • colorLightness
  • colorSaturation
  • colorHue

Data and dimensions

Data in ECharts is generally stored in series. Data.

Different chart types have different data formats, but their common feature is the collection of data items. Each data item contains a value and additional information (optional). Each data value can be a single number (one-dimensional) or an array (multidimensional).

The most common form of series.data is a linear table, which is an ordinary array:

Series: {data: [{// each item here is the data item (dataItem) value: 2323, // This is the data item (value) itemStyle: {…}}, 1212, // can also be the value of the dataItem directly, which is more common. [{// dataItem value: [3434, 129, ‘SAN Marino ‘], // dataItem value: [3434, 129,’ SAN Marino ‘] {…}}, [1212, 5454, ‘Vatican ‘], // can also be directly the value of dataItem, which is more common. [4343, 23, ‘Tuvalu ‘] // The first dimension is mapped to the x axis, the second dimension to the y axis, and the third dimension to the bubble radius (symbolSize)]}

In charts, the first two dimensions of value are mapped by default. For example, the first dimension is mapped to the X axis and the second dimension to the Y axis. If you want to show more dimensions, you can use visualMap.

VisualMap components

The visualMap component defines the mapping of specified dimensions of data to corresponding visual elements.

The visualMap component can define more than one to visually map multiple dimensions in the data simultaneously.

A visualMap component can be defined as either visualMap piecewise or visualMap continuous, distinguished by type. Such as:

Option = {visualMap: [{// first visualMap component type: Piecewise: piecewise: piecewise: piecewise: piecewise: Piecewise: Piecewise: Piecewise: Piecewise: Piecewise: Piecewise };

Segmented visual mapping component, with three modes:

  • Continuous data average segmentation: Automatic average segmentation into several pieces according to visualMap- Piecewise. splitNumber.
  • Continuous data custom piecing: The block scope is defined according to visualMap- Piecewise. pieces.
  • Discrete data is segmented according to categories: categories are defined in VisualMap-Piecewise.categories.

Segmented visual mapping component, shown in the following figure:

Example:

<! DOCTYPEhtml>
<html style="height: 100%">
   <head>
       <meta charset="utf-8">
   </head>
   <body style="height: 100%; margin: 0">
       <div id="container" style="height: 100%"></div>
       <script type="text/javascript" src="https://cdn.jsdelivr.net/npm/echarts/dist/echarts.min.js"></script>
       <script type="text/javascript" src="https://cdn.jsdelivr.net/npm/echarts-gl/dist/echarts-gl.min.js"></script>
       <script type="text/javascript" src="https://cdn.jsdelivr.net/npm/echarts-stat/dist/ecStat.min.js"></script>
       <script type="text/javascript" src="https://cdn.jsdelivr.net/npm/echarts/dist/extension/dataTool.min.js"></script>
       <script type="text/javascript" src="https://cdn.jsdelivr.net/npm/echarts/map/js/china.js"></script>
       <script type="text/javascript" src="https://cdn.jsdelivr.net/npm/echarts/map/js/world.js"></script>
       <script type="text/javascript" src="https://cdn.jsdelivr.net/npm/echarts/dist/extension/bmap.min.js"></script>
       <script type="text/javascript">
var dom = document.getElementById("container");
var myChart = echarts.init(dom);
var app = {};
option = null;
var geoCoordMap = {
    "Haimen": [121.15.31.89].ordos: [109.781327.39.608266]."Zhaoyuan": [120.38.37.35]."Zhoushan": [122.207216.29.985295].qiqihar: [123.97.47.33]."Yancheng": [120.13.33.38]."Chifeng": [118.87.42.28]."Qingdao": [120.33.36.07]."Rushan mountain": [121.52.36.89]."Jinchang": [102.188043.38.520089]."Quanzhou": [118.58.24.93]."Lacy": [120.53.36.86]."Sunshine": [119.46.35.42]."Jiaonan": [119.97.35.88]."Nantong": [121.05.32.08]."Lhasa": [91.11.29.97]."Yun fu": [112.02.22.93]."Meizhou": [116.1.24.55]."-": [122.05.37.2]."Shanghai": [121.48.31.22]."Panzhihua": [101.718637.26.582347].Weihai "": [122.1.37.5]."Chengde": [117.93.40.97]."Xiamen": [118.1.24.46]."Shanwei": [115.375279.22.786211]."Chaozhou": [116.63.23.68]."丹东": [124.37.40.13]."Taicang": [121.1.31.45]."Qujing": [103.79.25.51]."Yantai": [121.39.37.52]."Fuzhou": [119.3.26.08].wafangdian: [121.979603.39.627114]."Cieme": [120.45.36.38]."Fushun": [123.97.41.97]."Yuxi": [102.52.24.35].zhangjiakou: [114.87.40.82]."Yangquan": [113.57.37.85].Laizhou "": [119.942327.37.177017]."Lake": [120.1.30.86]."Shantou": [116.69.23.39]."Kunshan": [120.95.31.39]."Ningbo": [121.56.29.86]."Zhanjiang": [110.359377.21.270708].Jieyang "": [116.35.23.55]."Rongcheng city": [122.41.37.16].lianyungang: [119.16.34.59].hulusao: [120.836932.40.711052]."Changshu": [120.74.31.64]."Dongguan": [113.75.23.04]."Hope": [114.68.23.73].Huaian "": [119.15.33.5]."Taizhou": [119.9.32.49]."Nanning": [108.33.22.84].Yingkou "": [122.18.40.65]."Huizhou": [114.4.23.09]."Jiang Yin": [120.26.31.91]."Penglai": [120.75.37.8]."Shaoguan": [113.62.24.84].Jiayuguan pass: [98.289152.39.77313]."Guangzhou": [113.23.23.16]."Yan": [109.47.36.6]."Taiyuan": [112.53.37.87]."Qingyuan": [113.01.23.7]."Sun": [113.38.22.52]."Kunming": [102.73.25.04]."Shouguang": [118.73.36.86]."File": [122.070714.41.119997]."Changzhi": [113.08.36.18]."Shenzhen": [114.07.22.62]."Zhuhai": [113.52.22.3]."Suqian": [118.3.33.96]."Xianyang": [108.72.34.36]."Tongchuan": [109.11.35.09]."Pingdu": [119.97.36.77]."Foshan": [113.11.23.05]."Haikou": [110.35.20.02]."Jiangmen": [113.06.22.61]."Chapter grave": [117.53.36.72]."Zhaoqing": [112.44.23.05]."Dalian": [121.62.38.92]."Linfen": [111.5.36.08]."Wu jiang": [120.63.31.16]."Shizuishan": [106.39.39.04]."Shenyang": [123.38.41.8]."Suzhou": [120.62.31.32]."Maoming": [110.88.21.68]."Jiaxing": [120.76.30.77]."Changchun": [125.35.43.88]."Jiaozhou": [120.03336.36.264622]."Yinchuan": [106.27.38.47]."Zhangjiagang": [120.555821.31.875428]."Sanmenxia": [111.19.34.76]."Jinzhou": [121.15.41.13]."Nanchang": [115.89.28.68]."Liuzhou": [109.4.24.33]."Sanya": [109.511909.18.252847]."The city": [104.778442.29.33903]."Jilin": [126.57.43.87]."Yangjiang": [111.95.21.85]."Luzhou": [105.39.28.91]."Xining": [101.74.36.56]."Yibin": [104.56.29.77]."Hohhot": [111.65.40.82]."Chengdu": [104.06.30.67]."Datong": [113.3.40.12]."Zhenjiang": [119.44.32.2]."Guilin": [110.28.25.29]."Zhangjiajie": [110.479191.29.117096]."Yixing": [119.82.31.36]."North sea": [109.12.21.49]."Xi 'an": [108.95.34.27]."Tan": [119.56.31.74].Dongying "": [118.49.37.46]."Mudanjiang": [129.58.44.6]."Zunyi": [106.9.27.7]."Shaoxing": [120.58.30.01]."Yangzhou": [119.42.32.39]."Changzhou": [119.95.31.79]."Weifang": [119.1.36.62]."Chongqing": [106.54.29.59]."Taizhou": [121.420757.28.656386]."Nanjing": [118.78.32.04].Binzhou "": [118.03.37.36]."Guiyang": [106.71.26.57]."Wuxi": [120.29.31.59]."Benxi": [123.73.41.3]."Karamay": [84.77.45.59]."Weinan": [109.5.34.52].Ma on Shan: [118.48.31.56]."Baoji": [107.15.34.38]."Coke": [113.21.35.24]."Jurong": [119.16.31.95]."Beijing": [116.46.39.92]."Xuzhou": [117.2.34.26]."Hengshui": [115.72.37.72]."Baotou": [110.40.58]."City": [104.73.31.48]."Urumchi": [87.68.43.77].Zaozhuang "": [117.57.34.86]."Hangzhou": [120.19.30.26]."Zibo": [118.05.36.78]."Anshan": [122.85.41.12]."Liyang": [119.48.31.43].korla: [86.06.41.68].Anyang "": [114.35.36.1]."Kaifeng": [114.35.34.79]."Jinan": [117.36.65].Deyang "": [104.37.31.13]."Wenzhou": [120.65.28.01]."Jiujiang": [115.97.29.71]."Handan": [114.47.36.6]."Lin": [119.72.30.23]."Lanzhou": [103.73.36.03].Cangzhou "": [116.83.38.33]."Linyi": [118.35.35.05]."Nanchong": [106.110698.30.837793]."Tianjin": [117.2.39.13]."Fuyang": [119.95.30.07]."Taian": [117.13.36.18]."Zhuji": [120.23.29.71]."Zhengzhou": [113.65.34.76]."Harbin": [126.63.45.75]."Liaocheng": [115.97.36.45]."Wuhu": [118.38.31.33]."Tangshan": [118.02.39.63]."Mesa": [113.29.33.75]."Xingtai": [114.48.37.05]."Texas": [116.29.37.45]."The jining": [116.59.35.38]."Jing zhou": [112.239741.30.335165]."Yichang": [111.3.30.7]."Yiwu": [120.06.29.32]."Lishui": [119.92.28.45]."Luoyang": [112.44.34.7].qinhuangdao: [119.57.39.95]."Zhuzhou": [113.16.27.83]."Shijiazhuang": [114.48.38.03]."Laiwu": [117.67.36.19]."Changde": [111.69.29.05]."Baoding": [115.48.38.85]."Xiangtan": [112.91.27.87]."Jinhua": [119.64.29.12]."Yueyang": [113.09.29.37]."Changsha": [113.28.21]."Quzhou": [118.88.28.97]."Langfang": [116.7.39.53]."Heze": [115.480656.35.23375].Hefei "": [117.27.31.86]."Wuhan": [114.31.30.52]."Daqing": [125.03.46.58]};var convertData = function (data) {
    var res = [];
    for (var i = 0; i < data.length; i++) {
        var geoCoord = geoCoordMap[data[i].name];
        if(geoCoord) { res.push(geoCoord.concat(data[i].value)); }}return res;
};

option = {
    backgroundColor: '#404a59'.title: {
        text: Air Quality in Major Cities of China.subtext: 'data from PM25.in'.sublink: 'http://www.pm25.in'.left: 'center'.textStyle: {
            color: '#fff'}},tooltip: {
        trigger: 'item'
    },
    legend: {
        orient: 'vertical'.top: 'bottom'.left: 'right'.data: ['pm2.5'].textStyle: {
            color: '#fff'}},visualMap: {
        min: 0.max: 300.splitNumber: 5.color: ['#d94e5d'.'#eac736'.'#50a3ba'].textStyle: {
            color: '#fff'}},geo: {
        map: 'china'.label: {
            emphasis: {
                show: false}},itemStyle: {
            normal: {
                areaColor: '#323c48'.borderColor: '# 111'
            },
            emphasis: {
                areaColor: '#2a333d'}}},series: [{name: 'pm2.5'.type: 'scatter'.coordinateSystem: 'geo'.data: convertData([
                {name: "Haimen".value: 9},
                {name: ordos.value: 12},
                {name: "Zhaoyuan".value: 12},
                {name: "Zhoushan".value: 12},
                {name: qiqihar.value: 14},
                {name: "Yancheng".value: 15},
                {name: "Chifeng".value: 16},
                {name: "Qingdao".value: 18},
                {name: "Rushan mountain".value: 18},
                {name: "Jinchang".value: 19},
                {name: "Quanzhou".value: 21},
                {name: "Lacy".value: 21},
                {name: "Sunshine".value: 21},
                {name: "Jiaonan".value: 22},
                {name: "Nantong".value: 23},
                {name: "Lhasa".value: 24},
                {name: "Yun fu".value: 24},
                {name: "Meizhou".value: 25},
                {name: "-".value: 25},
                {name: "Shanghai".value: 25},
                {name: "Panzhihua".value: 25},
                {name: Weihai "".value: 25},
                {name: "Chengde".value: 25},
                {name: "Xiamen".value: 26},
                {name: "Shanwei".value: 26},
                {name: "Chaozhou".value: 26},
                {name: "丹东".value: 27},
                {name: "Taicang".value: 27},
                {name: "Qujing".value: 27},
                {name: "Yantai".value: 28},
                {name: "Fuzhou".value: 29},
                {name: wafangdian.value: 30},
                {name: "Cieme".value: 30},
                {name: "Fushun".value: 31},
                {name: "Yuxi".value: 31},
                {name: zhangjiakou.value: 31},
                {name: "Yangquan".value: 31},
                {name: Laizhou "".value: 32},
                {name: "Lake".value: 32},
                {name: "Shantou".value: 32},
                {name: "Kunshan".value: 33},
                {name: "Ningbo".value: 33},
                {name: "Zhanjiang".value: 33},
                {name: Jieyang "".value: 34},
                {name: "Rongcheng city".value: 34},
                {name: lianyungang.value: 35},
                {name: hulusao.value: 35},
                {name: "Changshu".value: 36},
                {name: "Dongguan".value: 36},
                {name: "Hope".value: 36},
                {name: Huaian "".value: 36},
                {name: "Taizhou".value: 36},
                {name: "Nanning".value: 37},
                {name: Yingkou "".value: 37},
                {name: "Huizhou".value: 37},
                {name: "Jiang Yin".value: 37},
                {name: "Penglai".value: 37},
                {name: "Shaoguan".value: 38},
                {name: Jiayuguan pass.value: 38},
                {name: "Guangzhou".value: 38},
                {name: "Yan".value: 38},
                {name: "Taiyuan".value: 39},
                {name: "Qingyuan".value: 39},
                {name: "Sun".value: 39},
                {name: "Kunming".value: 39},
                {name: "Shouguang".value: 40},
                {name: "File".value: 40},
                {name: "Changzhi".value: 41},
                {name: "Shenzhen".value: 41},
                {name: "Zhuhai".value: 42},
                {name: "Suqian".value: 43},
                {name: "Xianyang".value: 43},
                {name: "Tongchuan".value: 44},
                {name: "Pingdu".value: 44},
                {name: "Foshan".value: 44},
                {name: "Haikou".value: 44},
                {name: "Jiangmen".value: 45},
                {name: "Chapter grave".value: 45},
                {name: "Zhaoqing".value: 46},
                {name: "Dalian".value: 47},
                {name: "Linfen".value: 47},
                {name: "Wu jiang".value: 47},
                {name: "Shizuishan".value: 49},
                {name: "Shenyang".value: 50},
                {name: "Suzhou".value: 50},
                {name: "Maoming".value: 50},
                {name: "Jiaxing".value: 51},
                {name: "Changchun".value: 51},
                {name: "Jiaozhou".value: 52},
                {name: "Yinchuan".value: 52},
                {name: "Zhangjiagang".value: 52},
                {name: "Sanmenxia".value: 53},
                {name: "Jinzhou".value: 54},
                {name: "Nanchang".value: 54},
                {name: "Liuzhou".value: 54},
                {name: "Sanya".value: 54},
                {name: "The city".value: 56},
                {name: "Jilin".value: 56},
                {name: "Yangjiang".value: 57},
                {name: "Luzhou".value: 57},
                {name: "Xining".value: 57},
                {name: "Yibin".value: 58},
                {name: "Hohhot".value: 58},
                {name: "Chengdu".value: 58},
                {name: "Datong".value: 58},
                {name: "Zhenjiang".value: 59},
                {name: "Guilin".value: 59},
                {name: "Zhangjiajie".value: 59},
                {name: "Yixing".value: 59},
                {name: "North sea".value: 60},
                {name: "Xi 'an".value: 61},
                {name: "Tan".value: 62},
                {name: Dongying "".value: 62},
                {name: "Mudanjiang".value: 63},
                {name: "Zunyi".value: 63},
                {name: "Shaoxing".value: 63},
                {name: "Yangzhou".value: 64},
                {name: "Changzhou".value: 64},
                {name: "Weifang".value: 65},
                {name: "Chongqing".value: 66},
                {name: "Taizhou".value: 67},
                {name: "Nanjing".value: 67},
                {name: Binzhou "".value: 70},
                {name: "Guiyang".value: 71},
                {name: "Wuxi".value: 71},
                {name: "Benxi".value: 71},
                {name: "Karamay".value: 72},
                {name: "Weinan".value: 72},
                {name: Ma on Shan.value: 72},
                {name: "Baoji".value: 72},
                {name: "Coke".value: 75},
                {name: "Jurong".value: 75},
                {name: "Beijing".value: 79},
                {name: "Xuzhou".value: 79},
                {name: "Hengshui".value: 80},
                {name: "Baotou".value: 80},
                {name: "City".value: 80},
                {name: "Urumchi".value: 84},
                {name: Zaozhuang "".value: 84},
                {name: "Hangzhou".value: 84},
                {name: "Zibo".value: 85},
                {name: "Anshan".value: 86},
                {name: "Liyang".value: 86},
                {name: korla.value: 86},
                {name: Anyang "".value: 90},
                {name: "Kaifeng".value: 90},
                {name: "Jinan".value: 92},
                {name: Deyang "".value: 93},
                {name: "Wenzhou".value: 95},
                {name: "Jiujiang".value: 96},
                {name: "Handan".value: 98},
                {name: "Lin".value: 99},
                {name: "Lanzhou".value: 99},
                {name: Cangzhou "".value: 100},
                {name: "Linyi".value: 103},
                {name: "Nanchong".value: 104},
                {name: "Tianjin".value: 105},
                {name: "Fuyang".value: 106},
                {name: "Taian".value: 112},
                {name: "Zhuji".value: 112},
                {name: "Zhengzhou".value: 113},
                {name: "Harbin".value: 114},
                {name: "Liaocheng".value: 116},
                {name: "Wuhu".value: 117},
                {name: "Tangshan".value: 119},
                {name: "Mesa".value: 119},
                {name: "Xingtai".value: 119},
                {name: "Texas".value: 120},
                {name: "The jining".value: 120},
                {name: "Jing zhou".value: 127},
                {name: "Yichang".value: 130},
                {name: "Yiwu".value: 132},
                {name: "Lishui".value: 133},
                {name: "Luoyang".value: 134},
                {name: qinhuangdao.value: 136},
                {name: "Zhuzhou".value: 143},
                {name: "Shijiazhuang".value: 147},
                {name: "Laiwu".value: 148},
                {name: "Changde".value: 152},
                {name: "Baoding".value: 153},
                {name: "Xiangtan".value: 154},
                {name: "Jinhua".value: 157},
                {name: "Yueyang".value: 169},
                {name: "Changsha".value: 175},
                {name: "Quzhou".value: 177},
                {name: "Langfang".value: 193},
                {name: "Heze".value: 194},
                {name: Hefei "".value: 229},
                {name: "Wuhan".value: 273},
                {name: "Daqing".value: 279}]),symbolSize: 12.label: {
                normal: {
                    show: false
                },
                emphasis: {
                    show: false}},itemStyle: {
                emphasis: {
                    borderColor: '#fff'.borderWidth: 1}}}]};if (option && typeof option === "object") {
    myChart.setOption(option, true);
}
       </script>
   </body>
</html>
Copy the code

Configuration of visual mapping mode

In visualMap, you can specify that specified dimensions of data are mapped to corresponding visual elements.

 

option = {
    visualMap: [{type: 'piecewise'
            min: 0.max: 5000.dimension: 3.// the fourth dimension of series.data (value[3]) is mapped
            seriesIndex: 4.// Map the fourth series.
            inRange: {          // Select the visual configuration in the range
                color: ['blue'.'# 121122'.'red'].// Defines the list of colors for the graph color map,
                                                    // Data min mapped to 'blue',
                                                    // Max mapped to 'red',
                                                    // Other automatic linear calculation.
                symbolSize: [30.100]               // Define the mapping range of the graph size,
                                                    // The data minimum is mapped to 30,
                                                    // The maximum value maps to 100,
                                                    // Other automatic linear calculation.
            },
            outOfRange: {       // Select visual configuration out of range
                symbolSize: [30.100]}},... ] };Copy the code
option = {
    visualMap: [{...inRange: {          // Select the visual configuration in the range
                colorLightness: [0.2.1].// map to shade. That is, the original color of light and shade processing.
                                          // The original color may be selected from the global palette and the visualMap component does not care.
                symbolSize: [30.100]},... },... ] };Copy the code

ECharts event processing

In ECharts we can call the corresponding function back and forth by listening for user actions.

ECharts uses the ON method to listen for user behavior, such as clicks.

There are two types of events in ECharts:

User mouse clicks such as ‘click’, ‘dblclick’, ‘mousedown’, ‘Mousemove’, ‘mouseup’, ‘mouseover’, ‘mouseout’, ‘GlobalOut’, ‘ContextMenu’ events.

There are also behavioral events that are triggered when the user uses an interactive component, such as the ‘LegendselectChanged’ event when the legend switch is switched, the ‘Datazoom’ event when the data area is scaled, etc.

myChart.on('click'.function (params) {
    // The console prints the name of the data after the user clicks
    console.log(params);
});

myChart.on('legendselectchanged'.function (params) {
    console.log(params);
});

chart.on('click'.'series.line'.function (params) {
    console.log(params);
});

chart.on('mouseover', {seriesIndex: 1.name: 'xx'}, function (params) {
    console.log(params);
});
Copy the code

Mouse events

Mouse event types supported by ECharts, Includes ‘click’, ‘dblclick’, ‘mousedown’, ‘Mousemove’, ‘mouseup’, ‘mouseover’, ‘mouseout’, ‘GlobalOut’, ‘ContextMenu’ events.

In the following example, a dialog box pops up when clicking on a bar chart:

<! DOCTYPEhtml>
<html>
<head>
    <meta charset="utf-8">
    <title>ECharts instance</title>
    <! Echarts.js -->
    <script src="https://cdn.staticfile.org/echarts/4.3.0/echarts.min.js"></script>
</head>
<body>
    <! -- Prepare a Dom with size (width and height) for ECharts
    <div id="main" style="width: 600px; height:400px;"></div>
    <script type="text/javascript">
        // Initializes the ECharts instance based on the prepared DOM
        var myChart = echarts.init(document.getElementById('main'));

        // Specify the chart configuration items and data
        var option = {
            xAxis: {
                data: ["Shirt"."Cardigan"."Chiffon shirt."."Pants"."High heels"."Socks"]},yAxis: {},
            series: [{
                name: 'sales'.type: 'bar'.data: [5.20.36.10.10.20]]}};// Display the chart using the configuration items and data you just specified.
        myChart.setOption(option);
        // Handle the click event and pop up the data name
        myChart.on('click'.function (params) {
            alert(params.name);
        });
    </script>
</body>
</html>
Copy the code

All mouse events contain the parameter Params, which is an object containing data information about the click graph in the following format:

{// The name of the component to which the currently clicked graphic element belongs, // values such as 'series', 'markLine', 'markPoint', 'timeLine', etc. ComponentType: String, // Series type. The values can be: 'line', 'bar', 'pie', etc. Makes sense when componentType is 'series'. SeriesType: string, // Series index in the passed option.series. Makes sense when componentType is 'series'. SeriesIndex: number, // Series name. Makes sense when componentType is 'series'. SeriesName: string, // dataIndex: number, // dataIndex: number Object, // Graphs such as SANkey and graph contain both nodeData and edgeData. // dataType can be 'node' or 'edge', indicating whether the current click is on node or edge. // Most other charts have only one type of data, dataType is meaningless. DataType: string, / / the incoming data value: number | Array/color/data graphics. Makes sense when componentType is 'series'. color: string }Copy the code

How to tell where the mouse clicked:

myChart.on('click', Function (params) {if (params.ponentType === 'markPoint') {// If (params.seriesIndex === 5) {// Click on markPoint for series with index 5. } } else if (params.componentType === 'series') { if (params.seriesType === 'graph') { if (params.dataType === 'edge') { // Click on the edge of the graph. } else {// Click on the graph's node. }}}});Copy the code

Use query to trigger the callback only on the graphic elements of the specified component:

chart.on(eventName, query, handler);
Copy the code

Query can be a string or an Object.

String indicates the component type. The format can be ‘mainType’ or ‘mainType.subtype’. Such as:

chart.on('click', 'series', function () {... }); chart.on('click', 'series.line', function () {... }); chart.on('click', 'dataZoom', function () {... }); chart.on('click', 'xAxis.category', function () {... });Copy the code

If Object, it can contain one or more of the following properties, each of which is optional:

chart.setOption({ // ... series: { // ... type: 'custom', renderItem: function (params, api) { return { type: 'group', children: [{ type: 'circle', name: 'my_el', // ... }, { // ... }] } }, data: [[12, 33]] } }) chart.on('mouseup', {element: 'my_el'}, function () {// this method is called back when elements whose name is 'my_el' are 'mouseup'. });Copy the code

Code triggers the behavior of components in ECharts

Above we have only described user interactions, but sometimes we need to call methods in an application that trigger the behavior of the diagram, such as displaying tooltips.

ECharts dispatchAction({type: “}) is used to trigger chart actions, manage all actions uniformly, and record user action paths as needed.

The above example is used for the tooltip in the wheel pie chart:

<! DOCTYPEhtml>
<html>
<head>
    <meta charset="utf-8">
    <title>ECharts instance</title>
    <! Echarts.js -->
    <script src="https://cdn.staticfile.org/echarts/4.3.0/echarts.min.js"></script>
</head>
<body>
    <! -- Prepare a Dom with size (width and height) for ECharts
    <div id="main"  style="height: 100%; min-height:400px;"></div>
    <script type="text/javascript">
        // Initializes the ECharts instance based on the prepared DOM
        var myChart = echarts.init(document.getElementById('main'));
        var app = {};
        option = null;
        // Specify the chart configuration items and data
        var option = {
            title : {
                text: 'Pie chart program Call Highlight Example'.x: 'center'
            },
            tooltip: {
                trigger: 'item'.formatter: "{a} <br/>{b} : {c} ({d}%)"
            },
            legend: {
                orient: 'vertical'.left: 'left'.data: ['Direct access'.'Email marketing'.'Affiliate advertising'.'Video advertising'.'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 advertising'},
                        {value:135.name:'Video advertising'},
                        {value:1548.name:'Search engines'}].itemStyle: {
                        emphasis: {
                            shadowBlur: 10.shadowOffsetX: 0.shadowColor: 'rgba (0, 0, 0, 0.5)'}}}]}; app.currentIndex = -1;

        setInterval(function () {
            var dataLen = option.series[0].data.length;
            // Unhighlight the previously highlighted graphic
            myChart.dispatchAction({
                type: 'downplay'.seriesIndex: 0.dataIndex: app.currentIndex
            });
            app.currentIndex = (app.currentIndex + 1) % dataLen;
            // Highlight the current graphic
            myChart.dispatchAction({
                type: 'highlight'.seriesIndex: 0.dataIndex: app.currentIndex
            });
            / / display the tooltip
            myChart.dispatchAction({
                type: 'showTip'.seriesIndex: 0.dataIndex: app.currentIndex
            });
        }, 1000);
        if (option && typeof option === "object") {
            myChart.setOption(option, true);
        }
    </script>
</body>
</html>
Copy the code

Effect:

ECharts sun figure

Sunburst is composed of multi-layer ring graphs. In data structure, the inner ring is the parent node of the outer ring. Therefore, it can not only show the proportion of local and whole like a pie chart, but also show the hierarchy like a rectangular tree chart.

ECharts can create a sunrise diagram simply by declaring the type as SunBurst in the Series configuration item and the data structure as a tree structure. Here is a simple example:

<! DOCTYPEhtml>
<html>
<head>
    <meta charset="utf-8">
    <title>ECharts instance</title>
    <! Echarts.js -->
    <script src="https://cdn.staticfile.org/echarts/4.3.0/echarts.min.js"></script>
</head>
<body>
    <! -- Prepare a Dom with size (width and height) for ECharts
    <div id="main" style="width: 600px; height:400px;"></div>
    <script type="text/javascript">
        // Initializes the echarts instance based on the prepared DOM
        var myChart = echarts.init(document.getElementById('main'));
 
        // Specify the chart configuration items and data
        var option = {
            series: {
                type: 'sunburst'.data: [{
                    name: 'A'.value: 10.children: [{
                        value: 3.name: 'Aa'
                    }, {
                        value: 5.name: 'Ab'}]}, {name: 'B'.children: [{
                        name: 'Ba'.value: 4
                    }, {
                        name: 'Bb'.value: 2}]}, {name: 'C'.value: 3}}};// Display the chart using the configuration items and data you just specified.
        myChart.setOption(option);
    </script>
</body>
</html>
Copy the code

Effect:

Color and other style adjustments

By default, the global palette color is used to assign the innermost layer of color, and the rest of the layer is the same color as its parent element.

In the rising sun image, the color of the sector can be set in the following three ways:

  • Set the style of each pie block in series.data.itemStyle.
  • Set the style for each layer in series. Levels. ItemStyle.
  • Set the style for the entire sunrise image in series. ItemStyle.

The priority of the above three items is from highest to lowest, that is, a sector block configured with series.data.itemStyle will override the setting of series.levels.itemStyle and series.itemStyle.

Next, we will set the color of the whole as gray # AAA, the color of the innermost layer as blue blue, and the two pieces Aa and B as red red.

<! DOCTYPEhtml>
<html>
<head>
    <meta charset="utf-8">
    <title>ECharts instance</title>
    <! Echarts.js -->
    <script src="https://cdn.staticfile.org/echarts/4.3.0/echarts.min.js"></script>
</head>
<body>
    <! -- Prepare a Dom with size (width and height) for ECharts
    <div id="main" style="width: 600px; height:400px;"></div>
    <script type="text/javascript">
        // Initializes the echarts instance based on the prepared DOM
        var myChart = echarts.init(document.getElementById('main'));
 
        // Specify the chart configuration items and data
        var option = {
            series: {
                type: 'sunburst'.data: [{
                    name: 'A'.value: 10.children: [{
                        value: 3.name: 'Aa'.itemStyle: {
                            color: 'red'}}, {value: 5.name: 'Ab'}]}, {name: 'B'.children: [{
                        name: 'Ba'.value: 4
                    }, {
                        name: 'Bb'.value: 2}].itemStyle: {
                        color: 'red'}}, {name: 'C'.value: 3}].itemStyle: {
                    color: '#aaa'
                },
                levels: [{
                    // Node attributes left for data driller
                }, {
                    itemStyle: {
                        color: 'blue'}}}};// Display the chart using the configuration items and data you just specified.
        myChart.setOption(option);
    </script>
</body>
</html>
Copy the code

Layer-by-layer styling is a common feature that can greatly improve configuration efficiency.

Data drill-down

By default, the rising Sun map supports data driller, which means that when a fan block is clicked, the data of the fan block is used as the root node to further display the details of the data.

After the data drapers down, a pattern appears in the middle of the graph to return to the previous level, and the pattern can be configured with levels[0].

<! DOCTYPEhtml>
<html>
<head>
    <meta charset="utf-8">
    <title>ECharts instance</title>
    <! Echarts.js -->
    <script src="https://cdn.staticfile.org/echarts/4.3.0/echarts.min.js"></script>
</head>
<body>
    <! -- Prepare a Dom with size (width and height) for ECharts
    <div id="main" style="width: 600px; height:400px;"></div>
    <script type="text/javascript">
        // Initializes the echarts instance based on the prepared DOM
        var myChart = echarts.init(document.getElementById('main'));
 
        var data = [{
            name: 'Grandpa'.children: [{
                name: 'Uncle Leo'.value: 15.children: [{
                    name: 'Cousin Jack'.value: 2
                }, {
                    name: 'Cousin Mary'.value: 5.children: [{
                        name: 'Jackson'.value: 2}]}, {name: 'Cousin Ben'.value: 4}]}, {name: 'Father'.value: 10.children: [{
                    name: 'Me'.value: 5
                }, {
                    name: 'Brother Peter'.value: 1}}]]}, {name: 'Nancy'.children: [{
                name: 'Uncle Nike'.children: [{
                    name: 'Cousin Betty'.value: 1
                }, {
                    name: 'Cousin Jenny'.value: 2}}}]]]; option = {series: {
                type: 'sunburst'.// highlightPolicy: 'ancestor',
                data: data,
                radius: [0.'90%'].label: {
                    rotate: 'radial'}}};// Display the chart using the configuration items and data you just specified.
        myChart.setOption(option);
    </script>
</body>
</html>
Copy the code

If data driller is not required, it can be turned off by setting nodeClick to false or ‘link’ and data.link to the link opened by clicking on the fan block.

Highlight related sector blocks

When the mouse moves over a sector block, you can highlight related data blocks by setting a highlightPolicy. The following methods can be used to highlight data blocks:

  • ‘Descendant’ (default) : Highlight the scallop in which the mouse moves and its descendant elements;
  • ‘ancestor’ : Highlight the fan block where the mouse is and its ancestor element;
  • ‘self’ : highlight only the sector where the mouse is;
  • ‘None’ : Does not downplay other elements.

The “highlight” mentioned above uses the emphasis style for the sector over which the mouse is located; For other related sector blocks, the Highlight style is used. In this way, you can easily implement the need to highlight relevant data.

Specifically, for configuration items:

itemStyle: {
    color: 'yellow',
    borderWidth: 2,
    emphasis: {
        color: 'red'
    },
    highlight: {
        color: 'orange'
    },
    downplay: {
        color: '#ccc'
    }
}
Copy the code

‘descendant highlightPolicy to:

<! DOCTYPEhtml>
<html>
<head>
    <meta charset="utf-8">
    <title>ECharts instance</title>
    <! Echarts.js -->
    <script src="https://cdn.staticfile.org/echarts/4.3.0/echarts.min.js"></script>
</head>
<body>
    <! -- Prepare a Dom with size (width and height) for ECharts
    <div id="main" style="width: 600px; height:400px;"></div>
    <script type="text/javascript">
        // Initializes the echarts instance based on the prepared DOM
        var myChart = echarts.init(document.getElementById('main'));
 
        option = {
            silent: true.series: {
                radius: ['15%'.'95%'].center: ['50%'.'60%'].type: 'sunburst'.sort: null.highlightPolicy: 'descendant'.data: [{
                    value: 10.children: [{
                        name: 'target'.value: 4.children: [{
                            value: 2.children: [{
                                value: 1}]}, {value: 1
                        }, {
                            value: 0.5}]}, {value: 2}]}, {value: 4.children: [{
                        children: [{
                            value: 2}}}]]].label: {
                    normal: {
                        rotate: 'none'.color: '#fff'}},levels: [].itemStyle: {
                    color: 'yellow'.borderWidth: 2
                },
                emphasis: {
                    itemStyle: {
                        color: 'red'}},highlight: {
                    itemStyle: {
                        color: 'orange'}},downplay: {
                    itemStyle: {
                        color: '#ccc'}}}};setTimeout(function () {
            myChart.dispatchAction({
                type: 'sunburstHighlight'.targetNodeId: 'target'
            });
        });
 
        // Display the chart using the configuration items and data you just specified.
        myChart.setOption(option);
    </script>
</body>
</html>
Copy the code

‘ancestor highlightPolicy to:

<! DOCTYPEhtml>
<html>
<head>
    <meta charset="utf-8">
    <title>ECharts instance</title>
    <! Echarts.js -->
    <script src="https://cdn.staticfile.org/echarts/4.3.0/echarts.min.js"></script>
</head>
<body>
    <! -- Prepare a Dom with size (width and height) for ECharts
    <div id="main" style="width: 600px; height:400px;"></div>
    <script type="text/javascript">
        // Initializes the echarts instance based on the prepared DOM
        var myChart = echarts.init(document.getElementById('main'));
 
        option = {
            silent: true.series: {
                radius: ['15%'.'95%'].center: ['50%'.'60%'].type: 'sunburst'.sort: null.highlightPolicy: 'ancestor'.data: [{
                    value: 10.children: [{
                        value: 4.children: [{
                            value: 2.children: [{
                                name: 'target'.value: 1}]}, {value: 1
                        }, {
                            value: 0.5}]}, {value: 2}]}, {value: 4.children: [{
                        children: [{
                            value: 2}}}]]].label: {
                    normal: {
                        rotate: 'none'.color: '#fff'}},levels: [].itemStyle: {
                    color: 'yellow'.borderWidth: 2
                },
                emphasis: {
                    itemStyle: {
                        color: 'red'}},highlight: {
                    itemStyle: {
                        color: 'orange'}},downplay: {
                    itemStyle: {
                        color: '#ccc'}}}};setTimeout(function () {
            myChart.dispatchAction({
                type: 'sunburstHighlight'.targetNodeId: 'target'
            });
        });
 
        // Display the chart using the configuration items and data you just specified.
        myChart.setOption(option);
    </script>
</body>
</html>
Copy the code

Classic rising sun figure 1

<! DOCTYPEhtml>
<html>
<head>
    <meta charset="utf-8">
    <title>ECharts instance</title>
    <! Echarts.js -->
    <script src="https://cdn.staticfile.org/echarts/4.3.0/echarts.min.js"></script>
</head>
<body>
    <! -- Prepare a Dom with size (width and height) for ECharts
    <div id="main" style="width: 600px; height:400px;"></div>
    <script type="text/javascript">
        // Initializes the echarts instance based on the prepared DOM
        var myChart = echarts.init(document.getElementById('main'));
 
        var colors = ['#FFAE57'.'#FF7853'.'#EA5151'.'#CC3F57'.'#9A2555'];
        var bgColor = '#2E2733';

        var itemStyle = {
            star5: {
                color: colors[0]},star4: {
                color: colors[1]},star3: {
                color: colors[2]},star2: {
                color: colors[3]}};var data = [{
            name: 'imaginary'.itemStyle: {
                normal: {
                    color: colors[1]}},children: [{
                name: 'novel'.children: [{
                    name: '5' being.children: [{
                        name: 'pain'
                    }, {
                        name: 'compassion'
                    }, {
                        name: 'The tenant downstairs'}]}, {name: '4' being.children: [{
                        name: 'Cross of nothingness'
                    }, {
                        name: 'Silent confessions'
                    }, {
                        name: 'The End of Childhood'}]}, {name: '3' being.children: [{
                        name: Diary of a Mad Old Man}}]]}, {name: 'other'.children: [{
                    name: '5' being.children: [{
                        name: 'The Complete Short Stories of Nabokov'}]}, {name: '4' being.children: [{
                        name: 'Requiem'
                    }, {
                        name: 'Life puzzle'}]}, {name: '3' being.children: [{
                        name: 'I need you more than I love you'}]}]}, {name: 'Non-fiction'.itemStyle: {
                color: colors[2]},children: [{
                name: 'design'.children: [{
                    name: '5' being.children: [{
                        name: 'No interface interaction'}]}, {name: '4' being.children: [{
                        name: 'Lighting and Rendering techniques for Digital Drawing'
                    }, {
                        name: 'Anatomy of Japanese Architecture'}]}, {name: '3' being.children: [{
                        name: 'Art of Fantasy World' n&RPG Mapping Lecture}}]]}, {name: 'social science'.children: [{
                    name: '5' being.children: [{
                        name: 'pain points'}]}, {name: '4' being.children: [{
                        name: 'An effective manager'
                    }, {
                        name: 'evolution'
                    }, {
                        name: 'The advent of the post-materialistic era',}}, {name: '3' being.children: [{
                        name: 'Madness and Civilization'}}]]}, {name: 'psychological'.children: [{
                    name: '5' being.children: [{
                        name: 'The neurotic personality of our Time'}]}, {name: '4' being.children: [{
                        name: 'Pygmalion effect'
                    }, {
                        name: 'The Wounded'}]}, {name: '3' being}, {name: '2' being.children: [{
                        name: 'love'}}]]}, {name: 'home'.children: [{
                    name: '4' being.children: [{
                        name: 'House and family'
                    }, {
                        name: 'Live a life of necessity'
                    }, {
                        name: 'Nordic Simplicity'}}]]}, {name: 'this is'.children: [{
                    name: '5' being.children: [{
                        name: 'Design poetry'}]}, {name: '4' being.children: [{
                        name: 'If life messed with you'
                    }, {
                        name: 'A naturalist's Guide to mysterious Animals.'}]}, {name: '3' being.children: [{
                        name: 'direction'}}]]}, {name: 'philosophy'.children: [{
                    name: '4' being.children: [{
                        name: 'Wisdom of Life'}}]]}, {name: 'technology'.children: [{
                    name: '5' being.children: [{
                        name: 'Code Cleanliness'}]}, {name: '4' being.children: [{
                        name: 'Three.js Development Guide '}}}}]]]];for (var j = 0; j < data.length; ++j) {
            var level1 = data[j].children;
            for (var i = 0; i < level1.length; ++i) {
                var block = level1[i].children;
                var bookScore = [];
                var bookScoreId;
                for (var star = 0; star < block.length; ++star) {
                    var style = (function (name) {
                        switch (name) {
                            case '5' being:
                                bookScoreId = 0;
                                return itemStyle.star5;
                            case '4' being:
                                bookScoreId = 1;
                                return itemStyle.star4;
                            case '3' being:
                                bookScoreId = 2;
                                return itemStyle.star3;
                            case '2' being:
                                bookScoreId = 3;
                                return itemStyle.star2;
                        }
                    })(block[star].name);

                    block[star].label = {
                        color: style.color,
                        downplay: {
                            opacity: 0.5}};if (block[star].children) {
                        style = {
                            opacity: 1.color: style.color
                        };
                        block[star].children.forEach(function (book) {
                            book.value = 1;
                            book.itemStyle = style;

                            book.label = {
                                color: style.color
                            };

                            var value = 1;
                            if (bookScoreId === 0 || bookScoreId === 3) {
                                value = 5;
                            }

                            if (bookScore[bookScoreId]) {
                                bookScore[bookScoreId].value += value;
                            }
                            else {
                                bookScore[bookScoreId] = {
                                    color: colors[bookScoreId],
                                    value: value }; }}); } } level1[i].itemStyle = {color: data[j].itemStyle.color
                };
            }
        }

        option = {
            backgroundColor: bgColor,
            color: colors,
            series: [{
                type: 'sunburst'.center: ['50%'.'48%'].data: data,
                sort: function (a, b) {
                    if (a.depth === 1) {
                        return b.getValue() - a.getValue();
                    }
                    else {
                        returna.dataIndex - b.dataIndex; }},label: {
                    rotate: 'radial'.color: bgColor
                },
                itemStyle: {
                    borderColor: bgColor,
                    borderWidth: 2
                },
                levels: [{}, {
                    r0: 0.r: 40.label: {
                        rotate: 0}}, {r0: 40.r: 105
                }, {
                    r0: 115.r: 140.itemStyle: {
                        shadowBlur: 2.shadowColor: colors[2].color: 'transparent'
                    },
                    label: {
                        rotate: 'tangential'.fontSize: 10.color: colors[0]}}, {r0: 140.r: 145.itemStyle: {
                        shadowBlur: 80.shadowColor: colors[0]},label: {
                        position: 'outside'.textShadowBlur: 5.textShadowColor: '# 333',},downplay: {
                        label: {
                            opacity: 0.5}}}]};// Display the chart using the configuration items and data you just specified.
        myChart.setOption(option);
    </script>
</body>
</html>
Copy the code

Effect: