Vue+Echarts draws K-line chart (2)--time-sharing chart and transaction volume chart

1 Introduction

Recently, it has been discovered that the Echarts API has become more and more powerful. Echarts can be used to draw various graphics. Bar charts, pie charts, line charts, and polar coordinate charts have been introduced before. For the K-line chart, in addition to the detailed explanation of drawing K-line charts with vue+Echarts (1) - basic daily K-line drawing introduced earlier , the K-line chart contains many other types of graphics. After taking a break for about half a year, today Let’s continue to introduce the time-sharing chart and the trading volume chart in depth to contribute to the creation of a complete layout.

2 time chart

2.1 vue introduces Echarts

It has been introduced before. If you still don’t know how to introduce it, please refer to the previous tutorial: Introducing ECharts into the Vue project .

2.2 Introduction to time-sharing chart

The time-sharing chart is essentially a line chart. The horizontal axis is each minute of trading in a day, and the vertical axis is the real-time unit price of the stock market. In addition to realizing these two basic functions, you also need to bring a per-minute trading volume chart. When the mouse is placed on the chart, the relevant data corresponding to the current time must be displayed; as shown in the following figure:
Insert image description here

The functions we want to implement in this issue are: time-sharing line chart, time-sharing trading volume chart, mouse pointer to display detailed data, corresponding to trading volume color division; other detailed functions (chart switching, detail color and style processing) we will discuss later Let me introduce again.

2.3 Time-sharing line chart configuration

The time-sharing line chart is essentially a line chart. We can set the chart type to line. The focus is on data processing. Our data source format is object jsonarray data. The data for each minute is as follows:

  {
    
    "time":"1678411800","price":"3255.51","ratio":"-0.63%","increase":"-20.58","volume":"2925368","avgPrice":"3261.35","amount":"29.00\u4ebf","timeKey":"0930","datetime":"03-10 09:30","oriAmount":"2900320446","show":"1"},

First we need to process the data before it can be applied to Echarts; our time-sharing line chart configuration item code is as follows:

 // 横坐标数据配置
        xAxis: [
          {
    
    
            type: "category",
            data: this.xData,
            boundaryGap: false,
            axisLine: {
    
     onZero: false },
            splitLine: {
    
     show: false },
            min: "dataMin",
            max: "dataMax"
          },
        ]
// 纵坐标配置
        yAxis: [
          {
    
    
            scale: true,
            splitArea: {
    
    
              show: true
            }
          },
        ]
//图形数据配置:
		series: [
          {
    
    
            type: "line",
            data: this.hourData,
            symbol: "none", //无标记图案
            lineStyle: {
    
    
              width: 1
            }
          },
        ]

Among them, this.xDatait is the processed abscissa data in our vue page, and this.hourDatait is the processed hourly data in our page.

Note: seriesThe middle symbolattribute should be set to none, so that there will be no line mark pattern on the line chart.

The data processing code is as follows:

    // 横坐标数据处理
    initxData() {
      for (let i = 0; i < this.klineData.length; i++) {
        this.xData[i] = this.klineData[i].datetime;
      }
    },
        // 数据计算以及拆分,将json数据转为数组数据
    splitData(jsonData) {
      const hourData = [];
      for (let i = 0; i < jsonData.length; i++) {
        hourData.push([
          i,
          jsonData[i].price,
          jsonData[i].increase,
          jsonData[i].volume,
          jsonData[i].ratio,
          jsonData[i].amount,
          jsonData[i].datetime
        ]);
      }
      return hourData;
    }

Among them, this.klineDatait is the json data introduced by our page.

At this point we can take a look at the effect of the time-sharing line chart:

Insert image description here

You can see that the obtained line chart is our time-sharing line chart.

2.4 Combination volume chart

The trading volume chart is a bar chart between red and green at the bottom of Figure 2.2. The trading volume chart is essentially a bar chart. We can see that it has two characteristics:

  1. The abscissa is common to the time-sharing line chart, and the histogram is below the trading chart;
  2. When the current price is rising, the column is red; when the current price is falling, the column is green;

