美文网首页
React-Echarts-通用配置

React-Echarts-通用配置

作者: coderhzc | 来源:发表于2021-11-30 09:51 被阅读0次

Echarts图标通用配置

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

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
  <script src="lib/echarts.min.js"></script>
</head>

<body>
  <div style="width: 600px;height:400px"></div>
  <script>
    var mCharts = echarts.init(document.querySelector("div"))
    var xDataArr = ['张三', '李四', '王五', '闰土', '小明', '茅台', '二妞', '大强']
    var yDataArr1 = [88, 92, 63, 77, 94, 80, 72, 86]
    var yDataArr2 = [93, 60, 61, 62, 85, 79, 92, 30]
    var option = {
      title: {
        text: '成绩展示',
        textStyle: {
          color: 'red'
        },
        borderWidth: 5,
        borderColor: 'blue',
        borderRadius: 5,
        left: 50,
        top: 10
      },
      tooltip: {
        // trigger: 'item'
        trigger: 'axis',
        triggerOn: 'click',
        // formatter: '{b} 的成绩是 {c}'
        formatter: function(arg){
          return arg[0].name + '的分数是:' + arg[0].data
        }
      },
      toolbox: {
        feature: {
          saveAsImage: {}, // 导出图片
          dataView: {}, // 数据视图
          restore: {}, // 重置
          dataZoom: {}, // 区域缩放
          magicType: {
            type: ['bar', 'line']
          } // 动态图表类型的切换
        }
      },
      legend: { // 图例, 图例中的data数据来源于series中每个对象的name, 图例可以帮助我们对图表进行筛选
        data: ['语文', '数学']
      },
      xAxis: {
        type: 'category',
        data: xDataArr
      },
      yAxis: {
        type: 'value'
      },
      series: [
        {
          name: '语文',
          type: 'bar',
          data: yDataArr1
        },
        {
          name: '数学',
          type: 'bar',
          data: yDataArr2
        }
      ]
    }
    mCharts.setOption(option)
  </script>
</body>

</html>

实际截图:

image.png

React 中使用Echarts图表

// html 标签
 <div style={{ display: isShowChart === 1 ? 'block' : 'none' }}>
      {lineChartXDataObj && <div id="line-chart" style={{ width: '100%', height: '330px' }}></div>}
 </div>

