echarts常用配置项

1,200 阅读9分钟

echarts折线图拥有丰富的配置项,地址:echarts.apache.org/zh/option.h…

那么常用的有哪些呢?

backgroundColor

背景色,默认无背景

color

调色盘颜色列表。如果系列没有设置颜色,则会依次循环从该列表中取颜色作为系列颜色。 默认为: ['#c23531','#2f4554', '#61a0a8', '#d48265', '#91c7ae','#749f83', '#ca8622', '#bda29a','#6e7074', '#546570', '#c4ccd3']

title

标题

{
  text: '趋势', // 标题文本
  subtext: '苹果手机占比18%,粉丝消费能力一般', // 子标题
  left: 0, // 位置
  top: 0,
  textStyle:{ // 标题样式
    color: 'rgba(0, 0, 0, 0.85)',
    fontStyle: 'normal',
    fontWeight: 'normal',
    fontSize: 14,
  },
  subtextStyle:{ // 子标题样式
    color: 'rgba(0, 0, 0, 0.45)',
    fontStyle: 'normal',
    fontWeight: 'normal',
    fontSize: 14,
  },
},

tooltip

提示框组件

// formatter第一个参数的格式
interface Format {
  componentType?: 'series';
  // Series type
  seriesType?: string;
  // Series index in option.series
  seriesIndex?: number;
  // Series name
  seriesName?: string;
  // item marker, string of HTMLElement 原始的圆形图标的DOM结构
  marker?: string;
  // Data name, or category name
  name?: string;
  // Data index in input data array
  dataIndex?: number;
  // Original data as input
  data?: any;
  // Value of data
  value?: number | any[];
  // Value of axis
  axisValue?: number | string;
  // Label of axis value
  axisValueLabel?: string;
  // encoding info of coordinate system
  // Key: coord, like ('x' 'y' 'radius' 'angle')
  // value: Must be an array, not null/undefined. Contain dimension indices, like:
  // {
  //     x: [2] // values on dimension index 2 are mapped to x axis.
  //     y: [0] // values on dimension index 0 are mapped to y axis.
  // }
  encode?: object;
  // dimension names list
  dimensionNames?: string[];
  // data dimension index, for example 0 or 1 or 2 ...
  // Only work in `radar` series.
  dimensionIndex?: number;
  // Color of data
  color?: string;
  // the percentage of pie chart
  percent?: number;
}

{
  trigger: 'axis', // 触发项 坐标轴触发:axis 数据项图形触发:item
  axisPointer:  // 坐标轴指示器配置项 实际上坐标轴指示器的全部功能,都可以通过轴上的 axisPointer 配置项完成,如xAxis.axisPointer
  {
    type: 'line', // 指示器类型: line shadow cross none
  },
  confine: true, // 是否将 tooltip 框限制在图表的区域内。当图表外层的 dom 被设置为 'overflow: hidden',或者移动端窄屏,导致 tooltip 超出外界被截断时,此配置比较有用。
  // formatter: '{a} <br/>{b} : {c}',
  formatter(params: echarts.EChartOption.Tooltip.Format | echarts.EChartOption.Tooltip.Format[]) { // 提示框浮层内容格式器,支持字符串模板和回调函数两种形式。
    // 数据在传入的 data 数组中的 index
    const index = params[0].dataIndex;
    const prefix = `${params[0].axisValue} ${curConfig.title}<br>`;
    let result = '';
    let dataValue = '';
    params.forEach((item) => {
      const { seriesName, marker, seriesIndex } = item;
      if (!props.legendCategory) {
        dataValue = props.data[index][dataIndex];
      } else {
        dataValue = props.data[seriesIndex][index][dataIndex];
      }
      if (dataValue !== undefined) {
        result += `${marker}${seriesName ? `${seriesName}: ` : ''}${curConfig.render ? curConfig.render(dataValue) : dataValue}<br>`;
      }
    });
    return result ? prefix + result : '';
  },
}

xAxis

