React imports Echarts charts on demand

1. Install Echarts

Echarts official website: https://echarts.apache.org/handbook/zh/basics/download/
npm install echarts --save 或 yarn add echarts

2. Basic examples

Find the legend you need for your project in the Echarts example location, address: https://echarts.apache.org/examples/zh/index.html#chart-type-scatter This example is a basic example and can be performed
through the Echats configuration item manual Chart modifications
Insert image description here

3. React project import

1. Version configuration
The relevant construction framework used in this case is vite + axios + react + sass. Problems may sometimes occur in the version. Therefore, the relevant version number is also written out here to explain, to avoid being confused by the version. An error occurred

{
  "name": "vite-react",
  "version": "0.0.0",
  "scripts": {
    "dev": "vite",
    "build": "vite build",
    "serve": "vite preview"
  },
  "dependencies": {
    "antd": "^4.16.13",
    "axios": "^0.24.0",
    "crypto": "^1.0.1",
    "crypto-js": "^4.1.1",
    "echarts": "^5.2.2",
    "js-md5": "^0.7.3",
    "pubsub-js": "^1.9.4",
    "react": "^17.0.0",
    "react-dom": "^17.0.0",
    "react-router-dom": "^5.2.0",
    "node-sass": "^4.14.1",
    "sass": "^1.43.4"
  },
  "devDependencies": {
    "@vitejs/plugin-react": "^1.0.0",
    "vite": "^2.6.4"
  }
}

2. Echarts import.
Directly copy the code in the red box in the picture below into the project.
Insert image description here
3. The project actually imports
a new react component and names it xxxEcharts.jsx (the suffix is ​​.tsx if using typescript). You need to use react here. Life cycle function. If you are using a class component, you can directly copy the code into the componentDidMount() hook function of the class component. For specific usage methods, please refer to the react life cycle hook function. It is recommended to use functional components, in terms of performance
. It will be better. The
following source code example is jsx sample code, and the components used are functional components.

import React from 'react';
import axios from 'axios';
import * as echarts from 'echarts/core';
import {
    
    
  TimelineComponent,
  TitleComponent,
  TooltipComponent,
  GridComponent,
  VisualMapComponent
} from 'echarts/components';
import {
    
     ScatterChart } from 'echarts/charts';
import {
    
     UniversalTransition } from 'echarts/features';
import {
    
     CanvasRenderer } from 'echarts/renderers';

echarts.use([
  TimelineComponent,
  TitleComponent,
  TooltipComponent,
  GridComponent,
  VisualMapComponent,
  ScatterChart,
  CanvasRenderer,
  UniversalTransition
]);

import '../EchartsGlobal.sass'//本地的sass文件,作用是设置图表的大小

export default function ChartsScatter () {
    
    
  React.useEffect(() => {
    
    
    var ROOT_PATH =
      'https://cdn.jsdelivr.net/gh/apache/echarts-website@asf-site/examples';

    var chartDom = document.getElementById('scatter');
    var myChart = echarts.init(chartDom);
    var option;

    myChart.showLoading();
    axios.get(ROOT_PATH + '/data/asset/data/life-expectancy.json').then( response =>{
    
    
      var data = response.data
      myChart.hideLoading();
      var itemStyle = {
    
    
        opacity: 0.8
      };
      var sizeFunction = function (x) {
    
    
        var y = Math.sqrt(x / 5e8) + 0.1;
        return y * 80;
      };
      // Schema:
      var schema = [
        {
    
     name: 'Income', index: 0, text: '人均收入', unit: '美元' },
        {
    
     name: 'LifeExpectancy', index: 1, text: '人均寿命', unit: '岁' },
        {
    
     name: 'Population', index: 2, text: '总人口', unit: '' },
        {
    
     name: 'Country', index: 3, text: '国家', unit: '' }
      ];
      option = {
    
    
        baseOption: {
    
    
          timeline: {
    
    
            axisType: 'category',
            orient: 'vertical',
            autoPlay: true,
            inverse: true,
            playInterval: 1000,
            left: null,
            right: 0,
            top: 20,
            bottom: 20,
            width: 55,
            height: null,
            symbol: 'none',
            checkpointStyle: {
    
    
              borderWidth: 2
            },
            controlStyle: {
    
    
              showNextBtn: false,
              showPrevBtn: false
            },
            data: []
          },
          title: [
            {
    
    
              text: data.timeline[0],
              textAlign: 'center',
              left: '63%',
              top: '55%',
              textStyle: {
    
    
                fontSize: 100
              }
            },
            {
    
    
              text: '各国人均寿命与GDP关系演变',
              left: 'center',
              top: 10,
              textStyle: {
    
    
                fontWeight: 'normal',
                fontSize: 20
              }
            }
          ],
          tooltip: {
    
    
            padding: 5,
            borderWidth: 1,
            formatter: function (obj) {
    
    
              var value = obj.value;
              // prettier-ignore
              return schema[3].text + ':' + value[3] + '<br>'
                + schema[1].text + ':' + value[1] + schema[1].unit + '<br>'
                + schema[0].text + ':' + value[0] + schema[0].unit + '<br>'
                + schema[2].text + ':' + value[2] + '<br>';
            }
          },
          grid: {
    
    
            top: 100,
            containLabel: true,
            left: 30,
            right: '110'
          },
          xAxis: {
    
    
            type: 'log',
            name: '人均收入',
            max: 100000,
            min: 300,
            nameGap: 25,
            nameLocation: 'middle',
            nameTextStyle: {
    
    
              fontSize: 18
            },
            splitLine: {
    
    
              show: false
            },
            axisLabel: {
    
    
              formatter: '{value} $'
            }
          },
          yAxis: {
    
    
            type: 'value',
            name: '平均寿命',
            max: 100,
            nameTextStyle: {
    
    
              fontSize: 18
            },
            splitLine: {
    
    
              show: false
            },
            axisLabel: {
    
    
              formatter: '{value} 岁'
            }
          },
          visualMap: [
            {
    
    
              show: false,
              dimension: 3,
              categories: data.counties,
              inRange: {
    
    
                color: (function () {
    
    
                  // prettier-ignore
                  var colors = ['#51689b', '#ce5c5c', '#fbc357', '#8fbf8f', '#659d84', '#fb8e6a', '#c77288', '#786090', '#91c4c5', '#6890ba'];
                  return colors.concat(colors);
                })()
              }
            }
          ],
          series: [
            {
    
    
              type: 'scatter',
              itemStyle: itemStyle,
              data: data.series[0],
              symbolSize: function (val) {
    
    
                return sizeFunction(val[2]);
              }
            }
          ],
          animationDurationUpdate: 1000,
          animationEasingUpdate: 'quinticInOut'
        },
        options: []
      };
      for (var n = 0; n < data.timeline.length; n++) {
    
    
        option.baseOption.timeline.data.push(data.timeline[n]);
        option.options.push({
    
    
          title: {
    
    
            show: true,
            text: data.timeline[n] + ''
          },
          series: {
    
    
            name: data.timeline[n],
            type: 'scatter',
            itemStyle: itemStyle,
            data: data.series[n],
            symbolSize: function (val) {
    
    
              return sizeFunction(val[2]);
            }
          }
        });
      }
      myChart.setOption(option);
    })
    // function (data) {
    
    
    // });

    option && myChart.setOption(option);
  })

  return (
    <div className='echarts'>
      <div id="scatter" className='chart'></div>
    </div>
  )
}

4. Basic display of charts

Insert image description here

Guess you like

Origin blog.csdn.net/weixin_51033461/article/details/124141377