React 中使用Echarts

494 阅读1分钟
最近在项目开发中,需要做可视化折线图,因此引入了Echarts,确实很好用,各种配置都有,适合各种定制化图表展示,在此记录下
  1. 引入Echarts
import * as echarts from 'echarts';
  1. 使用并配置各项参数
const Chart = () => {
  const [time, setTime] = useState();
  
  useEffect(() => {
    let myChart = echarts.init(document.getElementById('main'));
    myChart.setOption({
        //四周留白
      grid: {
        left: 50,
        right: 20,
        top: 50,
        bottom: 50,
      },
      tooltip: {
        trigger: 'axis',
      },
      xAxis: {
          //横坐标显示
        axisLabel: {
          formatter: function (value, index) {
            const date = dayjs(parseInt(value));
            return date.format('MM-DD');
          },
        },
          //提示框里的坐标日期显示
        axisPointer: {
          label: {
            formatter: function (params) {
              return dayjs(parseInt(params.value)).format('MM-DD');
            },
          },
        },
        type: 'category',
        boundaryGap: false,
      },
      yAxis: {
        type: 'value',
        boundaryGap: false,
      },
      dataZoom: {
        start: 0,
        type: 'inside',
      },

      series: [
        {
          itemStyle: {
            color: '#D287ED', //拐点颜色
            borderColor: '#ffffff', //拐点边框颜色
            borderWidth: 2, //拐点边框大小
          },
          symbol: 'circle',
          symbolSize: 10,
          lineStyle: {
            width: 2,
            color: '#D287ED',
          },
          sampling: 'lttb',
            //填充色
          areaStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              {
                offset: 0,
                color: 'rgba(210, 135, 237, 0.5)',
              },
              {
                offset: 1,
                color: 'rgba(210, 135, 237, 0.1)',
              },
            ]),
          },
          name: 'Fake Data',
          type: 'line',
          smooth: true,
          showSymbol: false,
          data: data,
        }
      ],
    });
  });
  
  //制造假数据
  let base = +new Date(2021, 3, 31);
  let oneDay = 24 * 3600 * 1000;
  let data = [[base, Math.random() * 300]];
  for (let i = 1; i < 365; i++) {
    // let now = new Date((base += oneDay));
    data.push(
      [        (base += oneDay),        Math.abs(Math.round((Math.random() - 0.5) * 20 + data[i - 1][1])),
      ]
    );
  }
  
  return (
    <div>
      <div id="main" style={{ width: '100%', height: 400 }}></div>
    </div>
  );
}