echarts折线图 设置奇数行和偶数行有规律的背景色

echarts折线图 设置奇数行和偶数行有规律的背景色,并且实现图表数据更新的时候奇数行和偶数行的背景色能动态变化

获取echarts中y轴的数据 ---> 设置奇数行和偶数行的背景色

this.myChart = this.$echarts.init(document.getElementById("chartsBox"));
this.chartsComp = this.myChart.getModel().getComponent('yAxis')

const maxValue = this.chartsComp.axis.scale._extent[1]; // 获取y轴刻度的最大值
const step = this.chartsComp.axis.scale._interval; // 获取y轴刻度的步长

 关键代码

  initChartsBox() {
      this.option = {};
      this.myChart = this.$echarts.init(document.getElementById("chartsBox"));
      this.myChart.setOption(this.option); // 渲染页面
      this.chartsComp = this.myChart.getModel().getComponent('yAxis')
      // 更新series[0].markArea.data
      const { _extent, _interval } = this.chartsComp.axis.scale
      this.updateMarkAreaData(_extent[1], _interval);
      /* ECharts动态效果 */
      window.addEventListener("resize", () => {
        this.myChart.resize();
      });
    },

    updateMarkAreaData(maxValue, step) {
      const lightColor = "rgba(20,146,255,.1)";
      const darkColor = "rgba(20,146,255,.3)";
      let colorConfig = [];

      for (let i = 0; i <= maxValue; i += step) {
        colorConfig.push([
          {
            yAxis: i,
            itemStyle: {
              color: i % (step * 2) === 0 ? darkColor : lightColor,
            },
          },
          {
            yAxis: i + step,
          },
        ]);
      }

        this.myChart.setOption({
          series: [
            {
              markArea: {
                data: this.chartsData.roadNorm.some((e) => e && e>=0)
                  ? colorConfig
                  : [], // 当有数据的时候才更新 markArea.data
              },
            },
          ],
        });

    },

 完整代码 

<template>
  <div class="box-wrap" id="chartsBox"></div>
</template>

<script>
import { getParkingInFlow } from "@/api/parkingMonitoring/realTimeMonitoring";

