ECharts

引入

  1. 安装依赖
npm install echarts 
  1. 全局挂载
// main.js
import * as Echarts from "echarts"
Vue.prototype.echarts = Echarts;
Vue.use(Echarts);	// 注册插件

配置

公共部分

  1. 调整横纵坐标与边缘的距离

    • 方法一:
    grid: {
            top: "60px",
            bottom: "60px",
            left: "35px",
            right: "20px",
          },
    

  2. 有时候会发现数据和配置变了,但渲染处理的图表受到上次的影响而不符
    设置:setOptions(XXXX, true) : 设置了true,会重新渲染,不受上次影响
    参考: 简书


  3. 用v-if控制显隐失败原因
    参考:https://blog.csdn.net/SL7664/article/details/107861375


  1. 图表旋转90度

  1. 图例互斥

    // 配置
    legend: {
          data: ["氨氮", "溶解氧", "透明度", "氧化还原电位"],
          bottom: "0px",
          top: "0px",
          selected: {
            氨氮: true,
            溶解氧: false,
            透明度: false,
            氧化还原电位: false,
          },
        },
    
    // 监听修改交互
    handleChart(chart) {
      chart.on("legendselectchanged", function (params) {
        for (let [key, value] of Object.entries(params.selected)) {
          if (key !== params.name && value) {
            chart.dispatchAction({
              type: "legendUnSelect",
              name: key,
            });
          }
        }
      });
    },
    

  1. 禁止hover事件
series: [{
	silent: true,
}]