{
  type: 'category', // 坐标轴类型 数值轴连续数据:value 类目轴离散数据: category 时间轴连续的时序数据:time 对数轴:log
  data: props.data.map(item => formatTime(item[props.timeConfig.dataIndex])), // 类目数据,在类目轴(type: 'category')中有效 元素可以是string或者object
  boundaryGap: true, // 坐标轴两边留白策略,类目轴(true/false)和非类目轴(['20%', '20%'])的设置和表现不一样
  axisTick: // 坐标轴刻度相关设置
  {
    alignWithLabel: true, // 类目轴中在 boundaryGap 为 true 的时候有效,可以保证刻度线和标签对齐
  },
  axisLabel: // 坐标轴刻度标签的相关设置
  {
    show: true, // 是否显示刻度标签
    formatter: '{value} kg', // 刻度标签的内容格式器,支持字符串模板和回调函数两种形式
    fontSize: 16,
  },
  splitArea: { // 坐标轴在 grid 区域中的分隔区域,默认不显示。
    show: true,
  },
  name: 'km/s minus 299,000', // 坐标轴名称
  splitLine: { // 坐标轴在 grid 区域中的分隔线
    show: false,
  },
  nameGap: 30, // 坐标轴名称与轴线之间的距离
}

yAxis

{
  type: 'value', // 坐标轴类型 数值轴连续数据:value 类目轴离散数据: category 时间轴连续的时序数据:time 对数轴:log
  splitArea: {
    show: true,
  },
  scale: true,  // 只在数值轴中(type: 'value')有效,是否是脱离 0 值比例,设置成 true 后坐标刻度不会强制包含零刻度
}

legend

图例组件

{
  top: 'bottom', // 图例组件离容器上侧的距离
  data: props.legendData, // 图例的数据数组 元素可以是string或者object
}

grid

直角坐标系内绘图网格,设置canvas内部的边距

{
  left: '3%', // grid 组件离容器左侧的距离
  right: '4%',
  top: '2%',
  bottom: '3%',
  containLabel: true, // grid 区域是否包含坐标轴的刻度标签
}

series

系列列表。每个系列通过 type 决定自己的图表类型,每种类型支持的参数不同

折线图

props.legendData.map((value, index) => ({
  name: value, // 系列名称,用于tooltip的显示,legend 的图例筛选,在 setOption 更新数据和配置项时用于指定对应的系列。
  type: 'line', // 图表类型: line bar pie map funnel等
  data: props.seriesData[index],
})),

柱状图

props.legendData.map((value, index) => ({
  name: value, // 系列名称,用于tooltip的显示,legend 的图例筛选,在 setOption 更新数据和配置项时用于指定对应的系列。
  type: 'bar', // 图表类型: line bar pie map funnel等
  data: props.seriesData[index],
  barCategoryGap: '10%', // 同一系列的柱间距离,默认为类目间距的20%,可设固定值
  barMaxWidth: '30%', // 柱条的最大宽度,比 barWidth 优先级高
})),

漏斗图

{
  name: '漏斗图', // 系列名称,用于tooltip的显示,legend 的图例筛选,在 setOption 更新数据和配置项时用于指定对应的系列。
  type: 'funnel', // 图表类型: line bar pie map funnel等
  top: 0, // 漏斗图组件离容器上侧的距离
  left: 0,
  right: 100,
  min: 0, // 指定的数据最小值。
  maxSize: '500', // 数据最大值 max 映射的宽度。可以是绝对的像素大小,也可以是相对布局宽度的百分比。
  sort: 'descending', //数据排序, 可以取 'ascending''descending''none'(表示按 data 顺序),或者一个函数(即 Array.prototype.sort(function (a, b) { ... }))。
  gap: 2, // 数据图形间距
  label: { // 漏斗图图形上的文本标签,可用于说明图形的一些数据信息,比如值,名称等,label选项在 ECharts 2.x 中放置于itemStyle下,在 ECharts 3 中为了让整个配置项结构更扁平合理,label 被拿出来跟 itemStyle 平级,并且跟 itemStyle 一样拥有 emphasis 状态
    normal: {
      show: true,
      position: 'right',
    },
  },
  labelLine: {
    show: false, // 是否展示label引导线
  },
  data: chartData2,
},