export default {
  name: "box2",
  components: {},
  mixins: [],
  props: {},
  computed: {},
  watch: {},
  filters: {},
  data() {
    return {
      timeKey: "createTime",
      valueKey: "totalIn",
      chartsTop: 30,
      chartsComp: undefined,
    };
  },
  methods: {
    /**
     * @Event 获取折线图的数据
     * @param {*} obj.areaCode 区域编号 (1 道路 2 区域 传的都是 areaCode)
     * @param {*} obj.checkTypes 查询类型(1实时 2预测 3过去)
     * @param {*} obj.roadCode 路段编号
     * @param {*} obj.selectTime 选择时间
     * @description:
     * @author: mhf
     * @time: 2024-02-02 09:48:06
     **/
    getBox2Data(params) {
      return new Promise((resolve, reject) => {
        // areaType:1 道路 2 区域
        getParkingInFlow(params).then((res) => {
          if (res.code === 1) {
            this.chartsData = {
              // 初始化数据(五分钟一个点,24 * 12)
              roadNorm: Array.from({ length: 24 * 12 }, () => null), // Initialize with [null, null, ..., null]
              time: Array.from({ length: 24 * 12 }, (_, i) => i / 12), // Initialize with [0, 0.0833, ..., 23.9167]
            };
            if (res.data && res.data.length > 0) {
              res.data.forEach((item) => {
                const timeValue = new Date(item[this.timeKey]);
                const index = Math.floor(
                  timeValue.getHours() * 12 + timeValue.getMinutes() / 5
                );
                if (index >= 0 && index < this.chartsData.time.length) {
                  this.chartsData.roadNorm[index] = item[this.valueKey];
                }
              });
              const maxNumber = Math.max(
                ...res.data.map((obj) => obj[this.valueKey])
              );
              // this.chartsTop = maxNumber > 0.8 ? 40 : 6; // todo
            }
            resolve();
          } else {
            reject();
          }
        });
      })
        .then(() => {
          if (this.chartsData) {
            this.initChartsBox();
          }
        })
        .catch((e) => {
          console.warn("Error", e);
        });
    },

    initChartsBox() {
      this.option = {
        tooltip: {
          trigger: "axis",
          axisPointer: {
            animation: false,
          },
          formatter: function (params) {
            const index = params[0].dataIndex;
            const hour = Math.floor(index / 12);
            const minute = (index % 12) * 5;
            const formattedHour = String(hour).padStart(2, "0");
            const formattedMinute = String(minute).padStart(2, "0");
            const timeStr = `${formattedHour}:${formattedMinute}`;
            const congestionIndex = params[0].value;
            const formattedIndex = congestionIndex?.toFixed(2) || "-";
            const circleIcon =
              '<span style="display:inline-block;margin-right:5px;border-radius:50%;width:8px;height:8px;background-color:#1492FF;"></span>';
            return `${timeStr}<br>${circleIcon} ${formattedIndex} 辆`;
          },
        },
        axisPointer: {
          link: {
            xAxisIndex: "all",
          },
        },
        dataZoom: [
          {
            show: false,
            realtime: true,
            start: 0,
            end: 100,
            // height: 14,
            xAxisIndex: [0, 1],
            zoomLock: true,
          },
          {
            type: "inside",
            realtime: true,
            start: 0,
            end: 100,
            xAxisIndex: [0, 1],
            zoomLock: true,
          },
        ],
        grid: [
          {
            top: this.chartsTop,
            bottom: 20,
            left: 50,
            right: 10,
          },
          {
            left: -10,
            right: 10,
            top: 0,
            bottom: 0,
          },
        ],
        xAxis: [
          {
            type: "category",
            boundaryGap: false,
            axisLine: {
              onZero: true,
            },
            data: this.chartsData.time,
            axisLabel: {
              formatter: function (value, index) {
                const hour = Math.floor(value);
                return hour + ":00";
              },
            },
          },
          {
            gridIndex: 1,
          },
        ],

        yAxis: [
          {
            type: "value",
            min: 0,
            // max: 1000, // todo
            name: "单位: 辆",
          },
          {
            gridIndex: 1,
          },
        ],
        series: [
          {
            name: "饱和度",
            type: "line",
            smooth: true,
            symbol: "circle",
            symbolSize: 9,
            showSymbol: false,
            lineStyle: {
              normal: {
                width: 2,
                color: "#1492FF",
              },
            },
            markPoint: {
              // data: [
              //   {
              //     type: "max",
              //     name: "最大值",
              //   },
              //   {
              //     type: "min",
              //     name: "最小值",
              //   },
              // ],
            },
            markArea: {
              silent: true,
              label: {
                normal: {
                  position: ["4%", "50%"],
                },
              },
            },
            data: this.chartsData.roadNorm.map((value, index) => ({
              value,
              time: this.chartsData.time[index],
            })), // 数据初始化(tooltip中使用formatter)
          },
        ],
      };
      this.myChart = this.$echarts.init(document.getElementById("chartsBox"));
      this.myChart.setOption(this.option); // 渲染页面
      this.chartsComp = this.myChart.getModel().getComponent('yAxis')
      // 更新series[0].markArea.data
      const { _extent, _interval } = this.chartsComp.axis.scale
      this.updateMarkAreaData(_extent[1], _interval);
      /* ECharts动态效果 */
      window.addEventListener("resize", () => {
        this.myChart.resize();
      });
    },


    updateMarkAreaData(maxValue, step) {
      const lightColor = "rgba(20,146,255,.1)";
      const darkColor = "rgba(20,146,255,.3)";
      let colorConfig = [];

      for (let i = 0; i <= maxValue; i += step) {
        colorConfig.push([
          {
            yAxis: i,
            itemStyle: {
              color: i % (step * 2) === 0 ? darkColor : lightColor,
            },
          },
          {
            yAxis: i + step,
          },
        ]);
      }

        this.myChart.setOption({
          series: [
            {
              markArea: {
                data: this.chartsData.roadNorm.some((e) => e && e>=0)
                  ? colorConfig
                  : [], // 当有数据的时候才更新 markArea.data
              },
            },
          ],
        });

    },
  },
  created() {},
  mounted() {},
  destroyed() {},
};
</script>

<style lang="scss" scoped>
.box-wrap {
  width: 100%;
  height: 100%;
}
</style>

demo3

<template>
  <div class="lineChart" id="chartsBox">
  </div>
</template>

<script>

