ECharts --- a very cool and easy-to-use chart library. I found myself writing in great detail. No wonder it took so long.

ECharts_study

There are many libraries for rendering visual icons. Because of the needs of the project, I learned Echarts. The full name is Apache ECharts

Many drawings will not be explained in detail in the basic preparation part, so beginners must see the basic preparation part
Besides, there are a lot of charts,

Official website

What is Echarts

ECharts, an open-source visual chart library implemented with JavaScript, can run smoothly on PC s and mobile devices, is compatible with most current browsers (IE9/10/11, Chrome, Firefox, Safari, etc.), and the underlying layer relies on vector graphics library ZRender , provide intuitive, interactive and highly personalized data visualization charts.

ECharts provides a general Line chart,Histogram,Scatter diagram,Pie chart,K-line diagram , for statistics Box diagram , for geographic data visualization Map,Thermodynamic diagram,Line diagram , for relational data visualization Diagram,treemap,Rising sun chart , multidimensional data visualization Parallel coordinates , and for BI Funnel diagramDashboard And supports the mashup between graphs.

It's awesome. It's cool. That's not much nonsense. Let's start to see how to do it

First experience

It can be copied directly.

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>ECharts-First experience</title>
    <script src="https://cdn.jsdelivr.net/npm/echarts@5.2.0/dist/echarts.js"></script>
</head>

<body>
    <div id="main" style="width: 600px;height:400px;margin:100px auto;"></div>
    <script>
        // Initialize the ecarts instance based on the prepared dom
        var myChart = echarts.init(document.getElementById('main'));

        // Specify configuration items and data for the chart
        var option = {
            // Icon title
            title: {
                text: 'ECharts First experience'
            },
            // The legend tag of type HTML is also the title of the icon. But this label can be a specific icon. The title above can be the total title showing all icons
            legend: {
                data: ['achievement']
            },
            // Column, discount and other titles with horizontal and vertical coordinates will be easier to understand in combination with the figure
            xAxis: {
                data: ['language', 'mathematics', 'English', 'Physics', 'biology', 'Chemistry']
            },
            yAxis: {},
            // Figure list. 
            series: [{
                name: 'achievement',
                type: 'bar',
                data: [120, 130, 119, 90, 90, 88]
            }]
        };

        // Display the chart using the configuration item and data you just specified.
        myChart.setOption(option);
    </script>
</body>

</html>

install

There are many installation methods, such as downloading code directly, npm acquisition, and CDN. You can even select only what you need to install.

npm

npm install echarts --save

CDN

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

Or in https://www.jsdelivr.com/package/npm/echarts Select dist / ecarts.js, click and save it as an ecarts.js file.

Then use it in the file

<script src="echarts.js" />

Or special customization provided by the official

Click here

Import project

The previous section describes how to install. For those using CDN, all modules will be loaded. Those that use npm or yarn to install or only install some functions. We can import only some required modules.

Import all

import * as echarts from 'echarts';

This will import the components and renderers provided by echarts. And focus on the eckarts object. If we want to use the pass through point method.

echarts.init(....)

Partial import

For partial import, we can only import the modules we need to reduce the final volume of the code.

The core module and renderer are necessary. Other icon components can be introduced as needed. Note that you must register before using it.

// We introduce the core module of ecarts, which provides the necessary interface for the use of ecarts.
import * as echarts from 'echarts/core';
// The histogram Chart is introduced, and the suffix of the Chart is Chart
import { BarChart } from 'echarts/charts';
// The introduction prompt box, title, rectangular coordinate system, data set, built-in data converter Component, and Component suffix are all Component
import {
  TitleComponent,
  TooltipComponent,
  GridComponent,
  DatasetComponent,
  DatasetComponentOption,
  TransformComponent
} from 'echarts/components';
// Automatic label layout, global transition animation, etc
import { LabelLayout, UniversalTransition } from 'echarts/features';
// When introducing the Canvas renderer, note that introducing the Canvas renderer or SVGRenderer is a necessary step
import { CanvasRenderer } from 'echarts/renderers';

// Register required components
echarts.use([
  TitleComponent,
  TooltipComponent,
  GridComponent,
  DatasetComponent,
  TransformComponent,
  BarChart,
  LabelLayout,
  UniversalTransition,
  CanvasRenderer
]);

// The next use is the same as before, initializing the chart and setting configuration items
var myChart = echarts.init(document.getElementById('main'));
myChart.setOption({
  // ...
});

Basic preparation (also a common step for other charts)

Preparation steps

  1. Create a box. Used to display charts. Remember to give it an initial width and height.

  2. The init method provided by echart is introduced, and other API s or components can be introduced as needed

  3. Prepare an initialization chart function, which can be called when rendering for the first time or re rendering is required. (not necessary, if data need not be modified)

  4. Call the init method in the initial function and pass in the box node prepared in advance. The init method returns an instance of a chart (echartsInstance). A box can only initialize one chart instance

  5. Use the setOption method of the chart instance to pass in an option object, which is used to configure the generated icon type, data and style.

<template>
  <div>
      <!-- Set up a box to display the chart -->
    <div id="con" :style="{ width: '400px', height: '300px' }"></div>
  </div>