饼图

series: [
  {
    name: '设备',
    type: 'pie',
    radius: '55%', // 饼图的半径 可以为number string array
    center: ['50%', '50%'], // 饼图的中心(圆心)坐标,数组的第一项是横坐标,第二项是纵坐标。支持设置成百分比,设置成百分比时第一项是相对于容器宽度,第二项是相对于容器高度。
    data: deviceData,
    label: {
      formatter: '{b} {d}% ',
    },
    emphasis: { // 高亮的扇区和标签样式
      itemStyle: { // 所有属性:{ color , borderColor , borderWidth , borderType , shadowBlur , shadowColor , shadowOffsetX , shadowOffsetY , opacity }
        shadowBlur: 10,
        shadowOffsetX: 0,
        shadowColor: 'rgba(0, 0, 0, 0.5)',
      },
    },
  },
],

boxplot图

中文可以称为『箱形图』、『盒须图』、『盒式图』、『盒状图』、『箱线图』,是一种用作显示一组数据分散情况资料的统计图。它能显示出一组数据的最大值、最小值、中位数、下四分位数及上四分位数。

// 声明合并 https://ts.xcatliu.com/basics/declaration-files.html#%E5%9C%A8-npm-%E5%8C%85%E6%88%96-umd-%E5%BA%93%E4%B8%AD%E6%89%A9%E5%B1%95%E5%85%A8%E5%B1%80%E5%8F%98%E9%87%8F
// https://github.com/apache/incubator-echarts/blob/master/extension-src/dataTool/prepareBoxplotData.ts
declare global {
  namespace echarts {
    namespace dataTool {
      function prepareBoxplotData(url: number[][], opt?: {
        boundIQR?: number | 'none';
        layout?: 'horizontal' | 'vertical';
      }): {
        boxData: number[][]; // [low, Q1, Q2, Q3, high]
        outliers: number[][];
        axisData: string[];
      };
    }
  }
}
const data = echarts.dataTool.prepareBoxplotData([
  [850, 740, 900, 1070, 930, 850, 950, 980, 980, 880, 1000, 980, 930, 650, 760, 810, 1000, 1000, 960, 960],
  [960, 940, 960, 940, 880, 800, 850, 880, 900, 840, 830, 790, 810, 880, 880, 830, 800, 790, 760, 800],
  [880, 880, 880, 860, 720, 720, 620, 860, 970, 950, 880, 910, 850, 870, 840, 840, 850, 840, 840, 840],
  [890, 810, 810, 820, 800, 770, 760, 740, 750, 760, 910, 920, 890, 860, 880, 720, 840, 850, 850, 780],
  [890, 840, 780, 810, 760, 810, 790, 810, 820, 850, 870, 870, 810, 740, 810, 940, 950, 800, 810, 870],
]);
series: [
  {
    name: 'boxplot',
    type: 'boxplot', // 箱线图
    data: data.boxData,
    tooltip: {
      formatter(param) {
        const curParam = Array.isArray(param) ? param[0] : param;
        return [
          `Experiment ${curParam.name}: `,
          `upper: ${curParam.data[5]}`,
          `Q3: ${curParam.data[4]}`,
          `median: ${curParam.data[3]}`,
          `Q1: ${curParam.data[2]}`,
          `lower: ${curParam.data[1]}`,
        ].join('<br/>');
      },
    },
  },
  {
    name: 'outlier',
    type: 'scatter', // 散点图用来显示异常值
    data: data.outliers,
  },
],

散点气泡图