折线图

  1. 折线图连接空数据
    设置:connectNulls: true
    例子:

    series: [{
    	type: 'line',
    	connectNulls: true
    }]
    

    参考: CSDN


  2. 显示横坐标的最后一个值
    设置:showMaxLabel: true
    例子:

    xAxis: [
    {
    	axisLabel: {
    	showMaxLabel: true
    	}
    }
    ]
    

    参考:CSDN


  3. 设置辅助线:

    series: [
          {
            name: "氨氮",
            type: "line",
            data: waterLevel,
            connectNulls: true,
    		// 辅助线
            markLine: {
              symbol: "none", //去掉警戒线最后面的箭头
              label: {
                show: true,
                position: "middle",
                formatter: function (params) {
                  console.log(params);
                  return `${params.data.name}${params.data.yAxis}mg/L`; //预警值 对应显示 data1  预警值
                },
              },
              data: [
    			[
    			  { name: "黑臭限值", xAxis: 0, yAxis: 8 },
    			  { name: "黑臭限值", xAxis: xData[xData.length - 1], yAxis: 8 },
    			],
    			[
    			  { name: "劣V限值", xAxis: 0, yAxis: 2 },
    			  { name: "劣V限值", xAxis: xData[xData.length - 1], yAxis: 2 },
    			],
    		  ],
              lineStyle: {
                normal: {
                  type: "solid",
                  color: "#cb5856",
                },
              },
            },
    		]
    

  1. 线性图配置虚线

    series: [
          {
            name: "近一年数据",
            type: "line",
            data: yearData,
            connectNulls: true,
    		// 虚线
            itemStyle: {
              normal: {
                lineStyle: {
                  width: 2,
                  type: "dotted", //dotted点型虚线 solid实线 dashed线性虚线
                },
              },
            },
          },
          {
            name: "上一年同期",
            type: "line",
            data: beforeYearData,
            connectNulls: true,
            itemStyle: {
              normal: {
                lineStyle: {
                  width: 2,
                  type: "dotted", //dotted点型虚线 solid实线 dashed线性虚线
                },
              },
            },
          },
        ],
    
  2. 纵坐标显示罗马数字

    let RomeObj = { I: 1, II: 2, III: 3, IV: 4, 劣V: 5, 黑臭: 6 };
    
    yAxis: [
          {
            type: "value",
            name: "",
            position: "left",
            min: 1,
            max: 6,
            axisLabel: {
              color: "#333",
              fontSize: "12px",
              formatter: function (data) {
                for (let [key, value] of Object.entries(RomeObj)) {
                  if (value === data) {
                    return [key];
                  }
                }
              },
            },
            axisLine: {
              lineStyle: { color: "#333" },
            },
          },
        ],
    tooltip: {
          trigger: "axis",
          formatter: function (params) {
            return params.reduce((prev, curr) => {
              for (let [key, value] of Object.entries(RomeObj)) {
                if (value === curr.value) {
                  return (
                    prev +
                    curr.marker +
                    curr.seriesName +
                    ":" +
                    key +
                    "类<br/>"
                  );
                }
              }
            }, "");
          },
        },
    

image
12.折线图上的点上显示数据

        series: [
          {
            name: "水质指数",
            type: "line",
            data: waterFlow,
            areaStyle: areaStyle,
            connectNulls: true,
            itemStyle: { normal: { label: { show: true } } },
          },
        ],

image

柱形图

  1. 配置滚动条
// 配置滚动条
        option.dataZoom = [
          {
            // 设置滚动条的隐藏与显示
            show: true,
            // 设置滚动条类型
            type: "slider",
            realtime: true,
            showDetail: false,
            maxValueSpan: this.from === "Statistic" ? 3 : 4,
            // empty:当前数据窗口外的数据,被设置为空。
            // 即不会影响其他轴的数据范围
            filterMode: "empty",
            // 设置滚动条宽度,相对于盒子宽度
            width: "100%",
            // 设置滚动条高度
            height: 8,
            // 设置滚动条显示位置
            left: "center",
            // 是否锁定选择区域(或叫做数据窗口)的大小
            zoomLoxk: true,
            // 控制手柄的尺寸
            handleSize: 0,
            // dataZoom-slider组件离容器下侧的距离
            bottom: 3,
            xAxisIndex: [0, 1, 2, 3, 4, 5],
          },
          {
            // 没有下面这块的话,只能拖动滚动条,
            // 鼠标滚轮在区域内不能控制外部滚动条
            type: "inside",
            // 滚轮是否触发缩放
            zoomOnMouseWheel: false,
            // 鼠标滚轮触发滚动
            moveOnMouseMove: true,
            moveOnMouseWheel: true,
          },
        ];
  1. 三维立体柱
    image
option = {
xAxis: [
          {
            type: "category",
            axisLabel: {
              fontSize: 10,
              //坐标轴刻度标签的相关设置
              formatter: function (params) {
                var newParamsName = ""; // 最终拼接成的字符串
                var paramsNameNumber = params.length; // 实际标签的个数
                var provideNumber = 5; // 每行能显示的字的个数
                var rowNumber = Math.ceil(paramsNameNumber / provideNumber); // 换行的话,需要显示几行,向上取整
                /**
                 * 判断标签的个数是否大于规定的个数, 如果大于,则进行换行处理 如果不大于,即等于或小于,就返回原标签
                 */
                // 条件等同于rowNumber>1
                if (paramsNameNumber > provideNumber) {
                  /** 循环每一行,p表示行 */
                  for (var p = 0; p < rowNumber; p++) {
                    var tempStr = ""; // 表示每一次截取的字符串
                    var start = p * provideNumber; // 开始截取的位置
                    var end = start + provideNumber; // 结束截取的位置
                    // 此处特殊处理最后一行的索引值
                    if (p == rowNumber - 1) {
                      // 最后一次不换行
                      tempStr = params.substring(start, paramsNameNumber);
                    } else {
                      // 每一次拼接字符串并换行
                      tempStr = params.substring(start, end) + "\n";
                    }
                    newParamsName += tempStr; // 最终拼成的字符串
                  }
                } else {
                  // 将旧标签的值赋给新标签
                  newParamsName = params;
                }
                //将最终的字符串返回
                return newParamsName;
              },
            },
          },
		  { type: "category", position: "bottom", show: false },
            { type: "category", position: "bottom", show: false },
            { type: "category", position: "bottom", show: false },
            { type: "category", position: "bottom", show: false },
            { type: "category", position: "bottom", show: false },
        ],
		
};
let colors = ["rgba(140,98,255,", "rgba(60,162,255,"];
option.series = colors.reduce((prev, curr, index) => {
          // 内容背景
          prev.push({
            type: "bar",
            name: names[index],
            z: 3,
            data: this.showData
              .slice(1)
              .map(
                (item) =>
                  (Math.min(item[index * 2 + 1], item[index * 2 + 2]) /
                    item[index * 2 + 1]) *
                  100
              ),
            label: {
              show: this.from !== "Statistic",
              position: "inside",
              formatter({ name, seriesIndex }) {
                let data = _this.showData.find((item) => item[0] === name);
                let index = seriesIndex === 0 ? 1 : 3;
                return (
                  data &&
                  Number(
                    Number(
                      isNaN(
                        Math.min(data[index], data[index + 1]) / data[index]
                      )
                        ? 0
                        : Math.min(data[index], data[index + 1]) / data[index]
                    ) * 100
                  ).toFixed(0) + "%"
                );
              },
            },
            itemStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                { offset: 0, color: curr + "0.95)" },
                { offset: 1, color: curr + "0.3)" },
              ]),
            },
          });
          // 顶部背景(椭圆)
          [
            [100, 0.2],
            [70, 0.5],
            [40, 1],
          ].forEach(([percentage, opacity], key) => {
            prev.push({
              z: 2,
              silent: true,
              type: "pictorialBar",
              symbolPosition: "end",
              symbol: "circle",
              symbolOffset: ["0%", "-50%"],
              xAxisIndex: key + 2,
              symbolSize: [percentage + "%", 15 * percentage * 0.01],
              toolltip: {
                show: false,
              },
              itemStyle: {
                color: curr + opacity + ")",
              },
              data: new Array(this.showData.length - 1).fill(100),
              toolltip: {
                show: false,
              },
              barGap: "30%",
            });
          });
          // 顶部背景(纯色)
          prev.push({
            z: 3,
            silent: true,
            type: "bar",
            data: new Array(this.showData.length - 1).fill(100),
            // 一张图和统计label不同
            label:
              this.from !== "Statistic"
                ? {
                    position: "top",
                    show: true,
                    distance: 10,
                    formatter({ name, seriesIndex }) {
                      let data = _this.showData.find(
                        (item) => item[0] === name
                      );
                      let index = seriesIndex === 4 ? 1 : 3;
                      return data && `(${data[index + 1]}/${data[index]})`;
                    },
                    backgroundColor: curr + "1)",
                    borderRadius: 20,
                    color: "#fff",
                    padding: [5, 10],
                  }
                : {
                    position: "top",
                    distance: 10,
                    show: true,
                    formatter({ name, seriesIndex }) {
                      let data = _this.showData.find(
                        (item) => item[0] === name
                      );
                      let index = seriesIndex === 4 ? 1 : 3;
                      return (
                        (data &&
                          data[index] !== 0 &&
                          parseInt(
                            (Math.min(data[index + 1], data[index]) /
                              data[index]) *
                              100
                          ) + "%") ||
                        ""
                      );
                    },
                    color: curr + "1)",
                    rotate: 30,
                    fontSize: 10,
                    align: "center",
                  },
            itemStyle: {
              color: curr + "0.1)",
            },
            xAxisIndex: 5,
            barGap: "30%",
            toolltip: {
              show: false,
            },
          });
          // 底部
          prev.push({
            z: 2,
            silent: true,
            type: "pictorialBar",
            symbol: "circle",
            symbolOffset: ["0%", "50%"],
            symbolSize: ["100%", 15],
            toolltip: {
              show: false,
            },
            itemStyle: {
              color: curr + "1)",
            },
            data: new Array(this.showData.length - 1).fill(1),
            toolltip: {
              show: false,
            },
            barGap: "30%",
            xAxisIndex: 0,
          });
          // 顶部(内容椭圆)
          prev.push({
            z: 2,
            silent: true,
            type: "pictorialBar",
            symbolPosition: "end",
            symbol: "circle",
            symbolOffset: ["0%", "-50%"],
            xAxisIndex: 1,
            symbolSize: ["100%", 15],
            toolltip: {
              show: false,
            },
            itemStyle: {
              color: curr + "1)",
            },
            data: this.showData
              .slice(1)
              .map(
                (item) =>
                  (Math.min(item[index * 2 + 1], item[index * 2 + 2]) /
                    item[index * 2 + 1]) *
                  100
              ),
            toolltip: {
              show: false,
            },
            barGap: "30%",
          });
          return prev;
        }, []);