</template>
<script>
    // Import init 
    import { init } from "echarts";
    export default {
 	 name: "Echarts_bar",
        // Invoke after component mount, initialize chart
 	 mounted() {
	    this.initChart();
 	 },
    methods: {
    	initChart() {
      // Call init to return an ecahrt instance
      let myChart = init(document.getElementById("con"));
            
      // Configuration chart. option is an object used to configure the chart
      myChart.setOption(option)
};
</script>

option object

The configuration of option object is the difficulty of learning charts. The basic preparation is general, simple and easy.

Therefore, to learn echarts is to learn how to configure the option object and how to configure the required charts.

From the official website, the option object has many configurations. The key value under option may be an object, and the object has many key values.

But these are summaries. Only part of a chart is used, and some can be used but not necessary.

option:{
    title:{...}  // Configuration title
    xAxis:{...}
    yAxis:{...}  // Configure x and y axes
    series:[{}]  // Configuration chart
    //....
}

The option set in the same chart instance has another feature. The old and new options are merged rather than replaced.

That is, for the first time, we configured a lot of new data. If there is new data, it will be new to configure. I just want to add new or to be changed in the new option. If the configuration remains unchanged, you can not configure it for the second time.

Bar chart

Bar chart is a common chart in junior high school. The advantage of using bar chart for data visualization in the project is that we can know the approximate quantity and change trend at a glance.

So let's learn how to use echart to make a bar chart. (the following code is written based on vue's scaffolding project)

Chart configuration

Basic preparations are common. The difficulty lies in that different charts need different configurations (but some configurations are also common). The functions are complex and there are more configuration items. This section only describes some common configurations of bar charts. Other configurations can be found on the official website as needed.

The setOption method is passed an object. It's not difficult to know. What we need to write is the key value pair. (the following keys are in no order)

  • Title: the title of the configuration chart. The value is an object.
title: {
 // Title content, support \ nline break
  text: "echarts_bar"
    
  // Other configurations will be described in the following general configuration section
},
  • **xAxis / yAxis: * * the x-axis in the rectangular coordinate system grid. Generally, a single grid component can only place the upper and lower X-axes at most. If there are more than two X-axes, you need to configure the offset attribute to prevent the overlap of multiple X-axes at the same position. (if a chart requires a coordinate axis, you can't configure xAxis, but the value of xAxis can be an empty object.)
xAxis:{
    // Axis name
    name :''
    
    // Whether to display. The default value is true
    show : true
    
    // Axis type
    type:'category',  // The category axis is applicable to discrete category data. The data corresponding to the category name can be in series or retrieved
    // Other values: Value: value axis, applicable to continuous data.
   	// 			Time: time axis, suitable for continuous time series data
    // 			log: alignment axis. Applies to logarithmic data.
    
    //   Category data, valid in category axis (type: 'category').
    data : []

	
    // Position of the x-axis.
    position :  'top'/'bottom'
    
    // The offset of the x-axis from the default position is useful when there are multiple X-axes in the same position
     offset : '20' (Default units px)
    
    // Axis scale min. And maximum scale value
    min / max : // If you don't write, it will be calculated automatically. There are many ways to write values. Has different functions. See the documentation for details.
}
  • **Series: * * series list. Each series determines its own chart type by type. The value is an array. The element of an array is an object. An object corresponds to a chart. (however, these charts all work in the same container. It can also be the superposition of multiple charts of the same kind)
series:[
   {
       	// Series name, used for displaying tooltip, legend filtering of legend, and specifying corresponding series when setOption updates data and configuration items
        name:'System name',
        // Series type, that is, the type of table. Bar: bar table. Pie: pie chart. Line: line chart. etc.
        type:'bar',
       
       // data
        data: [],  
       // If we have set the data of a coordinate axis (its type is category), the data here can be a one-dimensional array as the value of the category. It corresponds to another prepared category one by one.
       // It can also be a multidimensional array, which is used to set x-axis data and y-axis data. (you need to specify which axis is category in xAxis or yAxis).
            // data:[
            //   ['Apple', 4],
            //   ['milk', 2],
            //   ['watermelon', 6],
            //   ['Banana', 3]
            // ]
   }
]

Simple case

<template>
  <div>
    <div id="con" :style="{ width: '400px', height: '300px' }"></div>
  </div>
</template>

<script>
import { init } from "echarts";

export default {
  name: "Echarts_bar",
  data() {
    return {
      xdata: ["watermelon", "Banana", "Apple", "Peach"],
      ydata: [2, 3.5, 6, 4],
    };
  },
  mounted() {
    this.initChart();
  },
  methods: {
    initChart() {
      // Initialize the ecarts instance based on the prepared dom
      let myChart = init(document.getElementById("con"));
      // Configuration chart
      myChart.setOption({
        title: {
          // Title Component
          text: "Fruit unit price table",
        },
        xAxis: {
          data: this.xdata,  // type will default this axis to category, otherwise data will not take effect
        },
        yAxis: {
            name:'Company/element'
        },  //  type defaults to value. Data is configured in series

        series: [  // List of series. Each series determines its own chart type by type
          {
            name: "Unit Price", // Name of this chart
            type: "bar", // The type of the icon
            data: this.ydata,  // Class name data
          }
        ],
      });
    },
  },
};
</script>

Other effects

barWidth

If the column width is 100%, it will be divided into equal proportions according to the number of categories on the x-axis (as shown in this figure). Then it will be taken out 100% as the column width according to the size. If it is not set, it will be adaptive. It is set in the series of sereies. It is suitable for bar charts

 // Width of bar column
 barWidth :  '20', // If the width of the column is 100%, it is divided into proportions according to the number of categories on the x-axis (in this figure). Each is one quarter of the box width, and this percentage is relative to one quarter. If it is not set, it will be adaptive.

markPoint

Mark point, which can mark some special data. It is used in the series

// Mark points to mark some special data
markPoint: {
  symbol: "pin", // Mark the shape, circle, square, etc.
  data: [  // Set marker point. It is an array. The elements of the array are objects. Each object corresponds to a marker point.
    {
      type: "max", // Maximum
    },
    {
      type: "min", // Maximum
      name: "The name of the tag", // Can not
    },
  ],
},

markLine

Marker line, used in series

markLine: {
  data: [
    {
      type: "average",
      name: "Marker line name", // Mean line
    },
  ],
},

label

The text label on the graph can be used to describe some data information of the graph, such as value, name, etc. it is used in the series

As far as the histogram is concerned, if only the column is used, the specific value represented cannot be seen directly, but it can be marked with label

label: {
      show: true, // Whether to display. The default is false
      position : 'Mark position'  // Support strings: left, inside, etc. it also supports array representation of position: [20,30] / [10%, 20%]
      rotate : 'Rotation of text'  // There are other styles, such as color, that can be set
},

Multi effect use cases

<template>
  <div>
    <div id="con" :style="{ width: '500px', height: '400px' }"></div>
  </div>
</template>

<script>
import { init } from "echarts";

export default {
  name: "Echarts",
  data() {
    return {
      xdata: ["watermelon", "Banana", "Apple", "Peach"],
      ydata: [5, 8, 4, 9],
      ydata2: [10, 20, 40, 30],
    };
  },
  mounted() {
    this.initChart();
  },
  methods: {
    initChart() {
      let myChart = init(document.getElementById("con"));
      myChart.setOption({
        title: {
          text: "Fruits",
          link:'https://echarts.apache.org/v4/zh/option.html#title',
          left:'30'
        },
        xAxis: {},
        yAxis: {
          type: "category",
          data: this.xdata,
        },
   
        series: [
          {
            name: "Unit Price", 
            type: "bar", 
            markLine: {
              // Marker line
              data: [
                {
                  type: "average",
                },
              ],
            },
            label: {
              show: true, // Whether to display. The default is false
            },
            barWidth: "25%", 
            data: this.ydata, // Chart data
          },
          {
            name: "Storage capacity",
            type: "bar",
            data:this.ydata2,
            markPoint: {
              symbol: "pin",
              data: [
                {
                  type: "max", // Maximum
                },
                {
                  type: "min",
                },
              ],
            },
          },
        ],
      });
    },
  },
};
</script>

General configuration

Here are some general configurations, but not all of them are listed. Some contents are used in special scenarios or rarely used. I won't introduce them. If you need to consult the documents, this note is for introductory learning and providing some cases.

title

Configure the title of the chart. The value is an object.

title: {
 // Title content, support \ nline break
  text: "echarts_bar",
      
  // Title hyperlink, click the title to jump
  link :'url'
    
  // Title Style object
  textStyle : {
     /*
     	color
     	fontStyle / fontWeight Equal font style
     	width / height
     	There are also border, shadow and other styles
     */
   }
    
  // Sub text title, it also has independent styles, links, etc.
   subtext :'character string'
    
  // Horizontal alignment of the whole (including text and subtext)
   textAlign :''  // 'auto','left','right','center'
    
   // position adjustment
   left / top / right / button  // The value can be 20 (default unit px), the percentage of '20%' relative to the width and height of the parent box, or 'top', 'middle', 'bottom'.
},

tooltip

Prompt box component. It can be set in many locations, such as global, local, a series, a data, etc

The prompt box component has different effects on different types of diagrams.

For example, in the bar chart, the effect is like this: (a prompt box appears when the mouse hovers over the bar column)

The value of tooltip is also an object. You can configure whether to display, display trigger conditions, displayed text, style, etc.

 //  Prompt box component.
tooltip: {
      show: true,
      trigger: "item", // Trigger type.
      // Item data item graph trigger is mainly used in scatter chart, pie chart and other charts without category axis. (that is, it will be triggered on the graph)
      // Axis coordinate axis trigger is mainly used in histogram, line chart and other charts that will use category axis (it can be on the coordinate axis, not necessarily on the graph)
      // none triggers nothing.
          
      triggerOn: "mousemove", // Triggered when the mouse moves. Or click / none

      //  formatter:'{b}: {c}' / / you can customize the content of the prompt box. If not, there will be the default content.
          						 // Some variables have been assigned values. You can refer to documents according to different types, such as b and c above
      //  It supports the writing of {variable}. It also supports HTML tags,
          
      //  In addition to a string, the value can also be a function. A function is a callback function. The return value of the function is a string, and the value of this string is displayed as the value of formatter.
      //  The function receives a parameter, which is an object with relevant data in it.
      formatter: (res) => {
        return `${res.name}:${res.value}`; // Category name: value
      },
        
      // Text style of the floating layer of the prompt box
       textStyle :{}  // Color, fontsize, etc
    },

toolbox

According to the column, there are five built-in tools: export chart as picture, data view, dynamic type switching, data area scaling and reset. They can be added as needed.

toolbox: {
    // Tool size
    itemSize:  15
    // Spacing between tools
    itemGap: 10
    
    // Configuration tool
      feature: {
        saveAsImageL: {}, // Export picture
        dataView: {}, // Direct data display
        restore: {}, // Reset
        dataZoom: {}, // zoom
        magicType: {
          // switch
          type: ["bar", "line"],
        },
      },
    },

legend

The legend component displays symbols, colors and names of different series. You can click the legend to control which series are not displayed

legend: {
    data: ["Unit Price", "Storage capacity"],  // The element value is the name of the series
    // There are also some control styles
 },
series:[
    {
        name:'Unit Price',
        ...
    },{
		name ;"Storage capacity"
        ....
    }
]

Line chart

Line chart is used to show the change of data in a continuous time interval or time span. Its characteristic is to reflect the trend of things changing with time or ordered categories.

The change trend is obvious, and when multiple groups of data are displayed in the same table, it is easy to compare and simple.

Basic use

The use of line chart is almost the same as that of bar chart. In most cases, you only need to replace the type bar with the type line.

Set box - > Import ecahrts related API - > create ecahrts instance - > set option

<template>
  <div>
    <div id="con" :style="{ width: '500px', height: '400px' }"></div>
  </div>
</template>

<script>
import { init } from "echarts";

export default {
  name: "Echarts_line",
  mounted() {
    this.initChart();
  },
  methods: {
    initChart() {
      let myChart = init(document.getElementById("con"));

      let option = {
          title:{
              text:'New user statistics',
              left:'center'
          },
          xAxis:{
              name:'month',
              data:['1','2','3','4','5','6']
          },
          yAxis:{
              name:'New user / individual'
          },
          series:[
              {
                  name:'New user statistics',
                  type:'line',
                  data:[3000,2400,6300,2800,7300,4600,2200]
              }
          ]

      };
      myChart.setOption(option);
    },
  },
};
</script>

Other effects

xAxis , yAxis

The configuration of the x and y axes is roughly the same. The section has been described in the bar chart section. Here are some necessary supplements.

  • boundaryGap

The setting and performance of category axis and non category axis are different.

The value can be Boolean or array ['value1','value2']. Set the blank size on both sides.

xAxis:{
  type:'',
  data:[],
  boundaryGap:false
}

  • scalse

type:'value' is valid only in the value axis. Whether it is a scale away from the 0 value. When set to true, the coordinate scale does not force zero scale.

It is suitable for data with large data and small fluctuation range, or in the scatter diagram of double value axis.

yAxis:{  // type defaults to value
    scale:true
}

lineStyle

The style of polyline is set in the series.

series: [
  {
// 	....
    lineStyle: {
      color: "red",
      type: "dashed", // dashed: dotted line, dotted: dotted line, solid: solid line (default)
    },
  },
]

  • smooth

Sets the style of the break point of the line chart, whether it is smooth or angular. The value is Boolean, and the default is false. Set in the series

series: [
  {
	// ....
    smooth:true
  },
]

  • markArea

Marking area, in the bar chart, we learned to mark points and lines. A marker area is added here. The marked area will have a shadow. We can set the color of the shadow.

It is also set in the series

// In the element object of sereis, 
markArea:{
    data:[  // data is a two-dimensional array. 
            [		// Set marker area
                {
                    xAxis:'1'
                },
                {
                    xAxis:'2'
                }
            ],
            [	// Set second marker area
                {
                    xAxis:'4',
                    yAxis:'3100'
                },
                {
                    xAxis:'6',
                    yAxis:'3300'
                }
            ]
    ]
}

  • areaStyle

Area fill pattern. After setting, it will be displayed as an area map.

 series: [
          {
			// ...
            areaStyle:{
                color:'pink',
                origin:'end'  // Auto (default), start, end
            }
          },
  ],

  • stack

Stack graph, when there is more than one group of data, and we want the second group of data to be superimposed on the first group of data.

series: [
  {
    name: "New user statistics",
    type: "line",
    data: [700, 1000, 400, 500, 300, 800, 200],
    // The value of stack is used for matching, and the superimposed value will match it
    stack:'mystack',
    areaStyle:{}  // Configure the color. If it is blank, ecahrts will automatically configure the color
  },{
      name:'Overlay data',
      type:'line',
      data: [700, 300, 400, 200, 500, 100, 300],

      stack:'mystack',  // Superimposed with the data of the stack configured first.
      areaStyle:{}
  }
],

Scatter diagram

Basic use

Scatter plot can help us infer the correlation between variables.

Its type is scatter. Compared with bar and line, its feature is that both coordinates are data (value). It displays points one by one.

The basic operation is the same as that of line chart and bar chart. The type of coordinate axis is value. The type of series is scatter. The data is a two-dimensional array.

<template>
  <div>
    <div id="con" :style="{ width: '500px', height: '400px' }"></div>
  </div>
</template>

<script>
import { init } from "echarts";

export default {
  name: "Echarts_scatter",
  data() {
    return {};
  },
  mounted() {
    this.initChart();
  },
  methods: {
    initChart() {
      let myChart = init(document.getElementById("con"));

      let option = {
        title: {
          text: "Scatter diagram",
          left: "center",
        },
        xAxis:{
            type:"value",
            scale:true
        },
        yAxis:{
         type:"value",
         scale:true
        },
        series:[
            {
                type:'scatter',
                data:[
                  // x , y   
                    [10,11],
                    [9,10],
                    [11,11],
                    [10,10],
                    [10,12],

                    [13,11],
                    [12,15],
                    [12,13],
                    [14,13],
                    [13,13],
                    [13,12],

                    [15,14],
                    [14,13],
                    [14,14],
                    [16,15],
                    [16,17],

                    [17,16],
                    [17,17],
                    [17,18],

                    [18,16],
                    [18,17],
                    [18,20],
                ],
            }
        ]
      }

      myChart.setOption(option);
    },
  },
};
</script>

Other effects

symbolSize

Configuration item that controls the size of scatter points. Used in series.

It can control the size of all scatter points by = one by one, or it can control the size of some added points

series:[
    {
         // ...
        
        // Controls the size of the scatter.
        // symbolSize:10, / / the value can be a numerical value to control the size of all scatter points in this series        
       symbolSize:function(e){  // The value can also be a function
          console.log(e);   // The value is an array of numeric values one point at a time.
          if(e[1]/e[0]>1){  // When the value of the y-axis is greater than the value of the x-axis, the size is 12, otherwise it is 6
            return 12
          }
          return 6
        },
    }
]

itemStyle

Control the color of scatter points, which is used in sereis series

It can control the color of all points or the color of some points.

itemStyle:{
      // color:'red' / / direct assignment,
    
      color:function(e){  // Function values are also supported
        console.log(e.data);  // E is the scattered data, and e.data takes out the numerical array
        let [a,b] = e.data
        if(b/a>1){
          return 'red'
        }
        return 'green'
      }
}

Figure of the combination of the above two effects

effectScatter

It is the value of type of series series. It is also a scatter chart. But it has ripple effect. For example:

We set the value of type to effectscutter. Then all scatter points of this series of scatter diagrams have the effect of ripple.

It can be used with showEffectOn trigger timing and rippleEffect ripple effect.

series:[{
    type:'effectScatter',   // Ripple animation effect. After use, turn on the ripple effect for all scatter points in this series. After the default icon is loaded, turn on the effect.
    
    // Trigger timing
	showEffectOn:'emphasize', // The default value is render. It means that the scatter is enabled after loading. emphasize means that the scatter is enabled only when the mouse hovers over the scatter
	
    // Ripple style
	rippleEffect:{
      color:'',  // The color of ripples, which defaults to the color of scattered points
      number : 2  // Number of ripples
      period : 3  // Animation period in seconds
      scale:10  //  Control the size of the expansion of ripples. scale is based on how many times the original.
    },			
}]

General configuration of xoy axis

The above three figures are all on the X and Y axes. This section describes some general configurations of the xoy axis.

grid

For the drawing grid in the rectangular coordinate system, the upper and lower X axes and the left and right Y axes can be placed in a single grid.

grid:{
    // Show chart border
    show:true,
    // border width 
    borderWidth:10,
    // Border color
    borderColor:'red',

    // left / top / controls the offset between the chart and the box. It will affect the size of the chart
    left:120  // left ,top , button,right 

    // Controls the size of the chart
    // width:/height:
},

axis

x and y axes. This knowledge point is actually mentioned in the bar chart.

xAxis:{  // Or yAxis
    
    // Axis name
    name :''
    
    // Whether to display. The default value is true
    show : true
    
    // Axis type
    type:'category',  // The category axis is applicable to discrete category data. The data corresponding to the category name can be in series or retrieved
    // Other values: Value: value axis, applicable to continuous data.
   	// 			Time: time axis, suitable for continuous time series data
    // 			log: on the number axis. Applicable to logarithmic data.
    
    //   Category data, valid in category axis (type: 'category').
    data : []

	
    // x. The position of the y-axis.
    position :  'top'/'bottom' / 'left'/ 'right'
    
    // The offset of the x-axis from the default position is useful when there are multiple X-axes in the same position
     offset : '20' (Default units px)
    
    // Axis scale minimum and maximum scale values
    min / max : // If you don't write, it will be calculated automatically. There are many ways to write values. They have different functions. Please refer to the document for details.
}

Emphasize a few points

  • If data is set, type defaults to category. If it is empty, it defaults to value. The value is obtained from series.
  • If category is set but data is not set, the data in the series must be a two-dimensional array.
  • If the data of an axis is obtained from the series and it is of category type, it must be configured with category type in axis.

dataZoom

Previously, we knew that there was a dataZoom tool in the toolbox. You can select a part of the graph to zoom in and out.

This dataZoom is not configured in the toolbox, but directly under option.

The value is an array, and the element of the array is a scaling function. For example, you can configure one for the x-axis and one for the y-axis data. Generally, when there is only one, the default is

let option = {
    dataZoom:[
        {
            // Zoom type, control zoom position, and method.
            type:'slider'  // There is a sliding axis at the bottom of the x axis. 'inside' / / zoom through the mouse pulley in the figure
        }
    ]
    // ...
}

**If it is inside * *, no UI will be added. However, when the mouse is placed in the figure and scrolled, it can be scaled according to the mouse position.

Multiple scalers

When there are multiple scalers, you need to configure the index of their corresponding coordinates corresponding to different coordinates.

Generally, if there are no multiple x and multiple y, then inde is 0.

 dataZoom:[
    {
        type:'slider',
        xAxisIndex:0  // x axis
    },{
        type:'slider',
          yAxisIndex:0
    }
],

Pie chart

The union chart is also a kind of chart with simple structure. Its characteristic is that it can intuitively see the approximate proportion of various purposes.

It doesn't need the x and y axes. But the basic preparation remains the same.

The main note is that the type of series is pie. And the type of data

The data value of series can be written in a variety of ways. One dimensional array, two-dimensional array, or object array. Object arrays are commonly used

[
    {
        name:'Data item name.',
        value:'Data value'
    }
]

Simple case

<template>
  <div>
     <div class="con" :style="{ width: '450px', height: '300px' }"></div>
  </div>
</template>

<script>
import {init} from 'echarts'
export default {
    name:'ecahrts_pie',
    mounted(){
        this.initChart()
    },
    methods:{
        initChart(){
        let chart = init(document.querySelector('.con'))
        let option={
            title:{
                text:'pie',
                left:'center'
            },
            series:[
                {
                    type:'pie',
                    data:[
                        {
                            name:'sleep',
                            value:'7'
                        },{
                            name:'Code',
                            value:'10'
                        }
                    ]
                }
            ]
        }
        chart.setOption(option)
    }
    }
}
</script>

Common effects

label

The text label on the pie chart graph can be used to describe some data information of the graph, such as value, name, etc. The default is displayed. That is, the coding and sleeping in the figure above.

// If the data is just a simple one-dimensional array
data = [7,10]
// Then there are only values and no names. Therefore, you can set label not to display
label:{
    show:false
}
// The picture shows a bare circle.

In addition to controlling whether the label is displayed, we can also control the content and style of the displayed data text.

label:{
    show : true,
    formatter:'character string', // Also fill in the variable {variable}
     //  {a} : series name.
	 //  {b} : data name.
	 //  {c} : data value.
	 //  {d} : percentage.
    // The value of formatter can also be a function. The function can be connected to a parameter. If there is data required on the parameter, integrate the data and return it.
        
    // There are also position, color and other control styles
}

radius

The radius of the pie chart. By setting it, we can change the radius of the pie chart or set it as a ring.

series:[{
    // ....
    radius:''  // Value: absolute radius in PX 
    		   // Percent: take half of the minimum value of width and high school, and then take the value of percent.
    	       // Array: ['inner radius',' outer radius']
}]
label:{
    show:true,
    formatter:'{b}:{d}%'
},
radius:['60','80']

roseType

Whether to display as Nightingale chart, and distinguish the size of data by radius. Two modes can be selected:

  • The 'radius' sector center angle shows the percentage of data, and the radius shows the size of data.
  • 'area' the center angle of all sectors is the same, and the data size is displayed only by radius.
series:[{
    // ...
    roseType:'radius'
}]

selectedMode

Click to select the mode. The pie chart has its own animation when the mouse hovers. But clicking does not respond.

Set selectedMode to add the click selection effect for the sector. It can be used with selectedOffset

series:[{
    // ...
    selectedMode:'single'  // Another value is multiple.
    // The effect is shown in the figure below. If it is single, only one sector can have this effect at the same time. While multipe allows multiple sectors to be in the selected state.
    
    // It can be used with selectedOffset to set the offset size
    selectedOffset: 30
}]

Map

MAPJSON

Basic use

Brief steps

The basic preparation remains unchanged.

  • Introduce echarts related API s, prepare containers, initialize objects, and set option s.

But it is also very different from the previous icons.

  • The json data of vector map needs to be prepared first. It can be loaded through ajax or downloaded locally in advance
  • Register map data globally using registerMap exposed by echarts.
import {registerMap} from 'echarts'

registerMap('chinaMap',china)  // The first parameter is the name required for later use, and the second is JSON data
  • In option, you can configure either series or geo.
geo:{
    // type is map 
    type:'map',
    map:'chinaMap'  // It needs to be the same as the name set during registration
}
// perhaps
series:[{
    type:'map',
    map:'chinaMap'
}]

Simple case

Download address of JSON file in this case

<template>
  <div>
  <div id="con" :style="{ width: '700px', height: '600px' }"></div>
  </div>
</template>

<script>
    // Import init and registerMap
import {init,registerMap} from 'echarts'
    // Import map JSON data downloaded locally in advance
import china from '../../jsondata/china.json'

export default {
    name:'echarts_map',
    mounted(){
        this.initChart()
    },
    methods: {
       async initChart(){
            let Chart = init(document.querySelector('#con'))
            		// Register maps with register
            await registerMap('chinaMap',china)
            let option = {
                geo:{
                    type:'map',
                    map:'chinaMap'  // It needs to be the same as the name set during registration
                }
            }
            Chart.setOption(option)
        }
    },
}
</script>

Common configuration

roam

Set the effects that allow zooming and dragging. When the mouse is placed on the map, you can zoom through the scroll wheel, and click the map to drag.

The value is Boolean

geo:{
    // ...
    roam:true
}
label

In the rendering of the above example, we can see that each province has no name. label can control the display and style of province names.

geo:{
    // ...
    label:{
        show:true,
        // The displayed content is not set. The default is the province name. The value can be a string or function. It is the same as the above.
        formatter: ''
        // There are many configurations of styles. Please refer to the document
    }
}

zoom

Set the zoom scale of the map during initial loading. The value is array. Under geo, it is the same level as label

center

Set the center point. The values are array. ['longitude coordinate', 'latitude coordinate'] set the point corresponding to longitude and latitude to the center of the chart

Common effects

Set color

In the above maps, they are all gray. Except that the mouse hovers, it will change color. It looks very monotonous.

Through the combination of series and visual map, we can set the color for the map, but its color will not be too dazzling. Generally, the color is used to display the population or temperature.

**Configuration steps * * (based on the configured basic map)

  • Prepare a data, which saves the names of provinces in the map and the corresponding data, or the names of cities (according to the national map, provincial map, or others)
let temdata = [
    {
        name:'Guangdong Province',  // Suppose it is a national map, and name matches Guangdong Province
        value:'32'	  //  Set the corresponding data. For example, here we set the temperature.
    },{
        name:'Fujian Province',
        value:'29'
    },{
        // ...
    },//...
]
  • Associate series with geo. Of course, geo can also be replaced by series, so it is to add a series.
series:[{
    // Configuration data is the data prepared above
  data:temdata,
    // The index of the associated map is required. The index can be configured in geo. If there is only one, the default is 0
  geoIndex:0,
    // The configuration type needs to be map.
  type:'map'
}],
  • Configure visual map. This is a required step, otherwise the color will not be displayed.

It is a visual mapping component used for "visual coding", that is, mapping data to visual elements (visual channels).

visualMap:{
    // After configuring visaulMap, show defaults to true. If it is set to false, this component will not be displayed.
    show:true,
    // Set minimum value
    min:0,
    // Set maximum
    max:100,
    // Configure the color change from minimum to maximum. If not configured, it will be set automatically
    inRange:{
      color:['white','pink','red']  // Multiple colors can be configured
    },
    calculable:true // The slider appears and is not set to false. However, it has the same filtering function as the original component.
}

case
<template>
  <div>
    <div id="con" :style="{ width: '1000px', height: '800px' }"></div>
  </div>
</template>

<script>
import { init, registerMap } from "echarts";
import china from "../../jsondata/china.json";
// import axios from 'axios'
export default {
  name: "echarts_map",
  data(){
    return {
      temdata:[]
    }
  },
  mounted() {
         // get data
   china.features.forEach(v=>{
      let obj = {
        name:v.properties.name,
        value:(Math.random()*(100)).toFixed(2)
      }
      this.temdata.push(obj)
    })
       // Initialize chart
    this.initChart();
  },
  methods: {
    async initChart() {
      let Chart = init(document.querySelector("#con"));
      await registerMap("china", china);
      let option = {
        geo:{
            type:'map',
            map:'china',
            label:{
                show:true
            }
        },
          series:[{
            data:this.temdata,
            geoIndex:0,
            type:'map'
          }],
      visualMap:{
        show:true,
        min:0,
        max:100,
        inRange:{
          color:['white','red']
        }
      }
      };
      Chart.setOption(option);
    },
  },
};
</script>

Combined with other figures

Maps can be displayed in combination with other maps.

Combined scatter diagram

A container can have multiple graphs. Here we add a scatter graph to the map, in fact, we add a series of objects with the type of scatter graph.

But our previous scatter map is on the coordinate axis, and the map has no coordinate axis. Therefore, we need to use longitude and latitude to mark the position of points.

Steps (based on map already configured)

  • Prepare data. The data uses longitude and latitude to mark the position of points. Longitude and latitude can be obtained in the json data of the map.
let opintData = [
    [116.405285, 39.904989],
    [117.190182, 39.125596],
    //....
]
  • Add an object in the series, whose type is scatter or effecrScatter, and set data.
  • At the same time, the coordinateSysem is configured as geo, that is, the longitude and latitude are set as the location reference, and the default is xoy coordinate axis
series:[
    {
        type:'effectScatter',
        data:opintData,
        coordinateSystem:'geo',
    }
]

Combine lines

Path map

It is used for drawing line data with start and end information, mainly for route and route visualization on the map

Its coordinateSystem is geo by default. Here we cooperate with the map to present the effect shown in the figure below.

The type of its series series is lines. No xoy shaft is required. Therefore, it also needs to pay attention to data processing.

series:[
    {
        type:'lines',
        data: [  // The value is an array of objects, and each object is a path.
          {
            coords: [
              [116.405285, 39.904989],  // starting point
              [129.190182, 38.125596],   // End,
              // Support multiple points, if necessary
            ],
              // Configure path style
            lineStyle:{
              color:'red',
              width:1,
              opacity:1
            },
              // Adds a text label to the end of the path.
            label:{
              show:true,
              formatter:'Beijing XXX company',
              fontSize:16,
              borderRadius:4,
              padding:[10,15],
              // verticalAlign :'middle',
              backgroundColor:'orange'
            }
          },
        ],
    }
]

Radar chart

Radar chart is generally a visual processing of data after testing the performance of an object. Can clearly see the advantages and disadvantages.

Basic use

step

  • Prepare the box, import ecahrt related API s, etc. (some of the above are not described in detail)
  • Configure radar.indicator: it is used to configure a framework. As shown in the figure above, the Pentagon and text.
// Its value is an array, and the elements of the array are objects. An object corresponds to a corner. There are name and max attributes in the object. Are the displayed text and the maximum value, respectively
option = {
    radar:{
        indicator:[
            {
            name:'hearing',
            max:'100'
            },{
                // ....
            }
        ]
    }
}
  • Configure series. The type is radar. data is an array of objects.
series: [
  {
    type: "radar",
    data: [
      {
        name: "English",
        value: ["80", "90", "77", "65", "100"],  // Match the object configuration sequence in the indicator one by one.
      },
        {
            // Can there be more than one
        }
    ],
  },
],

Simple case

<template>
  <div>
    <div
      class="con"
      :style="{
        width: '350px',
        height: '300px',
      }"
    ></div>
  </div>
</template>

<script>
import { init } from "echarts";
export default {
  name: "ecahrts_radar",
  mounted() {
    this.initChart();
  },
  methods: {
    initChart() {
      let chart = init(document.querySelector(".con"));
      let option = {
        radar: {
          indicator: [
            {
              name: "hearing",
              max: "100",
            },
            {
              name: "fluent",
              max: "100",
            },
            {
              name: "pronunciation",
              max: "100",
            },
            {
              name: "vocabulary",
              max: "100",
            },
            {
              name: "Aggregate quantity",
              max: "100",
            },
          ],
        },
        series: [
          {
            type: "radar",
            data: [
              {
                name: "English",
                value: ["80", "90", "77", "65", "100"],
              },
            ],
          },
        ],
      };
      chart.setOption(option);
    },
  },
};
</script>

Common configuration

label

Text label. Set to true to display data or

series:[{
    // ...
    label:{
        show:true
        formatter:'show contents'  // The default is the corresponding value
        position // Equal style settings
     }
}]

areaStyle

Area fill pattern, which can fill the part surrounded by some data with other colors. You can set color, transparency, etc.

series:[{
    // ...
    areaStyle:{  // Even empty objects have a default color fill
        color:'orange' ,
        opacity:0.6
    }
}]

shape

The radar chart is not necessarily square, but also round. We can modify the shape by adding a configuration shape to the label object

        radar: {
          shape: "circle",  // It can be a circle or a polygon (default)
      //    indicator: ...
        },

Instrument diagram

The instrument diagram is the simplest configuration diagram.

Basic use

step
  • Basic box preparation, introduction of ecarts API, etc
  • The type of the object element of the configuration series is gauge. data configuration pointer
series: [
  {
    name:'Company or data name' // For example, weight, or km/h, can also be absent
    type: "gauge",
    data: [  // The value is an array, the elements of the array are objects, and an object is a pointer
      {
        value: "92",   // Set the current value pointed by the pointer, and the maximum data and scale value of the instrument will be automatically adjusted
      },
    ],
  },
],

Common configuration

itemStyle

Configure the color of the pointer in the object that configures the pointer. Each pointer can be configured with different colors, border colors, shadows and other styles.

data:[{
    value:'92',
    itemStyle:{
        color:'pink'
    }
}]

min/max

The scale value of the instrument will be set automatically or manually.

series: [
  {
  	// .....
    min: "50",
    max: "150",
  },
],

style

Color theme

The easiest way to change the global style is to directly adopt the color theme.

Built in theme color

In addition to the consistent default theme (light), ECharts5 also has a built-in 'dark' theme.

The init API can also pass in the second parameter to change the color theme. The default is light. If you need to change to dark, you can pass in dark.

let myChart = init(document.querySelector('#con'),'dark')

Custom theme colors

Theme Editor

In the theme editor, we can edit the theme and then download it as a local file. Then use it in the project.

The specific steps are clearly written in the official documents.

  • After configuring your own font, set a theme name. Of course, you can also use the default font

  • Then click the download topic. There are two versions that can be downloaded and used. The use steps and official documents are also very clear

Introduction method

// es6
import  '../assets/mytheme'
	// use
  let chart = init(document.querySelector("#con"),'mytheme');

// CDN 
<script scr='url/mytheme.js'></script>

If you change the file name and forget the topic name, you can open the downloaded topic file and find the following code

echarts.registerTheme('mytheme',...)  // The first parameter is the subject name.

Debug color wheel

Whether it's a built-in theme or a theme we set ourselves. Each has a palette.

For example:

If there are no special settings, the chart will take colors from the palette.

For example, we often do not set color, but the bar column has color, and the pie chart also has color.

Global palette

In addition to the theme's own color palette, we can also set a global color palette, which will overwrite the theme color palette.

The global palette is directly set under option, the key is color and the value is array

option:{
    color:['#ff0000','blue','green '] / / support colors such as hexadecimal
}

If there are fewer kinds of colors, the same color may appear in parts that should have different colors, such as color:['red','blue ']

Local palette

The partial palette is set in the series. Dedicated to a graph.

series:[{
    type:'pie',
    color:['red','yellow']
}]

Direct style settings (xxxStyle)

The color palette provides color, but when rendering, the color of a part is uncertain, or may change.

Therefore, we can use the relevant configuration to set its color directly.

Direct style setting is a common setting method. In option, itemStyle,textStyle,lineStyle,areaStyle,label, etc. can be set in many places. In these places, the color, line width, point size, label text, label style, etc. of graphic elements can be set directly.

itemStyle

This can be used in many charts. It can set the color of the bar column of the bar chart, control the color of each part of the pie chart, and use it in the scatter chart, etc.

series:[{
    //...
    itemStyle:{
        color:'red'   // Control all, support callback function color: (RES) = > {}
    }
}]

There are also graphs that support writing in data to control the color of some data, such as pie charts

series:[{
	type:'pie',
	data:[{
		name: "sleep",
        value: "7",
        
        // Set color
        itemStyle: {
          color: "green",
        },
	}]
}]

In addition to controlling the color, itemStyle has other styles to control

// part
borderColor: '#000 ', / / border color
borderWidth: 0 ,	   // Border width
borderType: 'solid' ,	// Border type
borderDashOffset: 0 ,   // Used to set the offset of the dashed line
borderCap: butt ,		// Specifies how segment ends are drawn
opacity: 1 ,			// transparency
 ......
textStyle

Text Style is configured in the title. We usually use to configure the color, size and position. Therefore, the use method is basically the same as that of other styles. There are some general descriptions in the general configuration. We won't repeat it.

lineStyle

It can be used in line related graphs such as line graph and path graph.

areaStyle

We have used this configuration in line chart and radar chart. But there are more than two kinds of charts that can use it. But its configuration is also relatively simple.

label

Text tags, which we have used many times in the above examples, will not be repeated.

Constant light and highlight

Normally on, that is, its color in the general state, which can be configured by direct style or color palette.

This section focuses on highlighting.

Highlight is the color (such as mouse hovering or clicking) that appears when the graph corresponding to some data is selected. It is generally hovering.

The highlighted style is configured through emphasis.

Take the pie chart as an example, others are similar.

series:[{
    //...
    emphasis:{
        scale:true  // Zoom in or not,
        scaleSize:2 // Magnification
        focus:'none' // Fade other graphics
        // For example, linestyle, itemstyle, label, etc. some can also be placed in emphasis. The writing method remains the same, but the position changes. Configure the style when highlighting
        itemStyle: {
        color:'red'
    }
}]

Color gradient and texture fill

The value of color supports the use of RGB to represent pure color, such as' rgb(128, 128, 128) ', or RGBA, such as' rgba(128, 128, 128, 0.5)', or hexadecimal format, such as' #ccc '.

The value of color can also be a callback function.

In addition, the value of color can be an object. The gradient used to configure the color

// Linear gradient
color:{
    type:'linear'  // Linear gradient
    
    x: ,
    y: ,
    x2:,
    y2:,  // (x,y) represents one point, (x2,y2) represents another point, and x,y points to x2,y2. Indicates the direction
        
    colorStops:[{
        offset:0,  // Color at 0%
        color:''   
    },{
        offset: 0.3  // Color at 30%
        color:''
    },{
       // ....
    }]
}
// Radial Gradient 
{
  type: 'radial',
  x: 0.5,
  y: 0.5,
  r: 0.5,  // (x,y) is the origin and r is the radius
      
  colorStops: [{
      offset: 0, color: 'red' // Color at 0%
  }, {
      offset: 1, color: 'blue' // Color at 100%
  }],
}

What's more amazing about color is that it supports texture filling, which is equivalent to backgroundImage.

// Texture fill
{
  image: imageDom, // Htmlimageelement and htmlcanvas element are supported, but path string is not supported
  repeat: 'repeat' // Whether to tile. It can be 'repeat-x', 'repeat-y', 'no repeat'
}

case

<template>
  <div>
    <div class="con" :style="{ width: '450px', height: '300px' }"></div>
  </div>
</template>

<script>
import { init } from "echarts";
export default {
  name: "ecahrts_pie",
  mounted() {
    this.initChart();
  },
  methods: {
    initChart() {
        // Load picture resources as textures
      let imgsrc = "https://img0.baidu.com/it/u=1884420695,412160940&fm=26&fmt=auto";
      let piePatternImg = new Image();
      piePatternImg.src = imgsrc;

      let chart = init(document.querySelector(".con"));
      let option = {
        color: ["pink", "lightblue"],
        title: {
          text: "pie",
          left: "center",
        },
        series: [
          {
            type: "pie",
            data: [
              {
                name: "sleep",
                value: "7",
                itemStyle: {
                  color: {
                    type: "linear",
                    x: 0,
                    y: 0,
                    x2: 0,
                    y2: 1,
                    colorStops: [
                      {
                        offset: 0,
                        color: "red", // Color at 0%
                      },
                      {
                        offset: 1,
                        color: "blue", // Color at 100%
                      },
                    ],
                    global: false, // The default is false
                  },
                },
              },
              {
                name: "Code",
                value: "9",
                itemStyle: {
                  color: {
                    type: "radial",
                    x: 0.5,
                    y: 0.5,
                    r: 0.5,
                    colorStops: [
                      {
                        offset: 0,
                        color: "#46bbf2 ", / / color at 0%
                      },
                      {
                        offset: 1,
                        color: "#Aa47d7 ", / / color at 100%
                      },
                    ],
                    global: false, // The default is false
                  },
                },
              },
              {
                name: "Daydreaming",
                value: "5",
                itemStyle: {
                  color: {
                    image: piePatternImg,
                    repeat: "repeat",
                  },
                },
              },
            ],
          },
        ],
      };
      chart.setOption(option);
    },
  },
};
</script>


Container and container size

Containers are used to store charts. In the above use, we only used one method to set the width and height.

Define a parent container with width and height in HTML (recommended)

Generally speaking, you need to define a < div > node in HTML first, and make the node have width and height through CSS. Using this method, you must ensure that the container has width and height at init.

<!-- Specify width and height -->
<div class="con" :style="{ width: '450px', height: '300px' }"></div>
<!-- Specify the height and width as the width of the viewer visual interface -->
<div class="con" :style="{  height: '300px' }"></div>

Specifies the size of the chart

If the chart container does not have width and height, or if you want the chart width and height not to be equal to the container size, you can also specify the size during initialization.

<div id="con"></div>

  var myChart = init(document.getElementById('con'), null, {
    width: 600,
    height: 400
  });

This takes advantage of the third parameter of init, which is an object that specifies the width and height of the chart.

Respond to changes in container size

When the width and height are specified, the size of the chart is fixed. If we change the size of the viewer window, we will find that the size of the chart will not change.

Even if the width is not set to dead. The container width is adaptive, but the chart will not be adaptive, and some will be obscured. As shown in the figure:

If we want the chart to be adaptive, we can use the resize() method on the chart instance returned by init.

var myChart = init(document.getElementById('con'));
  window.onresize = function() {  // Listen for window size events
    myChart.resize();  // Call the resize method
 };

// You can do the same
window.onresize = myCahrts.resize

// Or use the event listener
 window.addEventListener("resize", myChart.resize);

resize supports an object parameter, which is equivalent to the third parameter of init, so that the actual width and height of the chart does not depend on the container.

myChart.resize({
  width: 800,
  height: 400
});

Note, however, that the size of the chart is limited by the container. Once the width and height of the chart is dead, it cannot be changed adaptively

In the following cases, calling resize directly cannot change the width and height of the chart

// 1. Vessel width and height limit
    <div
      id="con"
      :style="{ width: '600px', height: '400px'}"
    ></div>

// 2. Chart width and height limit
  var myChart = init(document.getElementById('con'), null, {
    width: 600,
    height: 400
  });

But it is not without solution

We can get the width and height of the viewer and modify the width and height of the container by resetting setOption. If the container does not set overflow to hidden, the dynamically obtained width and height can also be used as the resize parameter.

animation

Load animation

A lot of chart data is requested from the server. If the network is not very good, or there is a lot of data, there will be blank.

Therefore, ecarts has built-in loading animation.

myChart.showLoading()  // Show animation

myChart.hideLoading()  // hide animation

// myChart is the chart instance returned by init

We can turn on the animation when loading data, and then hide the loaded animation when the data comes back.

animation

Animation configuration in option.

option turns on the animation effect by default. For example, after loading the data, or when changing the data.

option = {
	animation:  true   // Whether to enable animation effect. The default value is true
    
    animationDuration : 100  // Animation duration in milliseconds
    // The value of an animation can be a function, and the parameter of the function is the number of each part of the image. It depends on the actual situation
    
    
    animationEasing:'linear'  //  Jog animation
    // More effect references https://echarts.apache.org/examples/zh/editor.html?c=line-easing
	
    animationThreshold:8   // Maximum animation
    // Take the histogram for example. Each column, or marker point, or marker line will have an independent animation. If these independent animations exceed the number set here, all animation effects will be cancelled. It is equivalent to that the animation is false.
    
    // There are also some configurations of animation control, which can be referred to the official documents.
}

API

The API s provided by ecahrts can be divided into four categories.

  • ecahrts: Global ecarts object
  • Echartsinstance: ecahrts instance, that is, the object returned by init
  • Action: Chart behavior supported in echarts
  • Event: event in ECharts

echarts

The global ecarts object is obtained after the script tag is imported into the ecarts.js file, or through the import module.

init

Create an ecarts instance and return an ecarts instance. You cannot initialize multiple ecarts instances on a single container.

init(Container node, theme, chart width and height)  
// Of the three parameters, only the first is required

connect

connect is an API exposed by ecarhts, which can associate multiple charts.

Because a container registers a chart instance. If multiple charts need to be displayed and cannot be merged, they will become separate pieces.

If we want to click to download as an image, or refresh the chart at the same time, it will be a little troublesome. connect can solve this problem.

import {connect} from 'ecahrts'

// Set the group id of each instance separately. You need to set the same id for the associated chart
chart1.group = 'group1';
chart2.group = 'group1';
connect('group1');

// Or you can directly pass in the instance array that needs linkage
connect([chart1, chart2]);

disconnect

Disassociate connect. The parameter is the associated group id.

import {disconnect} from 'ecahrts'
disconnect(groupid)

dispose

dispose is to destroy the instance. It destroys the chart and destroys the instance. At this time, resetting the option is invalid. It is different from the API of another clear.

import {dispose} from 'ecahrts'

dispose(myEchart)  // Parameters are icon instances or container nodes

use

Use components to cooperate with new on-demand interfaces. It needs to be used before init.

// We introduce the core module of ecarts, which provides the necessary interface for the use of ecarts.
import * as echarts from 'echarts/core';
// The histogram Chart is introduced, and the suffix of the Chart is Chart
import {
    BarChart
} from 'echarts/charts';
// Rectangular coordinate system components are introduced, and the suffix of components is Component
import {
    GridComponent
} from 'echarts/components';
// When introducing the Canvas renderer, note that introducing the Canvas renderer or SVGRenderer is a necessary step
import {
    CanvasRenderer
} from 'echarts/renderers';

// Register required components
echarts.use(
    [GridComponent, BarChart, CanvasRenderer]
);

registerMap

Register the map. After obtaining the SJON data of the map, register the map globally.

import {registerMap} from 'ecahrts'
registerMap('mapName',mapJsonValue)

echartsInstance

API on icon instance

group

Grouping of charts for connect ion

let myChart = init(document.querySelector(".con"))

mtChart.group = 'String'  // group id .   The value is a string for linkage

setOption

chart.setOption(option, notMerge, lazyUpdate);

  • option: Chart configuration
  • notMerge: the value is Boolean, and the default is false. That is, the new option is merged with the old option. If set to true, the new option will completely replace the old option
  • lazyUpdate: Select. Whether to not update the chart immediately after setting the option. The default value is false, that is, synchronize and update immediately. If true, the chart will be updated in the next animation frame
myChart.setOption(option)

The setOption parameter has a lot to write. But the commonly used one is actually option

resize

Recorded in the container and container size section.

clear

Clear the current chart, but the instance still exists after clearing. You can also reset the option.

Chart instances also have a dispose method, which directly destroys the instance without parameters.

action

Chart behaviors supported in ECharts are triggered through dispatchAction. Some events triggered manually can be simulated.

dispatchAction is a method on a chart instance. It is here because it mainly serves action.

Chart behavior is to click a part of the icon to highlight it, hover it, or switch the chart type, zoom, and so on

The following is an example. You can view the document for more examples. The method of use is similar.

// To highlight a series:
dispatchAction({
    // Specify type
    type: 'highlight',

    // Use index or id or name to specify the series    
    seriesIndex:0      //  Represents the first chart in the series
    // You can also use arrays to specify multiple series.
   // seriesId?: string | string[],
   // seriesName?: string | string[],

    // If you do not specify the index of the data item, you can also specify the data item by name through the name attribute
    dataIndex?: number | number[],
               
    // Optional, data item name, ignored when there is dataIndex
    name?: string | string[],
});

event

event events are functions that execute when certain events are triggered. action is the corresponding style change of the chart after some chart behaviors occur.

event includes some DOM events, such as click ing, mouse entering mouseover and other mouse events.

There are also some custom events of ecahrts, such as highlight event, event triggered when the data selection status changes, and so on.

These events are monitored through the on method of the instance, which is equivalent to an event listener. The on method is also an example of a chart.

myChart.on('Event type',Callback function)
 // Event type, click, highlight, selectchange, etc
 // The callback function will receive a parameter with some data of the event

The off method can cancel listening to events.

myChart.off('Event type',Callback function)
// The event type is to cancel the event listening on the instance
// The callback function does not have to be passed. If it is not passed, the event bound on this type will be cancelled.

Tags: Front-end echarts

Posted on Wed, 24 Nov 2021 16:28:08 -0500 by jervo