// 散点数据series.data
const marksData = [{  name: '点1',  value: [10, 20],
},
{
  name: '点2',
  value: [15, 22],
},
{
  name: '点3',
  value: [34, 51],
},
{
  name: '点4',
  value: [25, 64],
},
{
  name: '点5',
  value: [42, 20],
},
{
  name: '点6',
  value: [32, 15],
},
{
  name: '点7',
  value: [68, 34],
},
{
  name: '点8',
  value: [25, 65],
},
{
  name: '点9',
  value: [45, 56],
},
{
  name: '点10',
  value: [35, 47],
},
];
// 中心线坐标
const centerCoord = [30, 40];
// 中心线series.markLine.data
const centerLine = [{  name: '大盘条均曝光次数 2.4',  xAxis: centerCoord[0],
},
{
  name: '大盘CTR 34.3%',
  yAxis: centerCoord[1],
},
];
// 中心点
// const centerMark = [{//   value: '中心点',//   coord: centerCoord,// }];
// 象限series.markArea.data
const markAreaData = [  // 第一象限  [{    name: '第一象限',    coord: [centerCoord[0], centerCoord[1]],
    itemStyle: {
      color: 'rgba(68, 97, 123, .1)',
    },
    label: {
      position: 'insideTopRight',
      color: 'rgba(0, 0, 0, .1)',
      fontSize: 14,
    },
  }, {
    coord: [Number.MAX_SAFE_INTEGER, Number.MAX_SAFE_INTEGER],
  }],
  // 第二象限
  [{    name: '第二象限',    coord: [0, Number.MAX_SAFE_INTEGER],
    itemStyle: {
      color: 'rgba(68, 97, 123, .1)',
    },
    label: {
      position: 'insideTopLeft',
      color: 'rgba(0, 0, 0, .1)',
      fontSize: 14,
    },
  }, {
    coord: [centerCoord[0], centerCoord[1]],
  }],
  // 第三象限
  [{    name: '第三象限',    coord: [0, 0],
    itemStyle: {
      color: 'rgba(68, 97, 123, .1)',
    },
    label: {
      position: 'insideBottomLeft',
      color: 'rgba(0, 0, 0, .1)',
      fontSize: 14,
    },
  }, {
    coord: [centerCoord[0], centerCoord[1]],
  }],
  // 第四象限
  [{    name: '第四象限',    coord: [centerCoord[0], centerCoord[1]],
    itemStyle: {
      color: 'rgba(68, 97, 123, .1)',
    },
    label: {
      position: 'insideBottomRight',
      color: 'rgba(0, 0, 0, .1)',
      fontSize: 14,
    },
  }, {
    coord: [Number.MAX_SAFE_INTEGER, Number.MIN_SAFE_INTEGER],
  }],
];
// series
const seriesScatter: echarts.EChartOption.SeriesScatter = {
  type: 'scatter',
  data: marksData,
  label: {
    show: true,
    position: 'bottom',
    formatter: '{b}',
  },
  itemStyle: {
    shadowBlur: 2,
    shadowColor: 'rgba(120, 36, 50, 0.5)',
    shadowOffsetY: 1,
    color: 'gray',
    // color: (/* params: object*/) => { // 传入的是数据项 seriesIndex, dataIndex, data, value 等各个参数。
    //   // console.log(params);
    //   const randomColor = `rgba(${Math.floor(Math.random() * 240)},${Math.floor(Math.random() * 240)}
    //     ,${Math.floor(Math.random() * 240)},` + '.8' + ')';
    //   return randomColor;
    // },
  },
  symbolSize: 10, // 设置标记(气泡)大小
  // symbolSize(data: number[]) { // 设置标记(气泡)大小
  //   return data[1];
  // },
  // 各象限区域
  markArea: {
    silent: true, // 图形是否不响应和触发鼠标事件,默认为 false,即响应和触发鼠标事件
    // @ts-ignore
    data: markAreaData,
  },
  // 中心点交集象限轴
  markLine: {
    silent: true, // 是否不响应鼠标事件
    precision: 2, // 精度
    lineStyle: {
      type: 'solid',
      color: blue[6], // '#096dd9'
    },
    label: {
      position: 'insideEndTop',
      formatter: '{b}',
    },
    // @ts-ignore
    data: centerLine,
  },
  // 中心点
  /*
  markPoint: {
    symbol: 'roundRect',
    symbolSize: 15,
    itemStyle: {
      color: 'rgba(234, 85, 6, .8)',
    },
    label: {
      position: 'top',
    },
    // @ts-ignore
    data: centerMark,
  },*/
};
const option: echarts.EChartOption = {
  tooltip: {
    axisPointer: {
      show: true,
      type: 'cross',
      lineStyle: {
        type: 'dashed',
        width: 1,
      },
      label: {
        backgroundColor: '#555',
      },
    },
  },
  grid: {
    left: 50,
    right: 50,
    bottom: '4%',
    top: '6%',
    containLabel: true,
  },
  xAxis: {
    name: '条均曝光次数(曝光次数/在池视频数)',
    nameLocation: 'middle',
    nameTextStyle: {
      verticalAlign: 'top',
      lineHeight: 40,
      color: '#000',
    },
    scale: true, // 不会强制包含零刻度
    axisLine: {
      lineStyle: {
        color: '#ddd',
      },
    },
    axisLabel: {
      color: '#666',
    },
    splitLine: {
      lineStyle: {
        color: '#eee',
      },
    },
  },
  yAxis: {
    scale: true,
    name: 'CTR(播放次数/曝光次数)',
    nameLocation: 'middle',
    nameTextStyle: {
      lineHeight: 40,
      color: '#000',
    },
    axisLine: {
      lineStyle: {
        color: '#ddd',
      },
    },
    axisLabel: {
      color: '#666',
    },
    splitLine: {
      lineStyle: {
        color: '#eee',
      },
    },
  },
  series: [seriesScatter],
};