饼图

  1. 设置饼图

  1. 饼图中间显示文字
  • 效果图
    image
  • 源码:
let option = {
        // 主题颜色
        color: this.config.color,
        // 提示框浮层
        tooltip: {
          trigger: "item",
        },
        //图表配置
        series: [
          {
            type: "pie",
            radius: ["40%", "70%"],
            label: {
              normal: {
                show: true,
                position: "center",
                color: "#4c4a4a",
                formatter: "{total|" + total + "}" + "\n\r" + "{name|总量(人)}",
                rich: {
                  total: {
                    fontSize: 24,
                    fontFamily: "Microsoft YaHei",
                    color: "#00ecfb",
                  },
                  name: {
                    fontFamily: "Microsoft YaHei",
                    fontSize: 14,
                    color: "#fff",
                  },
                },
              },
              emphasis: {
                //中间文字显示
                show: true,
              },
            },
            data: this.config.data,
            itemStyle: {
              normal: {
                borderWidth: 1,
                borderColor: "#061e3d",
              },
            },
          },
        ],
      };

  1. 修改饼图辅助线和辅助文字的颜色
  • 效果图:
    image
  • 源码
//图表配置
        series: [
          {
            type: "pie",
            width: "60%",
            radius: this.data.radius || [0, "75%"],
            itemStyle: {
              normal: {
                label: {
                  textStyle: {
                    color: "#fff",	// 文字
                    fontSize: 14,
                    fontWeight: "bolder",
                  },
                  formatter: this.data.labelFormatter || "{c}",
                },
                labelLine: {
                  lineStyle: {
                    color: "#fff",	// 辅助线
                  },
                },
              },
            },

            data: this.data.data,
          },
        ],

  1. 饼图设置管道效果
  • 效果图
    image
  • 源码