export default {
  name: "lineChart",
  components: {},
  props: {
    chartData: {
      type: Array,
      default: () => {
        return [];
      }
    }
  },
  computed: {},
  watch: {
    chartData: {
      handler(val) {
        this.initChartsBox(val.map(i => i.time), val.map(i => i.count));
      },
      deep: true,
    }
  },
  data() {
    return {
      myChart: undefined
    };
  },
  methods: {
    initChartsBox(xData,yData) {
      let option = {
        tooltip: {
          trigger: 'axis'
        },
        grid: [
          {
            top: 30,
            bottom: 30,
            left: 40,
            right: 20,
          },
        ],
        xAxis:  {
          type: "category",
          boundaryGap: false,
          data: xData,
          axisTick: {
            show: false,
          },
          axisLabel: {
            interval: "auto", // 设置刻度线的智能显示
            show: true, // 是否显示刻度标签,默认显示
            // interval: 0, // 坐标轴刻度标签的显示间隔,在类目轴中有效;默认会采用标签不重叠的策略间隔显示标签;可以设置成0强制显示所有标签;如果设置为1,表示『隔一个标签显示一个标签』,如果值为2,表示隔两个标签显示一个标签,以此类推。
          },
          axisLine: {
            lineStyle: {
              color: "#F0F5FF",
              width: 0,
            },
          },
        },
        yAxis:{
          type: "value",
          axisLabel: {
            color: "#fff",
          },
          splitLine: {
            show: true,
            lineStyle: {
              type: "line",
              width: 0.5,
              color: "rgba(0, 170, 255, 0.30)",
            },
          },
          splitArea: {
            show: true,
            areaStyle: {
              color: ["rgba(6, 21, 44,.5)", "rgba(7, 40, 69,.5)"], // 设置网格区域的背景色,可以使用数组来实现循环效果
            },
          },
        },
        series: [{
          name: '流量',
          type: 'line',
          data: yData,
          showSymbol: false, // 不展示折线图原点
          lineStyle: {
            normal: {
              width: 2,
              color: {
                type: 'linear',

                colorStops: [{
                  offset: 0,
                  color: '#5a79b8' // 0% 处的颜色
                }, {
                  offset: 1,
                  color: '#32c2ff' // 100% 处的颜色
                }],
                globalCoord: false // 缺省为 false
              },
              shadowColor: 'rgba(87, 116, 178, 0.4)',
              shadowBlur: 4,
              shadowOffsetY: 20
            }
          },
          itemStyle: {
            normal: {
              color: '#fff',
              borderWidth: 10,
              /*shadowColor: 'rgba(72,216,191, 0.3)',
              shadowBlur: 100,*/
              borderColor: "#A9F387"
            }
          },
          smooth: true
        }]
      };
      this.myChart = this.$echarts.init(document.getElementById("chartsBox"));
      this.myChart.setOption(option); // 渲染页面
      window.addEventListener("resize", () => {
        this.myChart.resize();
      });
    },

  },
  created() {
  },
  mounted() {
    this.initChartsBox(this.chartData.map(i => i.time), this.chartData.map(i => i.count))
  },
  destroyed() {
    this.myChart.dispose();
  },
};
</script>
<style lang="scss" scoped>
$top: 14px;
$canvasHeight: 274px; // .dialogBox-content-camera > .canvas的高度

.lineChart {
  width: 100%;
  margin-top: $top;
  height: calc(#{$canvasHeight} - #{$top}) !important;
  position: relative;
}
</style>
// chartData 数据
chartData: [
            {
                "time": "00:00",
                "count": "0"
            },
            {
                "time": "01:00",
                "count": "0"
            },
            {
                "time": "02:00",
                "count": "0"
            },
            {
                "time": "03:00",
                "count": "1"
            },
            {
                "time": "04:00",
                "count": "0"
            },
            {
                "time": "05:00",
                "count": "0"
            },
            {
                "time": "06:00",
                "count": "0"
            },
            {
                "time": "07:00",
                "count": "0"
            },
            {
                "time": "08:00",
                "count": "0"
            },
            {
                "time": "09:00",
                "count": "0"
            },
            {
                "time": "10:00",
                "count": "0"
            },
            {
                "time": "11:00",
                "count": "0"
            },
            {
                "time": "12:00",
                "count": "0"
            },
            {
                "time": "13:00",
                "count": "0"
            },
            {
                "time": "14:00",
                "count": "0"
            },
            {
                "time": "15:00",
                "count": null
            },
            {
                "time": "16:00",
                "count": null
            },
            {
                "time": "17:00",
                "count": null
            },
            {
                "time": "18:00",
                "count": null
            },
            {
                "time": "19:00",
                "count": null
            },
            {
                "time": "20:00",
                "count": null
            },
            {
                "time": "21:00",
                "count": null
            },
            {
                "time": "22:00",
                "count": null
            },
            {
                "time": "23:00",
                "count": null
            }
        ],

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值