// JS
componentDidMount() {
    this.getQueryChartData(); // 折线图数据查询
}

 // 图表查询
  getQueryChartData() {
    axios({
      url: BaseURL + '/data/DutyRecord/dutyStatisticsChart',
      params: {
        dutyPerson: this.state.buttonValue.includes('值班员'),
        dutyLocation: this.state.buttonValue.includes('值班位置'),
        statistics: this.state.queryTypeValue == 1 ? 'count' : 'sum',
        timeGroup: this.state.bottomChangeValue == 2 ? 'month' : 'year',
        sort: '',
        startTime: window.dutyAllStartTime ? moment(window.dutyAllStartTime).format('x') : '',
        endTime: window.dutyAllEndTime ? moment(window.dutyAllEndTime).format('x') : '',
        location: window.dutyAllPosition ? window.dutyAllPosition : '',
        name: window.dutyAllPerson ? window.dutyAllPerson : '',
      },
    }).then(res => {
      const {
        data: { data },
      } = res;
      const newDataLineOrBar = data ? data : {};
      console.log(newDataLineOrBar);
      if (this.state.isShowChart === 1) {
        this.setState(
          {
            lineChartXDataObj: newDataLineOrBar,
          },
          () => this.getLineChart()
        );
      } else {
        this.setState(
          {
            barChartXDataObj: newDataLineOrBar,
          },
          () => this.barChartData()
        );
      }
    });
  }

  // 折线图
  getLineChart() {
    let { num, typeList, dataList } = this.state.lineChartXDataObj;
    let series = [];
    num.forEach((item, index) => {
      series.push({
        name: typeList[index],
        data: item,
        type: 'line',
        smooth: true,
        itemStyle: {
          normal: {
            // color: '#289df5', // 折线条的颜色
            // borderColor: '#289df5', // 拐点边框颜色
            // areaStyle: {
            //   type: '#6186FF',
            //   opacity: 0.1,
            // },
          },
        },
      });
    });
    let lineChart = echarts.init(document.getElementById('line-chart'));
    lineChart.setOption({
      tooltip: {
        trigger: 'axis',
        transitionDuration: 0,
        backgroundColor: '#fff',
        extraCssText: 'max-width:180px !important;white-space:pre-wrap;color:#333;border:1px solid #efefef',
        // show: true,
        formatter: params => {
          let str = '';
          for (let item of params) {
            str += `<span style="line-height: 30px;"><i style="display:inline-block;width:15px;height:15px;background:${
              item.color
            };transform: translateY(3px);margin-right:5px;"></i>${item.seriesName}:${
              this.state.queryTypeValue === 2
                ? Math.floor(item.data / 60) + 'h' + (item.data % 60 <= 0 ? '' : (item.data % 60) + 'min')
                : item.data
            }</span>`;
          }
          return `<div style="display:flex;flex-direction: column;">${params[0].name}<br/>${str}</div>`;
        },
      },
      dataZoom: [
        {
          type: 'inside',
          start: 5,
          end: 95,
        },
        {
          start: 5,
          end: 95,
        },
      ],
      title: {
        text: this.state.queryTypeValue === 1 ? '次数(次)' : '时长(分)', // 标题文字
        textStyle: {
          // 标题样式设置
          color: '#333',
          fontWeight: 'normal',
          fontSize: 14,
        },
        left: 45,
        top: 20,
      },

      //图例
      legend: {
        itemHeight: 14,
        itemWidth: 14,
        icon: 'rect',
        right: 10,
        data: typeList,
      },
      grid: {
        left: '4%',
        right: '2%',
        containLabel: true,
      },
      xAxis: {
        type: 'category',
        data: dataList,
        boundaryGap: false,
      },
      yAxis: {
        type: 'value',
        scale: true,
      },
      series,
    });
    window.addEventListener('resize', function () {
      lineChart.resize();
    });
  }

 barChartData() {
    let { num, typeList, dataList } = this.state.barChartXDataObj;
    // 柱状图
    let series = [];
    num.forEach((item, index) => {
      series.push({
        name: typeList[index],
        type: 'bar',
        barWidth: '25%', // number string 百分比
        stack: '1',
        data: item, // Y轴的数据,
      });
    });
    let pillarChart = echarts.init(document.getElementById('pillar-chart'));
    pillarChart.setOption({
      tooltip: {
        trigger: 'axis',
        transitionDuration: 0,
        backgroundColor: '#fff',
        extraCssText: 'max-width:180px !important;white-space:pre-wrap;color:#333;border:1px solid #efefef',
        axisPointer: {
          type: 'line',
        },
        // show: true,
        formatter: params => {
          let str = '';
          for (let item of params) {
            str += `<span style="line-height: 30px;"><i style="display:inline-block;width:15px;height:15px;background:${
              item.color
            };transform: translateY(3px);margin-right:5px;"></i>${item.seriesName}:${
              this.state.queryTypeValue === 2
                ? Math.floor(item.data / 60) + 'h' + (item.data % 60 <= 0 ? '' : (item.data % 60) + 'min')
                : item.data
            }</span>`;
          }
          return `<div style="display:flex;flex-direction: column;">${params[0].name}<br/>${str}</div>`;
        },
      },
      dataZoom: [
        {
          type: 'inside',
          start: 5,
          end: 95,
        },
        {
          start: 5,
          end: 95,
        },
      ],
      //图例
      legend: {
        itemHeight: 14,
        itemWidth: 14,
        icon: 'rect',
        right: 10,
        data: typeList,
      },
      grid: {
        left: '5%',
        right: '2%',
      },
      title: {
        text: this.state.queryTypeValue === 1 ? '次数(次)' : '时长(分)', // 标题文字
        textStyle: {
          // 标题样式设置
          color: '#333',
          fontWeight: 'normal',
          fontSize: 14,
        },
        left: 45,
        top: 20,
      },
      xAxis: {
        type: 'category',
        axisTick: {
          alignWithLabel: true,
        },
        data: dataList,
      },
      yAxis: {
        type: 'value',
      },
      series,
    });
  }

实际截图

折线图


image.png

柱状图:


image.png

相关文章

网友评论

      本文标题:React-Echarts-通用配置

      本文链接:https://www.haomeiwen.com/subject/hearxrtx.html