// 饼型图表初始化
    initPieChart() {
      let Chart = this.echarts.init(this.$refs.Chart);
      let option = {
        // 主题颜色
        color: ["#00E8B1", "#FFBF1F"],
        // 提示框浮层
        tooltip: {
          trigger: "item",
        },
        graphic: {
          elements: [
            {
              //环形图中间添加图片
              type: "image", //通过不同top值可以设置上下显示
              top: "20%",
              left: "30%",
              style: {
                image: require("@/assets/images/chart-bg.png"), //文字的颜色
              },
            },
            {
              //环形图中间添加文字
              type: "text", //通过不同top值可以设置上下显示
              left: "center",
              top: "40%",
              style: {
                text: "80%",
                textAlign: "center",
                fill: "#fff", //文字的颜色
                width: 30,
                height: 30,
                fontSize: 24,
                fontFamily: "Microsoft YaHei",
                fontWeight: "bold",
              },
            },
            {
              //环形图中间添加文字
              type: "text", //通过不同top值可以设置上下显示
              left: "center",
              top: "55%",
              style: {
                text: "完成率",
                textAlign: "center",
                fill: "#fff", //文字的颜色
                width: 30,
                height: 30,
                fontSize: 14,
                fontFamily: "Microsoft YaHei",
              },
            },
          ],
        },
        //图表配置
        series: [
          {
            type: "pie",
            radius: ["65%", "85%"],
            center: ["50%", "50%"],
            selectedMode: false,
            hoverAnimation: false,
            data: [{ value: 1, name: "" }],
            itemStyle: {
              color: "#02142e",
            },
            label: {
              show: false,
            },
            labelLine: {
              show: false,
            },
            tooltip: {
              show: false,
            },
            animation: false,
            cursor: "auto",
            emphasis: {
              itemStyle: {
                color: "#02142e",
              },
            },
          },
          {
            type: "pie",
            colorBy: "series",
            radius: ["70%", "80%"],
            label: {
              show: false,
            },
            data: [
              {
                name: "rest", // 实际显示部分是总量-用量
                value: 280,
                itemStyle: {
                  borderRadius: 100,
                  borderColor: "#000",
                  borderWidth: 2,
                  color: {
                    type: "linear", // 渐变
                    x: 0,
                    y: 0,
                    x2: 1,
                    y2: 1,
                    colorStops: [
                      {
                        offset: 0,
                        color: "#f3a800", // 0% 处的颜色
                      },
                      {
                        offset: 1,
                        color: "#eb6600", // 100% 处的颜色
                      },
                    ],
                    global: false, // 缺省为 false
                  },
                },
              },
              {
                name: "bottom",
                value: 90, //底部透明部分的颜色,看实际情况,如果需要的是半圆图,这个透明部分的value值就变成和all相同的值,以此类推,可以自己调节value的大小
                itemStyle: {
                  color: "transparent",
                },
              },
            ],
            itemStyle: {
              color: "#fff",
              normal: {
                borderWidth: 1,
                borderColor: "#061e3d",
              },
            },
          },
        ],
      };
      option && Chart.setOption(option);
    },

资料

官网

posted @ 2022-08-18 15:27  拉布拉多~  阅读(195)  评论(0编辑  收藏  举报