使用echarts绘制数量随月份的折线图的setOption

function setOption(date, count) {

}

date和count是长度相等的数组,一个存储日期Date,一个存储和日期对应的数量统计。

比较特殊的是,如果统计数量为0,那么不会有相应的输入,所以必须要对数据进行处理。

import * as echarts from "echarts";

function setOption(date, count) {
  // 找到最早和最晚的日期
  const minDate = new Date(Math.min(...date));
  const maxDate = new Date(Math.max(...date));

  // 生成完整的年月序列
  const yearMonthSeries = [];
  let currentDate = new Date(minDate);
  while (currentDate <= maxDate) {
    const year = currentDate.getFullYear();
    const month = currentDate.getMonth() + 1;
    yearMonthSeries.push(`${year}-${month.toString().padStart(2, '0')}`);
    currentDate.setMonth(currentDate.getMonth() + 1);
  }

  // 生成年月对应的数据对象
  const dataMap = {};
  for (let i = 0; i < date.length; i++) {
    const key = date[i];
    const year = key.getFullYear();
    const month = key.getMonth() + 1;
    const formattedKey = `${year}-${month.toString().padStart(2, '0')}`;
    dataMap[formattedKey] = count[i];
  }

  // 补充缺失的月份数据
  yearMonthSeries.forEach(yearMonth => {
    if (!dataMap[yearMonth]) {
      dataMap[yearMonth] = 0;
    }
  });

  // 将数据按照年月排序
  const sortedDataMap = Object.fromEntries(Object.entries(dataMap).sort());

  // 生成最终的 x 轴和数据
  const xAxisData = Object.keys(sortedDataMap);
  const seriesData = xAxisData.map(key => sortedDataMap[key]);

  let option = {
    tooltip: {
      trigger: 'axis'
    },
    title: {
      text: '每月***数统计',
      left: '5%',
      top: '5%',
      textStyle: {
        color: '#007AFF',
        fontSize: 16
      }
    },
    xAxis: {
      type: 'category',
      data: xAxisData,
      axisLabel: {
        formatter: function (value, index) {
          const parts = value.split('-');
          if (parts[1] === '01') {
            return parts[0] + '年';
          } else {
            return parts[1] + '月';
          }
        }
      }
    },
    yAxis: {
      type: 'value'
    },
    grid: {
      left: '3%',
      right: '8%',
      bottom: '10%',
      containLabel: true
    },
    series: [
      {
        name: '***',
        data: seriesData,
        type: 'line',
        showBackground: true,
        itemStyle: {
          color: '#0262F7'
        },
        label: {
          show: true,
          position: 'top',
          color: '#000'
        },
        backgroundStyle: {
          color: 'rgba(180, 180, 180, 0.2)'
        }
      }
    ],
    

  };
  return option;
}

export default {
  setOption
};

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值