地图

// https://echarts.apache.org/examples/vendors/echarts/echarts.min.js
// https://echarts.apache.org/examples/vendors/echarts/map/js/china.js

interface IProvinceDataItem {
  name: string;
  value: number;
}

const [provinceData, setProvinceData] = useState<IProvinceDataItem[]>([]); // value值有序

myChart1.current.setOption({
  tooltip: {
    formatter(params) {
      const index = Array.isArray(params) ? params[0].dataIndex : params.dataIndex;
      const percent = getPercentage(provinceData[index || 0].value / provinceTotal);
      return `粉丝所在省份<br>${provinceData[index || 0].name}:${provinceData[index || 0].value}(${percent})`;
    },
  },
  visualMap: [{ // visualMap 是视觉映射组件,用于进行『视觉编码』,也就是将数据映射到视觉元素(视觉通道)。可以定义多个
    min: 0,
    max: provinceData[0].value,
    left: 'left',
    top: 'bottom',
    text: ['高', '低'], // 两端的文本
    inRange: { // 定义 在选中范围中 的视觉元素
      color: ['#e0ffff', '#006edd'],
    },
    show: true,
  }],
  geo: { // 地理坐标系组件
    map: 'china',
    roam: false, // 是否开启鼠标缩放和平移漫游。默认不开启。如果只想要开启缩放或者平移,可以设置成 'scale' 或者 'move'。设置成 true 为都开启
    zoom: 1.23, // 当前视角的缩放比例
    label: {
      normal: {
        show: true,
        fontSize: '10',
        color: 'rgba(0,0,0,0.7)',
      },
    },
    itemStyle: {
      normal: {
        borderColor: 'rgba(0, 0, 0, 0.2)',
      },
      emphasis: { // 高亮状态下的多边形和标签样式
        areaColor: '#F3B329',
        shadowOffsetX: 0,
        shadowOffsetY: 0,
        shadowBlur: 20,
        borderWidth: 0,
        shadowColor: 'rgba(0, 0, 0, 0.5)',
      },
    },
  },
  series: [
    {
      name: '粉丝量',
      type: 'map',
      geoIndex: 0, // 默认情况下,map series 会自己生成内部专用的 geo 组件。但是也可以用这个 geoIndex 指定一个 geo 组件。这样的话,map 和 其他 series(例如散点图)就可以共享一个 geo 组件了。并且,geo 组件的颜色也可以被这个 map series 控制,从而用 visualMap 来更改。
      data: provinceData,
    },
  ],
});