Regarding feature 1, the pictures we introduced before are all in a common coordinate system. The new knowledge point here is that the coordinate system is not shared, but how should the common abscissa data be processed? That is to set two objects in , xAxisand yAxis. seriesrepresents two different coordinates, and then align the abscissas of the two coordinate systems;

code show as below:

// 横坐标数据
        xAxis: [
          // 折线图
          {
    
    
            type: "category",
            data: this.xData,
            boundaryGap: false,
            axisLine: {
    
     onZero: false },
            splitLine: {
    
     show: false },
            min: "dataMin",
            max: "dataMax"
          },
          // 柱状图
          {
    
    
            type: "category",
            gridIndex: 1, //x 轴所在的 grid 的索引,默认位于第一个 grid。
            data: this.xData,
            boundaryGap: false,
            axisLine: {
    
     onZero: false },
            axisTick: {
    
     show: false },
            splitLine: {
    
     show: false },
            axisLabel: {
    
     show: false },
            min: "dataMin",
            max: "dataMax"
          }
        ],
        // 纵坐标配置
        yAxis: [
          {
    
    
            scale: true,
            splitArea: {
    
    
              show: true
            }
          },
          {
    
    
            scale: true,
            gridIndex: 1, // y 轴所在的 grid 的索引,默认位于第一个 grid
            splitNumber: 2,
            axisLabel: {
    
     show: false },
            axisLine: {
    
     show: false },
            axisTick: {
    
     show: false },
            splitLine: {
    
     show: false }
          }
        ],
         series: [
          {
    
    
            type: "line",
            data: this.hourData,
            symbol: "none", //无标记图案
            lineStyle: {
    
    
              width: 1
            }
          },
          {
    
    
            name: "Volume",
            type: "bar",
            xAxisIndex: 1,
            yAxisIndex: 1,
            data: this.culomnValue
          }
        ]   

For feature 2, to control the different colors of each histogram, we need to use visualMap.piecesattributes; the description of this attribute on the official website is: customize the range of each segment of the "segmented visual mapping component (visualMapPiecewise)", and the text, and a unique style for each paragraph.

Let’s go directly to the code and explanation to see how to use this attribute. The code is as follows:

 		visualMap: {
    
    
          type: "piecewise",
          show: false, //不展示map,只应用对应颜色划分逻辑
          seriesIndex: 1, //指定取哪个系列的数据
          dimension: 2,
          // 定义每一段的颜色
          pieces: [
            {
    
    
              value: -1,
              color: this.downColor
            },
            {
    
    
              value: 1,
              color: this.upcolor
            }
          ]
        },

The explanation of this code is: when seriesthere isdata a value in the data , use , when , use .value==-1colorthis.downColorvalue==1colorthis.upcolor

At this time, we also need to process the color data and display the growth and decline of the corresponding time period of the K-line chart in the array. The trading volume data processing code is as follows:

    // 初始化交易数据和交易柱状图颜色参数
    initCulomnColor() {
    
    
      this.culomnColor[0] = this.klineData[0].increase > 0 ? 1 : -1;
      this.culomnValue[0] = [0, this.klineData[0].volume, -1];
      for (let i = 1; i < this.klineData.length; i++) {
    
    
        this.culomnColor[i] =
          this.klineData[i].price > this.klineData[i - 1].price ? 1 : -1;
        this.culomnValue[i] = [
          i,
          this.klineData[i].volume,
          this.culomnColor[i]
        ];
      }
    },

At this point, our trading volume histogram can be rendered. The next step is to adjust the positions of the line chart and the histogram, and allocate appropriate areas to the two charts. The code is as follows:

 // 图像位置配置
        grid: [
          {
    
    
            left: "10%",
            right: "10%",
            height: "50%"
          },
          {
    
    
            left: "10%",
            right: "10%",
            top: "65%",
            height: "18%"
          }
        ],

