preface

I have been working as an intern for more than a month. I am responsible for the page writing of the measurement module in the department, and the technology mainly involved is Echatrs. Up until now, I had only dabled with Data visualization in Python, not Echarts. This article takes you through Echarts step by step, starting with the presentation requirements of diagrams and using the various requirements diagrams of columnar stacked diagrams as examples

Introduction to Echarts

1 installation

  • (1) inputnpm install echartsThe installation
  • ② Then introduce it globally in main.jsimport echarts from "echarts".Vue.prototype.$echarts = echartsAdd the above two lines of code

How to use Echarts in VUE

2.1 Given an area

Give a region in

<div id="myChart1" :style="{width: '100%', height: '700px'}"></div>
Copy the code

2.2 Write a method in Methods

drawImg1() {
    // Initializes the echarts instance based on the prepared DOM
    let myChart1 = this.$echarts.init(
        document.getElementById("myChart1"));// Draw a diagram
    myChart1.setOption({

    });
},
Copy the code

SetOption to write the official example, the official sample linkOfficial column stack diagram So let me just copy that, and the code looks like this

  drawImg1() {
        // Initializes the echarts instance based on the prepared DOM
        let myChart1 = this.$echarts.init(
            document.getElementById("myChart1"));// Draw a diagram
        myChart1.setOption({
			tooltip: {
            trigger: 'axis'.axisPointer: {            // Axis indicator. Axis trigger works
                  type: 'shadow'        / / the default value is linear, optional: 'the line' | 'shadow'}},legend: {
                data: ['Direct access'.'Email marketing'.'Affiliate advertising'.'Video advertising'.'Search engines']},grid: {
                left: '3%'.right: '4%'.bottom: '3%'.containLabel: true
            },
            xAxis: {
                type: 'value'
            },
            yAxis: {
                type: 'category'.data: ['Monday'.'on Tuesday'.'on Wednesday'.'on Thursday.'on Friday'.'on Saturday.'Sunday']},series: [{name: 'Direct access'.type: 'bar'.stack: 'total'.label: {
                        show: true.position: 'insideRight'
                    },
                    data: [320.302.301.334.390.330.320] {},name: 'Email marketing'.type: 'bar'.stack: 'total'.label: {
                        show: true.position: 'insideRight'
                    },
                    data: [120.132.101.134.90.230.210] {},name: 'Affiliate advertising'.type: 'bar'.stack: 'total'.label: {
                        show: true.position: 'insideRight'
                    },
                    data: [220.182.191.234.290.330.310] {},name: 'Video advertising'.type: 'bar'.stack: 'total'.label: {
                        show: true.position: 'insideRight'
                    },
                    data: [150.212.201.154.190.330.410] {},name: 'Search engines'.type: 'bar'.stack: 'total'.label: {
                        show: true.position: 'insideRight'
                    },
                    data: [820.832.901.934.1290.1330.1320]}}); },Copy the code

Above code, suggest beginners or in the official instance website to change their own, observe the chart changes. It helps to understand the official column stack diagram

2.3 Mounted (

mounted(){
	this.drawImg1()
}
Copy the code

In this way, one of our official samples is rendered on the page.

3 Simple Requirements

A rendering of the requirements is shown below

3.1 Analyzing Requirements

Compare the difference between the demand effect drawing and the official sample drawing

  • (1) First see the above button, the data must be selected according to the user to dynamically obtain from the back end and then render the drawing
  • ② The direction of X-axis and Y-axis is reversed from the official sample drawing
  • ③ Supervisor added requirements: add a button that can switch data view and download picture as shown in figure

  • ④ There are two more lines, and the lines should display the percentage of data, rather than directly display the data
  • ⑤ The color of the bar chart
  • ⑥ There are y axes on both sides of the demand effect map, that is, there are two Y axes, and the column corresponds to the y axis data on the left, and the broken line corresponds to the Y axis data on the right
  • ⑦ Display color of data on bar chart and line chart
  • ⑧ Supervisor increase demand: when the horizontal axis data volume is too large, you can zoom in and out of the horizontal axis, so that the data of a certain area can be clearly displayed

3.2 Fulfill requirements

You can take a look at the finished image belowSee the instructions and comments in the code below for details of the completion process and the stamping process.

  • 1.”Point on pitWhen obtaining dynamic data, I switched different selection buttons, and then re-obtained data from the back end. When rendering again, I found that some data were wrong, and some data in the new picture was brought from the old one, which led to the supervisor telling me that the data was wrong. I searched and found out that Echarts has a caching function, and some data will be retained and carried to the next image if it is not reassigned. So I found that I had tosetOptionwithmyChart1.clear();This line clears the code for the diagram that has been drawn
  • 【 Requirement 】 button control logic. We can useVuethewatchListen for changes in the value of the button, after which a method to retrieve data from the back end is executeddrawImg1()Method to re-render
  • ③ [Completion requirements] The direction of X-axis and Y-axis is reversed from the official sample drawing. This is easy to solve, we will directly official samplexAxistoyAxis.yAxistoxAxisThis is good, the specific logic can try to modify the code to understand
  • ④ add the button that can switch data view and download picture button. The echarts package already comes with this functionality, so we can add the code and write it in the following codetoolbox
  • ⑤ There are two more lines, and the line should display the percentage of data, rather than directly display the data. This is also easy. We just need to be inseriesAdd two control polyline objects to the code belowseriesYou can see the details at the end, as for the presentation data displayed as a percentage, this should be usedformatterTo control the
  • ⑥ The color of the bar chart. This is available in every oneseriesObject passed separatelycolorTo set the controls, default to the random color of the official column stack instance if you don’t use it
  • Demand diagram on both sides of the y axis, that is, there are two Y axis, and the column corresponding to the left of the Y axis data, broken line corresponding to the right of the Y axis data. weyAxisWrite two objects, one controls the left y axis and one controls the right y axis, just changepositiontheleftorrightOk, so we have two y-axes. And then we have to control that the bar corresponds to the y axis on the left, and the polyline corresponds to the y axis on the right, becauseyAxisIt’s an array, which by default corresponds to the first Y-axis, so we’re inseriesTo a polyline objectyAxisIndex: 1This corresponds to the percentage Y-axis on the right, as shown at the end of the code belowseriesObject code
  • Display color of data on bar chart and line chart. This is inseriesthelabelthetextStylethecolorCan be written to
  • When there is too much data in the horizontal axis, you can zoom in and out of the horizontal axis to clearly display the data in a certain area. Plus the following codedataZoomThe specific control logic is explained in the notes
 drawImg1() {
      // Initializes the echarts instance based on the prepared DOM
      let myChart1 = this.$echarts.init(
          document.getElementById("myChart1")); myChart1.clear();// It is better to add this line of code to avoid data rendering errors caused by dynamic switching ICONS
      // Draw a diagram
      myChart1.setOption({
          title: { text: "Custom version" },  // The title at the top left of the chart
          tooltip: {
              trigger: "axis".axisPointer: {
                  // Axis indicator. Axis trigger works
                  type: "shadow"./ / default is linear, optional: 'the line' | 'shadow', his switch to put the mouse on data view, indicator change can be observed, the shadow is usually recommended more beautiful}},toolbox: {	// Here is the button to control the upper right corner, can switch data display view, quite useful, suggested to add
              show: true.feature: {
                  // Control whether the data view appears to display data
                  dataView: {
                      show: true.readOnly: false,},// Save the image button, there are other buttons in the official document, you can see by yourself
                  saveAsImage: { show: true}},},legend: {
          	  // Here controls the upper legend, because the legend of the modification is relatively fixed, so I do not use dynamic data, directly write here
              data: [
                  "Unapplied release amount of version"."Release success"."Release failures"."Release success rate"."Application rate",]},grid: {
              left: "3%".right: "4%".bottom: "10%".// Controls the position of the drag bar at the bottom. If this is not changed, the drag bar will affect the data view with the default value of bottom
              containLabel: true,},yAxis: [{type: "value".position: "left".// On the left, the first Y-axis controls the display position
              },
              {
                  type: "value".position: "right".// The second Y-axis
                  axisLabel: {
                      formatter: "{value}%".// Control the format of the Y-axis interval display data
                  },
                  splitLine: {
                      show: false.// Control whether each interval has a dividing line}},].xAxis: {
              type: "category".data: this.Img1xAxisData, DrawImg1 (); drawImg1(); drawImg1(); drawImg1()
          },
          // dataZoom to control whether the data can be enlarged and reduced
          dataZoom: [{type: "inside".// Add this inside, that is, you can place the mouse on the data view, and then use the mouse wheel to scroll up and down to zoom in and out of the X axis. You can delete the specific difference and compare it with adding this line of code. Without this line, you can only control the X-axis up and down by scrolling down the drag bar
              },
              {
                  start: 0.end: 10.handleIcon:
                      "M10.7, 11.9 v - 1.3 H9.3 v1.3-4.9 c, 0.3-8.8, 4.4, 8.8, 9.4 c0, 5,3.9, 9.1, 8.8, 9.4 v1.3 c4.9 h1.3 v - 1.3-0.3, 8.8, 4.4, 8.8 9.4 C19.5, 16.3, 15. ,12.2 6, 10.7, 11.9 z M13.3, 24.4 H6.7 V23h6. 6 v24. 4 z M13.3 H6.7 19.6 v - 1.4 - h6.6 V19.6 z".handleSize: "80%".handleStyle: {
                      color: "#fff".shadowBlur: 3.shadowColor: "Rgba (0, 0, 0, 0.6)".shadowOffsetX: 2.shadowOffsetY: 2,}},// This controls the drag bar style, generally this does not need to change].series: [{name: "Unapplied release amount of version".// Name will be controlled according to legend. It can not be filled out randomly, and it should be made dynamic later
                  type: "bar".// Line is a broken line
                  stack: "Total".color: ["#ff9933"].// Control column color
                  label: {
                      show: true.// Control whether the display data is displayed in the column
                      position: "inside".// Control the position of tactical data in the column. It can be inside, top, insideRight
                      textStyle: {  // Control the format of data in the column
                          // fontWeight: "bolder", // bold
                          fontSize: "12".// Font size
                          color: "# 141414".// Font color}},data: this.Img1unpublishversion,
              },
              {
                  name: "Release success".type: "bar".stack: "Total".color: ["#ffff99"].label: {
                      show: true.position: "inside".textStyle: {
                          // fontWeight: "bolder",
                          fontSize: "12".color: "# 141414",}},data: this.Img1successversion,
              },
              {
                  name: "Release failures".type: "bar".stack: "Total".color: ["#3333ff"].label: {
                      show: true.position: "inside".textStyle: {
                          // fontWeight: "bolder",
                          fontSize: "12".color: "# 141414",}},data: this.Img1failversion,
              },
              {
                  name: "Release success rate".type: "line"./ / line
                  stack: "".// This field must be empty, cannot correspond to the total
                  symbolSize: 10.// Inflection point size
                  yAxisIndex: 1.// Corresponds to the second Y-axis
                  lineStyle: {
                      Color: "#66cc33", // change the line color
                      width: 2.// Change the line thickness
                  },
                  itemStyle: {
                      normal: {
                          label: {
                              show: true.// The line chart shows whether the numbers are correct or not
                              formatter: "{c}%".// Customize data value plus percentage to control display data format}},},data: this.Img1successpercent,
              },
              {
                  name: "Application rate".type: "line".stack: "".symbolSize: 10.// Inflection point size
                  yAxisIndex: 1.lineStyle: {
                      color: "#3366cc".width: 2.// Change the line color
                  },
                  itemStyle: {
                      normal: {
                          label: {
                              show: true.formatter: "{c}%".// Custom data value plus percentage}},},data: this.Img1failpercent,
              },
          ],
      });
  },
Copy the code

After reading the code and comments above, you should be able to grasp the basics

4. Advanced demand

In fact, the real hard part is later, because the data is still very small, our objects are written manually, but if we have a lot of objects, do you want toseriesTo add objects one by one? And every time I get new data,seriesThe object is also different, so obviously we need a dynamic oneseries. I’m not going to show you what the new requirements diagram looks like, I’m going to show you the finished diagram. Just like the figure below, there is a lot of data on each column. For each additional legend data, we need one moreseries, so we need to write dynamicallyseries

4.1 Analyzing Requirements

Compare and contrast this new diagram with the first finished diagram above

  • ① Legend, there are many objects on each column
  • ② The text on the left y axis is blue and a small distance from the data view
  • ③ Legends are at the bottom of the data view
  • ④ There is a total number on the far right of each column
  • 5.dataZoomOn the right

4.2 Completing Requirements

  • ① Can not write one by one, because it is dynamic, so we need to write a method dynamic willseriesTo join. So I thought about this for a long time and I didn’t know what to do with it, but then I thought about how to store the data that I get directly from the back end, rightdataAnd then I was incomputedWrite a method according todataTo dynamically return oneseriesObject array, which is then rendered into the data view, as shown in the following codecomputedIn the view
  • The text on the left y axis is blue, and there is a small distance from the data view. inyAxisaddaxisLabelAnd then usetextStyleTo control the text style,mariginTo control the distance of text from the data view
  • Legends are at the bottom of the data view. inlegendaddy: "bottom"
  • ④ there is a total value on the right side of each column. Add a total valueseriesObject, specified in the following codecomputedIn the view. Specific different implementation method referenceThe echarts stack histogram shows the sum at the top
  • ⑤【 Fulfill requirements 】dataZoomOn the right. Because in this picture, the X-axis goes to the left, so it becomes the Y-axis, so we’re atdataZoomAdd two lines to theyAxisIndex: 0, so that the scroll bar corresponds to the left Y-axis, see the code and comments below
   drawImg2() {
      // Initializes the echarts instance based on the prepared DOM
      let myChart2 = this.$echarts.init(
          document.getElementById("myChart2")); myChart2.clear();// Draw a diagram
      myChart2.setOption({
          tooltip: {
              trigger: "axis".axisPointer: {
                  // Axis indicator. Axis trigger works
                  type: "shadow"./ / the default value is linear, optional: 'the line' | 'shadow'}},toolbox: {
              show: true.feature: {
                  // Controls whether the data view appears
                  dataView: {
                      show: true.readOnly: false,},saveAsImage: { show: true}},},legend: {
              data: this.Img2Legend, // Dynamically get legend data from the back end
              y: "bottom".// Control legend is at the bottom
          },
          grid: {
              left: "3%".right: "4%".bottom: "10%".// Control the position of the bottom drag bar
              containLabel: true,},xAxis: [{type: "value".position: "left"],},yAxis: {
              type: "category".data: this.Img2xAxiasData,
              axisLabel: {
              	  // interval: 0,
                  Rotate: 30 controls the text Angle
                  textStyle: {
                      color: "#3399ff",}// The style of the axis scale
                  margin: 20.// Control the distance between text and data view}},dataZoom: [{type: "inside".yAxisIndex: 0.// In this case, the graph is on the right side, corresponding to the left y axis
              },
              {
                  start: 0.end: 10.handleIcon:
                      "M10.7, 11.9 v - 1.3 H9.3 v1.3-4.9 c, 0.3-8.8, 4.4, 8.8, 9.4 c0, 5,3.9, 9.1, 8.8, 9.4 v1.3 c4.9 h1.3 v - 1.3-0.3, 8.8, 4.4, 8.8 9.4 C19.5, 16.3, 15. ,12.2 6, 10.7, 11.9 z M13.3, 24.4 H6.7 V23h6. 6 v24. 4 z M13.3 H6.7 19.6 v - 1.4 - h6.6 V19.6 z".handleSize: "80%".handleStyle: {
                      color: "#fff".shadowBlur: 3.shadowColor: "Rgba (0, 0, 0, 0.6)".shadowOffsetX: 2.shadowOffsetY: 2,},yAxisIndex: 0.// In this case, the graph is on the right side, corresponding to the left y axis},].series: this.Img2series, // Dynamically add a series object, see the code below
      });
  },
Copy the code

Above is the method for this data view. For a series dynamic data code in computed, see the code below

computed:{
	Img2series: function () {
        let Arr = [];
        let Img2sumData = [];
        let sum = 0;
        if (this.Img2yAxiasEndData.length) {
        	Img2yAxiasEndData if(this.img2yaXiasendData) {// If (this.img2yaXiasendData) {// If (this.img2yaXiasendData) {// If (this.img2yaXiasendData)
            for (let j = 0; j < this.Img2yAxiasEndData[0].length; j++) {
                sum = 0;
                for (let i = 0; i < this.Img2yAxiasEndData.length; i++) {
                    sum = sum + this.Img2yAxiasEndData[i][j]; } Img2sumData.push(sum); }}// Add total values
        Arr.push({
            name: "Total".type: "bar".barGap: "100%".// This is the key, because the total is actually an additional transparent bar graph object superimposed on the original graph
            label: {
                normal: {
                    show: true.position: "right".formatter: "A total {c}".textStyle: { color: "# 000"}},},itemStyle: {
                normal: {
                    color: "rgba(128, 128, 128, 0)"./ / transparent}},data: Img2sumData,
        });
        if (this.Img2Sixvalue === "By audit code") { // Button control logic
        	// iterate to add series
            for (let i = 0; i < this.Img2Legend.length; i++) {
                Arr.push({
                    name: this.Img2Legend[i], // The corresponding number of legends
                    type: "bar".stack: "Total".label: {
                        show: true.position: "inside".textStyle: {
                            fontSize: "12".color: "# 141414",}},data: this.Img2yAxiasEndData[i], // The corresponding group of data}); }}else {
            this.Img2Legend.push("Total");
            Arr.push({
                name: "Total".type: "bar".stack: "Total".color: ["#3399ff"].label: {
                    show: true.position: "inside".textStyle: {
                        fontSize: "12".color: "# 141414",}},data: Img2sumData,
            });
        }
        return Arr; // Return the array, and the series in drawImg2() will be rendered}},Copy the code

conclusion

After using Echarts, I really feel that Echarts is a very powerful visual icon library, just like the epidemic map at the beginning of the year, which is also displayed through Echarts. It is a very intuitive way to display, and I have made one myself, as shown in the figure (the figure is virtual data, for reference only).This article will only get you started, but if you want to really play with Echarts, you’ll have to read the official documentation and try to modify it based on examples

At the end of the article

If you think my writing is good, you can give me a thumbs up. If there is anything wrong or bad, please comment and point out so that I can correct it. (This series is coming to an end, so you can review the previous ones, and I will update some other ones. Please stay tuned.)

Other articles

  • ⑥ — Performance optimization, Web security, common Linux commands
  • 5. Front-end basics — Http, Ajax, cross-domain
  • Front end basics ④ – events and DOM
  • ③ Asynchronous (Interview scenario)
  • Front End Basics ② — Scopes and closures
  • Front end basic knowledge ① — CSS interview questions