echarts折线图设置背景颜色

本文详细描述了如何使用ECharts库在JavaScript中创建动态图表,包括配置项如tooltip、坐标轴、数据系列和动画效果,以及图表的初始化和尺寸调整方法。
摘要由CSDN通过智能技术生成

如果有特定规律的话 可以参考方法二(如奇数行和偶数行不同特殊处理即可)


    initChartsBox() {
      this.option = {
        tooltip: {
          trigger: "axis",
          axisPointer: {
            // 方法一
            type: "shadow", // 默认为直线,可选为:'line' | 'shadow'
            shadowStyle: {
              color: "rgba(41, 95, 204, 0.2)",
            },
          },
          borderColor: "rgba(0, 170, 255)", // 边框颜色
        }, // 坐标轴指示器配置
        textStyle: {
          color: "#333", // xy轴的提示文字颜色,不包含背景刻度线
        },
        color: ["#1492FF"],
        grid: {
          top: "25px",
          left: "50px",
          right: "20px",
          bottom: "35px",
        },
        xAxis: [
          {
            type: "category",
            data: this.chartsData.time,
            axisLine: {
              show: true,
              lineStyle: {
                color: "#004080",
                // width: 0,
                // type: "solid",
              }, // x轴线的颜色以及宽度
            },
            // axisLabel: {
            //   show: true,
            //   textStyle: {
            //     color: "rgba(255, 255, 255, 0.3)",
            //   }
            // }, // x轴文字的配置
            splitLine: {
              show: false,
              lineStyle: {}, // 分割线配置
            },
            axisTick: {
              show: false,
            }, // x轴的刻度线
          },
        ],
        yAxis: [
          {
            type: "value",
            splitLine: {
              show: true,
              lineStyle: {
                color: "#333",
                opacity: 0.1,
              }, // 设置横向的线的颜色
            },
            axisLabel: {
              show: true,
              margin: 20,
              // textStyle: {
              //   color: "rgba(255, 255, 255, 0.3)",
              // }, // y轴的字体配置
            },

            splitArea: {
              show: true,
              areaStyle: {
                color: [
                  'rgba(21, 190, 80, 0.1)',
                  'rgba(109, 217, 147, 0.1)',
                  'rgba(245, 221, 102, 0.11)',
                  'rgba(255, 107, 0, 0.1)',
                  'rgba(212, 0, 0, 0.1)',
                ]
              }
            }

          },
        ],
        series: [
          {
            data: this.chartsData.roadNorm,
            type: "line",
            smooth: true,
            symbolSize: 0, // 设置圆点大小为 0,即不显示圆点
          },
        ],
      };
      this.myChart = this.$echarts.init(document.getElementById("chartsBox")); // 图标初始化
      this.myChart.setOption(this.option); // 渲染页面
      var that = this;
      let index = 0;
      this.eChartsTimer = setInterval(function () {
        let len = that.chartsData.time.length;
        if (index >= len) {
          index = 0;
        }
        that.myChart.dispatchAction({
          type: "showTip", // 提示框
          seriesIndex: 0,
          dataIndex: index, // 第 lightIndex 柱子高亮
        });
        index += 1
      }, 1000);

      /* ECharts动态效果 */
      window.addEventListener("resize", () => {
        this.myChart.resize();
      });
    },
方法二
<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,
    };
  },
  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: 28,
            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.calculateColorConfig(),
            },
            // data: this.chartsData.roadNorm,
            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); // 渲染页面
      /* ECharts动态效果 */
      window.addEventListener("resize", () => {
        this.myChart.resize();
      });
    },

    calculateColorConfig() {
      const maxVal = 100; // 假设最大值为 10
      const step = 20; // 每次增加的 y 轴值
      const lightColor = "rgba(20,146,255,.1)";
      const darkColor = "rgba(20,146,255,.3)";
      let colorConfig = []

      for (let i = 0; i < maxVal; i += step) {
         colorConfig.push([
          {
            yAxis: i,
            itemStyle: {
              color: i % (step * 2) === 0 ? darkColor : lightColor,
            },
          },
          {
            yAxis: i + step,
          },
        ]);
      }
      return colorConfig;
    },
  },
  created() {},
  mounted() {},
  destroyed() {},
};
</script>

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值