gridConfigure two objects to represent the line chart and bar chart positions respectively;

The renderings we see after fusion are as follows:

Insert image description here

2.5 Mouse indication data setting

The requirement of the K-line chart is that when the mouse is pointed at a certain position on the chart, the detailed data of this time period needs to be displayed; here we need to use the attribute, but this attribute displays the current abscissa and ordinate by default tooltip. value, if we need to configure the displayed data, we also need to use tooltip.formatterattributes to return the data we want to display. This attribute can be expanded to a very wide range. We will not introduce it this time, but only introduce it in the k-line chart. Basic usage. code show as below:

tooltip: {
          trigger: "axis",
          axisPointer: {
            type: "cross" //十字准星指示器
          },
          borderWidth: 1,
          borderColor: "#ccc",
          padding: 10,
          textStyle: {
            color: "#000"
          },
          formatter: function(param) {
            param = param[0];
            return [
              "时间: " + param.data[6] + '<hr size=1 style="margin: 3px 0">',
              "价格: " + param.data[1] + "<br/>",
              "涨跌额: " + param.data[2] + "<br/>",
              "成交量: " + param.data[3] + "<br/>",
              "涨跌幅: " + param.data[4] + "<br/>"
            ].join("");
          }
        },

We display the five attributes: time, price, rise and fall, trading volume, and rise and fall on the page in a simple style. The result is as follows:

Insert image description here

At this point, the drawing of time-sharing line chart and trading volume chart has been basically completed;

2.6 Complete project code

The complete code of the vue project is as follows:

<template>
  <div class="echart" id="mychart" style="width:100%; height: 500px;"></div>
</template>

<script>
import * as echarts from "echarts";
import SZHourData from "./data/hourData.TS";

export default {
      
      
  data() {
      
      
    return {
      
      
      upcolor: "#FF0000", //增长颜色
      upBorderColor: "#8A0000",
      downColor: "#008000", // 下跌颜色
      downBorderColor: "#008F28",
      klineData: [], //k线图数据
      hourData: [], //charts表格小时数据
      xData: [],
      culomnColor: [], //颜色
      culomnValue: []
    };
  },
  mounted() {
      
      
    // 数据初始化
    this.initData();
    // 图标初始化
    this.initEcharts();
  },
  methods: {
      
      
    initData() {
      
      
      this.klineData = SZHourData.priceinfo;
      this.hourData = this.splitData(this.klineData);
      this.initxData();
    },
    initEcharts() {
      
      
      const option = {
      
      
        title: {
      
      
          text: "上证指数",
          left: 0
        },
        tooltip: {
      
      
          trigger: "axis",
          axisPointer: {
      
      
            type: "cross" //十字准星指示器
          },
          borderWidth: 1,
          borderColor: "#ccc",
          padding: 10,
          textStyle: {
      
      
            color: "#000"
          },
          formatter: function(param) {
      
      
            param = param[0];
            return [
              "时间: " + param.data[6] + '<hr size=1 style="margin: 3px 0">',
              "价格: " + param.data[1] + "<br/>",
              "涨跌额: " + param.data[2] + "<br/>",
              "成交量: " + param.data[3] + "<br/>",
              "涨跌幅: " + param.data[4] + "<br/>"
            ].join("");
          }
        },

        visualMap: {
      
      
          type: "piecewise",
          show: false, //不展示map,只应用对应颜色划分逻辑
          seriesIndex: 1, //指定取哪个系列的数据
          dimension: 2,
          // 定义每一段的颜色
          pieces: [
            {
      
      
              value: -1,
              color: this.downColor
            },
            {
      
      
              value: 1,
              color: this.upcolor
            }
          ]
        },
        // 图像位置配置
        grid: [
          {
      
      
            left: "10%",
            right: "10%",
            height: "50%"
          },
          {
      
      
            left: "10%",
            right: "10%",
            top: "65%",
            height: "18%"
          }
        ],
        // 横坐标数据
        xAxis: [
          // 折线图
          {
      
      
            type: "category",
            data: this.xData,
            boundaryGap: false,
            axisLine: {
      
       onZero: false },
            splitLine: {
      
       show: false },
            min: "dataMin",
            max: "dataMax"
          },
          // 柱状图
          {
      
      
            type: "category",
            gridIndex: 1, //x 轴所在的 grid 的索引,默认位于第一个 grid。
            data: this.xData,
            boundaryGap: false,
            axisLine: {
      
       onZero: false },
            axisTick: {
      
       show: false },
            splitLine: {
      
       show: false },
            axisLabel: {
      
       show: false },
            min: "dataMin",
            max: "dataMax"
          }
        ],
        // 纵坐标配置
        yAxis: [
          {
      
      
            scale: true,
            splitArea: {
      
      
              show: true
            }
          },
          {
      
      
            scale: true,
            gridIndex: 1, // y 轴所在的 grid 的索引,默认位于第一个 grid
            splitNumber: 2,
            axisLabel: {
      
       show: false },
            axisLine: {
      
       show: false },
            axisTick: {
      
       show: false },
            splitLine: {
      
       show: false }
          }
        ],
        dataZoom: [
          {
      
      
            type: "inside",
            xAxisIndex: [0, 1],
            start: 50, //展示的数据范围,默认为50%-100%
            end: 100
          },
          {
      
      
            show: true,
            xAxisIndex: [0, 1],
            type: "slider",
            top: "90%",
            start: 50, //展示的数据范围,默认为50%-100%
            end: 100
          }
        ],
        series: [
          {
      
      
            type: "line",
            data: this.hourData,
            symbol: "none", //无标记图案
            lineStyle: {
      
      
              width: 1
            }
          },
          {
      
      
            name: "Volume",
            type: "bar",
            xAxisIndex: 1,
            yAxisIndex: 1,
            data: this.culomnValue
          }
        ]
      };
      const myChart = echarts.init(document.getElementById("mychart"));
      myChart.setOption(option);
      //随着屏幕大小调节图表
      window.addEventListener("resize", () => {
      
      
        myChart.resize();
      });
    },
    // 横坐标数据处理
    initxData() {
      
      
      for (let i = 0; i < this.klineData.length; i++) {
      
      
        this.xData[i] = this.klineData[i].datetime;
      }
      this.initCulomnColor();
    },
    // 初始化交易数据和交易柱状图颜色参数
    initCulomnColor() {
      
      
      this.culomnColor[0] = this.klineData[0].increase > 0 ? 1 : -1;
      this.culomnValue[0] = [0, this.klineData[0].volume, -1];
      for (let i = 1; i < this.klineData.length; i++) {
      
      
        this.culomnColor[i] =
          this.klineData[i].price > this.klineData[i - 1].price ? 1 : -1;
        this.culomnValue[i] = [
          i,
          this.klineData[i].volume,
          this.culomnColor[i]
        ];
      }
    },
    // 数据计算以及拆分,将json数据转为数组数据
    splitData(jsonData) {
      
      
      const hourData = [];
      for (let i = 0; i < jsonData.length; i++) {
      
      
        hourData.push([
          i,
          jsonData[i].price,
          jsonData[i].increase,
          jsonData[i].volume,
          jsonData[i].ratio,
          jsonData[i].amount,
          jsonData[i].datetime
        ]);
      }
      return hourData;
    }
  }
};
</script>

3 Summary

The new attributes introduced this time Echartsare widely used. I wonder if you have realized how echartspowerful they are. If you can integrate various attributes, you will become stronger soon. It should be noted that the above code is for learning reference only. It is not a project-level code. There are various boundary value issues that are not considered, as well as possible compatibility issues. Please be aware of this.

This series of vue+Echarts drawing K-line chart (2) – time-sharing chart and transaction volume chart ends here. We will continue to explore the implementation of other knowledge of K-line chart in the future. If you have any questions, please leave a message.

Guess you like

Origin blog.csdn.net/m0_46309087/article/details/129483500