# Echarts

返回开源:前端 | 别处阅读

# 如何隐藏坐标轴

坐标轴

Echarts 中 options 对象有 xAxis、yAxis 参数,可以控制是否显示坐标轴、坐标轴刻度标签、坐标轴轴线、坐标轴刻度、分割线等

yAxis: { // y轴
 type: 'value',
 show: false, // 是否显示坐标轴
 data: [],
 axisLabel: { show: false }, // 坐标轴刻度标签
 axisLine: { show: false }, // 坐标轴轴线
 axisTick: { show: false }, // 坐标轴刻度
 splitLine: { show:false } // 分割线
}
1
2
3
4
5
6
7
8
9

# 柱形图如何设置柱子渐变和圆角

itemStyle

主要通过 itemStyle 属性,color 来设置渐变,barBorderRadius 属性设置圆角,遵循 css 左上、右上、右下、左下顺序。同时下方代码加了柱子数值 label 配置。barWidth 是柱子宽度。

series: [
  {
    type: "bar",
    barWidth: 40, // 柱子宽度
    label: {
      show: true,
      position: "top", // 位置
      color: "#1CD8A8",
      fontSize: 14,
      fontWeight: "bold", // 加粗
      distance: 20, // 距离
    }, // 柱子上方的数值
    itemStyle: {
      barBorderRadius: [20, 20, 0, 0], // 圆角(左上、右上、右下、左下)
      color: new echarts.graphic.LinearGradient(
        0,
        1,
        0,
        0,
        ["#2FAEF2", "#1CD8A8"].map((color, offset) => ({ color, offset }))
      ), // 渐变
    },
    data: [10, 52, 200, 334, 390, 330, 220],
  },
];
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25

# 柱形图柱子阴影

柱子阴影

从上方 series 可以看出,接收的数组类型的。所以我们在加一个,同样的 type,不过数据,我们在每个值上+100,做成阴影即可。

var data = [10, 52, 200, 334, 390, 330, 220];
...
series : [{ // 阴影柱形
 type: 'bar',
 barWidth: 40,
 itemStyle: {
 color: 'rgba(167,167,167,0.2)',
 barBorderRadius: [20, 20, 0, 0]
 },
 barGap:'-100%',
 data: data.map(item=>{
 return item+=100
 }),
},
...
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

# 柱形图添加折线

柱形图添加折线

同上方一样,我们还可以再在 series 里面添加 line,同时可以设置折线颜色(lineStyle),折线线条区域颜色(areaStyle)等,都是可以通过 new echarts.graphic.LinearGradient()来设置渐变。

series: [
 ...
 ...
 {
 type:'line',
 smooth: true, // 线条转折有弧度
 symbol: 'circle', // 数值点类型('circle', 'rectangle', 'triangle', 'diamond', 'emptyCircle', 'emptyRectangle', 'emptyTriangle', 'emptyDiamond')
 showSymbol: true,
 symbolSize: 8, // 数值点的大小
 itemStyle: {
 color: ['#1CD8A8']
 },// 数值点的颜色
 lineStyle: {
 width: 2,
 color: new echarts.graphic.LinearGradient(0, 0, 1, 0, [{offset: 0, color: '#2FAEF2'},{offset: 1, color: '#1CD8A8'}])
 }, // 线条渐变
 areaStyle: {
 color: new echarts.graphic.LinearGradient(0, 1, 0, 0, [
 {offset: 0, color: 'rgba(47,174,242,0)'},
 {offset: 0.5, color: 'rgba(34,202,192,0.04)'},
 {offset: 1, color: 'rgba(28,216,168,0.52)'}]
 )
 }, // 线条区域渐变
 data: data, // 折线图的渲染数据
}]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25

# 数据格式

数据格式

只需要在需要格式化的地方,加上 formatter 方法,即可对数据进行格式化。

series: [
 ...
 ...
 {
 type: 'bar',
 barWidth: 12,
 label: {
 show: true,
 position: 'top',
 formatter: (params) => {
 return params.value + '万';
 },
 color: '#1CD8A8',
 fontSize: 14,
 fontWeight: 'bold',
 distance: 25
 },
 ...
 },
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19

# 多数据图表可缩放 dataZoom

缩放

在 options 下可以添加 dataZoom,来控制默认展示位置等。
inslideslide两种 dataZoom,也分 X,Y 轴

  • dataZoom 的运行原理是通过 数据过滤 以及在内部设置轴的显示窗口来达到 数据窗口缩放 的效果。
  • 数据过滤模式(dataZoom.filterMode)的设置不同,效果也不同。
    • 'filter':当前数据窗口外的数据,被 过滤掉。即 会 影响其他轴的数据范围。每个数据项,只要有一个维度在数据窗口外,整个数据项就会被过滤掉。
    • 'weakFilter':当前数据窗口外的数据,被 过滤掉。即 会 影响其他轴的数据范围。每个数据项,只有当全部维度都在数据窗口同侧外部,整个数据项才会被过滤掉。
    • 'empty':当前数据窗口外的数据,被 设置为空。即 不会 影响其他轴的数据范围。
    • 'none': 不过滤数据,只改变数轴范围。
  • 如何设置,由用户根据场景和需求自己决定。经验来说:
    • 当『只有 X 轴 或 只有 Y 轴受 dataZoom 组件控制』时,常使用 filterMode: 'filter',这样能使另一个轴自适应过滤后的数值范围。
    • 当『X 轴 Y 轴分别受 dataZoom 组件控制』时:
      • 如果 X 轴和 Y 轴是『同等地位的、不应互相影响的』,比如在『双数值轴散点图』中,那么两个轴可都设为 fiterMode: 'empty'。
      • 如果 X 轴为主,Y 轴为辅,比如在『柱状图』中,需要『拖动 dataZoomX 改变 X 轴过滤柱子时,Y 轴的范围也自适应剩余柱子的高度』,『拖动 dataZoomY 改变 Y 轴过滤柱子时,X 轴范围不受影响』,那么就 X 轴设为 fiterMode: 'filter',Y 轴设为 fiterMode: 'empty',即主轴 'filter',辅轴 'empty'。
...
dataZoom: [{
 id: 'dataZoomX', // 组件 ID。默认不指定。指定则可用于在 option 或者 API 中引用组件。
 show: true, // 是否显示 组件。如果设置为 false,不会显示,但是数据过滤的功能还存在。
 backgroundColor = 'rgba(47,69,84,0)', // 组件的背景颜色。
 dataBackground: { // 数据阴影的样式。
  lineStyle: { // 阴影的线条样式
      // { color , width , type , dashOffset , cap , join , miterLimit , shadowBlur , shadowColor , shadowOffsetX , shadowOffsetY , opacity }
  },
  areaStyle: { // 阴影的填充样式
      // { color , shadowBlur , shadowColor , shadowOffsetX , shadowOffsetY , opacity }
  },
 },
 selectedDataBackground: { // 选中部分数据阴影的样式。如:dataBackground

 },
 fillerColor: 'rgba(167,183,204,0.4)', // 选中范围的填充颜色。
 borderColor: '#ffffff', // 边框颜色。
 handleIcon: 'M-9.35,34.56V42m0-40V9.5m-2,0h4a2,2,0,0,1,2,2v21a2,2,0,0,1-2,2h-4a2,2,0,0,1-2-2v-21A2,2,0,0,1-11.35,9.5Z', // 两侧缩放手柄的 icon 形状,支持路径字符串,可以通过 'image://url' 设置为图片,其中 URL 为图片的链接(URL 为图片链接例如:'image://http://xxx.xxx.xxx/a/b.png'),或者 dataURI(URL 为 dataURI 例如:'image://data:image/gif;base64,R0lGODlhEAAQAMQAAORHHOVSKudfOulrSOp3WOyDZu6QdvCchPGolfO0o/XBs/fNwfjZ0frl3/zy7////wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH5BAkAABAALAAAAAAQABAAAAVVICSOZGlCQAosJ6mu7fiyZeKqNKToQGDsM8hBADgUXoGAiqhSvp5QAnQKGIgUhwFUYLCVDFCrKUE1lBavAViFIDlTImbKC5Gm2hB0SlBCBMQiB0UjIQA7')。
 handleSize: '100%', // 控制手柄的尺寸,可以是像素大小,也可以是相对于 dataZoom 组件宽度的百分比,默认跟 dataZoom 宽度相同。
 handleStyle: { // 两侧缩放手柄的样式配置。
  color: '', // 图形的颜色。支持rgb(255,255,255),rgba(255,255,255,1),#fff等方式设置为纯色
  borderColor: '', // 图形的描边颜色。支持的颜色格式同 color,不支持回调函数。
  borderWidth: 12, // 描边线宽。为 0 时无描边。
  borderType: , // string/number/Array,可选'solid','dashed','dotted',自 v5.0.0 开始,也可以是 number 或者 number 数组,用以指定线条的 dash array,配合 borderDashOffset 可实现更灵活的虚线效果。
  borderDashOffset: 3, // 用于设置虚线的偏移量,可搭配 borderType 指定 dash array 实现灵活的虚线效果。
  borderCap: 'butt', // 用于指定线段末端的绘制方式,可以是:'butt': 线段末端以方形结束。'round': 线段末端以圆形结束。'square': 线段末端以方形结束,但是增加了一个宽度和线段相同,高度是线段厚度一半的矩形区域。
  borderJoin: 'level', // 用于设置2个长度不为0的相连部分(线段,圆弧,曲线)如何连接在一起的属性(长度为0的变形部分,其指定的末端和控制点在同一位置,会被忽略)。可以是:'bevel': 在相连部分的末端填充一个额外的以三角形为底的区域, 每个部分都有各自独立的矩形拐角。'round': 通过填充一个额外的,圆心在相连部分末端的扇形,绘制拐角的形状。 圆角的半径是线段的宽度。'miter': 通过延伸相连部分的外边缘,使其相交于一点,形成一个额外的菱形区域。这个设置可以通过 borderMiterLimit 属性看到效果。默认值为 'bevel'
  borderMiterLimit: 12, // 用于设置斜接面限制比例。只有当 borderJoin 为 miter 时, borderMiterLimit 才有效。
  shadowBlur: 10, // 图形阴影的模糊大小。该属性配合 shadowColor,shadowOffsetX, shadowOffsetY 一起设置图形的阴影效果。
  shadowColor: '#fff',
  shadowOffsetX: 12, // 阴影水平方向上的偏移距离。
  shadowOffsetY: 12, // 阴影垂直方向上的偏移距离。
  opacity: 1, // 图形透明度。支持从 0 到 1 的数字,为 0 时不绘制该图形。
 },
 moveHandleIcon: '', // 同handleIcon
 moveHandleSize: 7// 移动手柄的尺寸高度。
 moveHandleStyle: { // 移动手柄的样式配置。同handleStyle

 },
 labelPrecision: 'auto', // number/string,显示label的小数精度。默认根据数据自动决定。
 labelFormatter: 'aaaa{value}bbbb'// 如果为 string,表示模板,例如:aaaa{value}bbbb,其中{value}会被替换为实际的数值。如果为 Function,表示回调函数,
 showDetail: true, // 是否显示detail,即拖拽时候显示详细数值信息。
 showDataShadow: true, // 是否在 dataZoom-silder 组件中显示数据阴影。数据阴影可以简单地反应数据走势。
 realtime: true, // 拖动时,是否实时更新系列的视图。如果设置为 false,则只在拖拽结束的时候更新。
 textStyle: {
  color: '',
  fontStyle: 'normal', // 'normal','italic','oblique'
  fontWeight: 'normal', //'normal','bold','bolder','lighter',100 | 200 | 300 | 400...
  fontFamily: 'sans-serif', // 还可以是 'serif' , 'monospace', 'Arial', 'Courier New', 'Microsoft YaHei', ...
  fontSize: 12,
  lineHeight; 24,
  width: 24,
  height: 24,
  textBorderColor: '', // 文字本身的描边颜色。
  textBorderWidth: 24,
  textBorderType: '', // 'solid','dashed','dotted',自 v5.0.0 开始,也可以是 number 或者 number 数组,用以指定线条的 dash array,配合 textBorderDashOffset 可实现更灵活的虚线效果。
  textBorderDashOffset: 12,
  textShadowColor: '',
  textShadowBlur: 12,
  textShadowOffsetX: 12,
  textShadowOffsetY: 12,
  overflow: 'none', // 'truncate' 截断,并在末尾显示ellipsis配置的文本,默认为...,'break' 换行,'breakAll' 换行,跟'break'不同的是,在英语等拉丁文中,'breakAll'还会强制单词内换行
  ellipsis: '...', // 在overflow配置为'truncate'的时候,可以通过该属性配置末尾显示的文本。
  lineOverflow: 'truncate', // 文本超出高度部分是否截断,配置height时有效。
 },
 xAxisIndex: 3,
 start: 2, // 数据窗口范围的起始百分比。范围是:0 ~ 100。表示 0% ~ 100%。
 end: 100, // 数据窗口范围的结束百分比。范围是:0 ~ 100。
 startValue: 0, // 数据窗口范围的起始数值。如果设置了 dataZoom-slider.start 则 startValue 失效。dataZoom-slider.startValue 和 dataZoom-slider.endValue 共同用 绝对数值 的形式定义了数据窗口范围。注意,如果轴的类型为 category,则 startValue 既可以设置为 axis.data 数组的 index,也可以设置为数组值本身。 但是如果设置为数组值本身,会在内部自动转化为数组的 index。
 endValue: 4, // 数据窗口范围的结束数值。如果设置了 dataZoom-slider.end 则 endValue 失效。
 minSpan: 12, // 用于限制窗口大小的最小值(百分比值),取值范围是 0 ~ 100。如果设置了 dataZoom-slider.minValueSpan 则 minSpan 失效。
 maxSpan: 23, // 用于限制窗口大小的最大值(百分比值),取值范围是 0 ~ 100。如果设置了 dataZoom-slider.minValueSpan 则 maxSpan 失效。
 minValueSpan: 12, // 用于限制窗口大小的最小值(实际数值)。
 maxValueSpan: 23, // 用于限制窗口大小的最大值(实际数值)。
 orient: 'horizontal', // 'horizontal':水平。'vertical':竖直。
 zoomLock: true, // 是否锁定选择区域(或叫做数据窗口)的大小。如果设置为 true 则锁定选择区域的大小,也就是说,只能平移,不能缩放。
 throttle: 100, // 设置触发视图刷新的频率。单位为毫秒(ms)。如果 animation 设为 true 且 animationDurationUpdate 大于 0,可以保持 throttle 为默认值 100(或者设置为大于 0 的值),否则拖拽时有可能画面感觉卡顿。如果 animation 设为 false 或者 animationDurationUpdate 设为 0,且在数据量不大时,拖拽时画面感觉卡顿,可以把尝试把 throttle 设为 0 来改善。
}],
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79

# labelFormatter

/**
 * @param {*} value 如果 axis.type 为 'category',则 `value` 为 axis.data 的 index。
 *                  否则 `value` 是当前值。
 * @param {strign} valueStr 内部格式化的结果。
 * @return {string} 返回最终的label内容。
 */
labelFormatter: function (value) {
    return 'aaa' + value + 'bbb';
}
1
2
3
4
5
6
7
8
9

# xAxisIndex

option: {
    xAxis: [
        {...}, // 第一个 xAxis
        {...}, // 第二个 xAxis
        {...}, // 第三个 xAxis
        {...}  // 第四个 xAxis
    ],
    dataZoom: [
        { // 第一个 dataZoom 组件
            xAxisIndex: [0, 2] // 表示这个 dataZoom 组件控制 第一个 和 第三个 xAxis
        },
        { // 第二个 dataZoom 组件
            xAxisIndex: 3      // 表示这个 dataZoom 组件控制 第四个 xAxis
        }
    ]
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

# 图例 legend 详细参数

legend: {
    show: true, //是否显示
    type: "plain", // 图例的类型 'plain':普通图例  'scroll':可滚动翻页的图例
    zlevel: 1, // 所有图形的 zlevel 值。
    icon: "circle",
    top: "5%", // bottom:"20%" // 组件离容器的距离
    right: "5%", //left:"10%"  // // 组件离容器的距离
    width: "auto", // 图例组件的宽度
    height: "auto", // 图例组件的高度
    orient: "horizontal", // 图例列表的布局朝向。 'horizontal'  'vertical'
    align: "auto", // 图例标记和文本的对齐
    padding: 5, // 图例内边距
    itemWidth: 6, // 图例标记的图形宽度。
    itemGap: 20, // 图例每项之间的间隔。
    itemHeight: 14, //  图例标记的图形高度。
    symbolKeepAspect: true, // 如果图标(可能来自系列的 symbol 或用户自定义的 legend.data.icon)是 path:// 的形式,是否在缩放时保持该图形的长宽比。
    formatter: function (name) {
    return '{a|text}{a|   }{b|' +  name + '}'
    },
    selectedMode: true, // 图例选择的模式,
    inactiveColor: "#ccc", // 图例关闭时的颜色。
    textStyle: {
    color: "#556677", // 文字的颜色。
    fontStyle: "normal", // 文字字体的风格。
    fontWeight: "normal", // 文字字体的粗细。 'normal' 'bold'  'bolder' 'lighter'  100 | 200 | 300 | 400...
    fontFamily: "sans-serif", // 文字的字体系列。
    fontSize: 12, // 文字的字体大小。
    lineHeight: 20, // 行高。
    backgroundColor: "transparent", // 文字块背景色。
    borderColor: "transparent", // 文字块边框颜色。
    borderWidth: 0, // 文字块边框宽度。
    borderRadius: 0, // 文字块的圆角。
    padding: 0, // 文字块的内边距
    shadowColor: "transparent", // 文字块的背景阴影颜色
    shadowBlur: 0, // 文字块的背景阴影长度。
    shadowOffsetX: 0, // 文字块的背景阴影 X 偏移。
    shadowOffsetY: 0, // 文字块的背景阴影 Y 偏移。
    // width: 50, // 文字块的宽度。 默认
    // height: 40, // 文字块的高度 默认
    textBorderColor: "transparent", // 文字本身的描边颜色。
    textBorderWidth: 0, // 文字本身的描边宽度。
    textShadowColor: "transparent", // 文字本身的阴影颜色。
    textShadowBlur: 0, // 文字本身的阴影长度。
    textShadowOffsetX: 0, // 文字本身的阴影 X 偏移。
    textShadowOffsetY: 0, // 文字本身的阴影 Y 偏移。
    rich: {
    a: {
        color: "red",
        lineHeight: 10,
    },
        b: {
        color: "#fff",
        lineHeight: 10,
    },
    }, // 自定富文本样式
    },
},

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58

# 视图里面加阴影提示:tooltip,提示框组件

  • show,默认 true,是否显示提示框组件
  • trigger,触发类型,item、axis、none,当为 none 的时候代表什么都不触发,就不会显示提示框
  • axisPointer,坐标轴指示器配置项,实际上坐标轴指示器的全部功能,都可以通过轴上的 axisPointer 配置项完成。
    • axisPointer 的 type 类型:
      • 1、'line' 直线指示器
      • 2、'shadow' 阴影指示器
      • 3、'none' 无指示器
      • 4、'cross' 十字准星指示器。其实是种简写,表示启用两个正交的轴的 axisPointer。
  • label 属性加 formatter 函数,可以格式化提示框显示内容
tooltip: {
  trigger: 'item', // 'item':数据项图形触发,主要在散点图,饼图等无类目轴的图表中使用。'axis':坐标轴触发,主要在柱状图,折线图等会使用类目轴的图表中使用。在 ECharts 2.x 中只支持类目轴上使用 axis trigger,在 ECharts 3 中支持在直角坐标系和极坐标系上的所有类型的轴。并且可以通过 axisPointer.axis 指定坐标轴。'none':什么都不触发。
  axisPointer:{ // 坐标轴指示器配置项。
    type: 'line', // 'line' 直线指示器,'shadow' 阴影指示器,'none' 无指示器,'cross' 十字准星指示器。其实是种简写,表示启用两个正交的轴的 axisPointer。
    axis: 'auto', // 指示器的坐标轴。默认情况,坐标系会自动选择显示哪个轴的 axisPointer(默认取类目轴或者时间轴)。可以是 'x', 'y', 'radius', 'angle'。
    snap: true, // 坐标轴指示器是否自动吸附到点上。默认自动判断。
    label: { // { show , precision , formatter , margin , color , fontStyle , fontWeight , fontFamily , fontSize , lineHeight , width , height , textBorderColor , textBorderWidth , textBorderType , textBorderDashOffset , textShadowColor , textShadowBlur , textShadowOffsetX , textShadowOffsetY , overflow , ellipsis , lineOverflow , padding , backgroundColor , borderColor , borderWidth , shadowBlur , shadowColor , shadowOffsetX , shadowOffsetY }

    },
  },
  showContent: true, // 是否显示提示框浮层,默认显示。只需tooltip触发事件或显示axisPointer而不需要显示内容时可配置该项为false。
  formatter: '{a}', // 提示框浮层内容格式器,支持字符串模板和回调函数两种形式。
}
1
2
3
4
5
6
7
8
9
10
11
12
13

# tooltip formatter

1.字符串模板

模板变量有 {a}, {b},{c},{d},{e},分别表示系列名,数据名,数据值等。 在 trigger 为 'axis' 的时候,会有多个系列的数据,此时可以通过 {a0}, {a1}, {a2} 这种后面加索引的方式表示系列的索引。 不同图表类型下的 {a},{b},{c},{d} 含义不一样。 其中变量{a}, {b}, {c}, {d}在不同图表类型下代表数据含义为(formatter: '{b0}: {c0}<br />{b1}: {c1}'):

  • 折线(区域)图、柱状(条形)图、K线图 : {a}(系列名称),{b}(类目值),{c}(数值), {d}(无)
  • 散点图(气泡)图 : {a}(系列名称),{b}(数据名称),{c}(数值数组), {d}(无)
  • 地图 : {a}(系列名称),{b}(区域名称),{c}(合并数值), {d}(无)
  • 饼图、仪表盘、漏斗图: {a}(系列名称),{b}(数据项名称),{c}(数值), {d}(百分比)

2.回调函数

回调函数格式:

(params: Object|Array, ticket: string, callback: (ticket: string, html: string)) => string | HTMLElement | HTMLElement[]
1
第一个参数 params 是 formatter 需要的数据集。格式如下:

{
    componentType: 'series',
    // 系列类型
    seriesType: string,
    // 系列在传入的 option.series 中的 index
    seriesIndex: number,
    // 系列名称
    seriesName: string,
    // 数据名,类目名
    name: string,
    // 数据在传入的 data 数组中的 index
    dataIndex: number,
    // 传入的原始数据项
    data: Object,
    // 传入的数据值。在多数系列下它和 data 相同。在一些系列下是 data 中的分量(如 map、radar 中)
    value: number|Array|Object,
    // 坐标轴 encode 映射信息,
    // key 为坐标轴(如 'x' 'y' 'radius' 'angle' 等)
    // value 必然为数组,不会为 null/undefied,表示 dimension index 。
    // 其内容如:
    // {
    //     x: [2] // dimension index 为 2 的数据映射到 x 轴
    //     y: [0] // dimension index 为 0 的数据映射到 y 轴
    // }
    encode: Object,
    // 维度名列表
    dimensionNames: Array<String>,
    // 数据的维度 index,如 0 或 1 或 2 ...
    // 仅在雷达图中使用。
    dimensionIndex: number,
    // 数据图形的颜色
    color: string,


    // 饼图的百分比
    percent: number,
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39

示例

formatter: params => {
  // console.info(params, '00000000000');
  let dateNum = params[0].axisValue || '';
  if (dateNum.length === 1) {
    dateNum = `0${dateNum}`;
  }
  let res = `${(searchTime || '').substring(0, 8)}${dateNum}`;
  for (let i = 0; i < params.length; i += 1) {
    res += `<br/>${params[i].marker}${params[i].seriesName}${params[i].value}`
  }
  return res;
}
1
2
3
4
5
6
7
8
9
10
11
12

# echarts 柱状图,每根柱子显示不同颜色(随机显示和定制显示)

series: [
  {
    name: "降水量",
    type: "bar",
    label: {
      normal: {
        show: true,
        position: "top",
      },
    },
    itemStyle: {
      normal: {
        // 随机显示
        //color:function(d){return "#"+Math.floor(Math.random()*(256*256*256-1)).toString(16);}

        // 定制显示(按顺序)
        color: function(params) {
          var colorList = [
            "#C33531",
            "#EFE42A",
            "#64BD3D",
            "#EE9201",
            "#29AAE3",
            "#B74AE5",
            "#0AAF9F",
            "#E89589",
            "#16A085",
            "#4A235A",
            "#C39BD3 ",
            "#F9E79F",
            "#BA4A00",
            "#ECF0F1",
            "#616A6B",
            "#EAF2F8",
            "#4A235A",
            "#3498DB",
          ];
          return colorList[params.dataIndex];
        },
      },
    },
    data: [
      32.6,
      25.9,
      39.0,
      26.4,
      28.7,
      70.7,
      75.6,
      82.2,
      48.7,
      58.8,
      16.0,
      32.3,
    ],
  },
];
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
series: {
      name:'日用电量',
      type:'bar',//不同类型的图,值不一样
      smooth: true,
      barWidth:50,
      data:data,//也是后台数据传来 ["-0.16", "0.14"]
      itemStyle:{
        normal:{
          //每个柱子的颜色即为colorList数组里的每一项,如果柱子数目多于colorList的长度,则柱子颜色循环使用该数组
          color: function (params){
            //我这边就两个柱子,大体就两个柱子颜色渐变,所以数组只有两个值,多个颜色就多个值
            var colorList = [['#0679e3','#3d97ed','#90c1fc'],['#07b8d9','#62c4db','#86e9fc']];
                          var index=params.dataIndex;
                          if(params.dataIndex >= colorList.length){
                                  index=params.dataIndex-colorList.length;
                            }
                  return new echarts.graphic.LinearGradient(0, 0, 0, 1,
                  [
                     {offset: 0, color: colorList[index][0]},
                     {offset: 0.5, color: colorList[index][1]},
                     {offset: 1, color: colorList[index][2]}
                  ]);
          },
          barBorderRadius: 5  //柱状角成椭圆形
        },
     
    }
  },
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28

# 饼图中标签防重叠

 avoidLabelOverlap: true, // 默认就是true
1

# 坐标轴

# x轴坐标值显示不全或者重叠

  • 旋转以使之不重叠(-90~90)
axisLabel: {
  interval: 0, // 设置为0强制显示所有标签,如果设置为1,表示隔一个标签显示一个标签,如果为3,表示隔3个标签显示一个标签
  rotate: 45, // 旋转的角度是-90到90度
}
1
2
3
4
  • 即使旋转,x轴的文字如果太长会受到遮挡,还是显示不全,此时需要grid属性解决
grid: {  
  left: '10%',  
  bottom: '35%',  
}
1
2
3
4
  • 调用formatter文字竖直显示
    • formatter:function(value,index){}
    • value是类目(测试医院A,人民医院),index 是类目索引
axisLabel: {  
  interval: 0,  
  formatter:function(value)  
  {  
      return value.split('').join('\n');  
  }  
} 
1
2
3
4
5
6
7
  • 竖直显示加强版:做一个两个字的加\n的换行
axisLabel: {
  interval: 0,
  formatter:function(value)
  {
      debugger
      var ret = "";//拼接加\n返回的类目项
      var maxLength = 2;//每项显示文字个数
      var valLength = value.length;//X轴类目项的文字个数
      var rowN = Math.ceil(valLength / maxLength); //类目项需要换行的行数
      if (rowN > 1)//如果类目项的文字大于3,
      {
          for (var i = 0; i < rowN; i++) {
              var temp = "";//每次截取的字符串
              var start = i * maxLength;//开始截取的位置
              var end = start + maxLength;//结束截取的位置
              //这里也可以加一个是否是最后一行的判断,但是不加也没有影响,那就不加吧
              temp = value.substring(start, end) + "\n";
              ret += temp; //凭借最终的字符串
          }
          return ret;
      }
      else {
          return value;
      }
  }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
  • X轴类目项隔一个换行
axisLabel: {
  interval: 0,
  formatter:function(value,index)
  {
      if (index % 2 != 0) {
          return '\n\n' + value;
      }
      else {
          return value;
      }
  }
}
1
2
3
4
5
6
7
8
9
10
11
12
  • 超长文本截断显示的几种方法
axisLabel: {
  width: 50,
  overflow: 'truncate', // 1、'truncate' 截断,并在末尾显示ellipsis配置的文本,默认为...,2、'break' 换行,3、'breakAll' 换行,跟'break'不同的是,在英语等拉丁文中,'breakAll'还会强制单词内换行
  ellipsis: '…', // 默认为'...'
}
1
2
3
4
5
axisLabel: {
  // echarts/src/util/format/truncateText
  formatter: (value, index) => truncateText(value, 50, '', '…'),
}
1
2
3
4

# y轴

  • 对数轴的话,注意值不可为0;
  • 如果全部为0,且markLine的值较大,导致处理过程中,所有数据都返回null,导致无法描点

# echarts图表Markline数值自动保存两位小数

TIP

echarts图表Markline遇到了一个情况,明明后端返值为0.025,结果页面显示为0.03,后发现默认保留两位小数,使用toFixed可解决(不足位数会在末尾补零)


marklineData.push(
   {
     name: `XXX(${data[j] - 0})`,
     yAxis: (data[j].value - 0).toFixed(3),
     label: {
       normal: {
            position: 'end',
            formatter: (params) => {
              return `${data[j].warterLevel} ${params.value}`;
            }
          }
         }
        },
1
2
3
4
5
6
7
8
9
10
11
12
13
14

以上位一种解决方案,另一种解决方案则是后台返回时,直接返回字符串,而非数字

# 事件及交互

# React

const zrClick = e => {
    e.getZr().on('click', t => {
      // 空白处的点击行为
      if (!t.target) {
        const point = [t.offsetX, t.offsetY];
        // 点击区域是否在数据展示区里,此处意思为{gridIndex:0}
        //finder If string, e.g., 'geo', means {geoIndex: 0}. If Object, could contain some of these properties below: { seriesIndex / seriesId / seriesName, geoIndex / geoId / geoName, bmapIndex / bmapId / bmapName, xAxisIndex / xAxisId / xAxisName, yAxisIndex / yAxisId / yAxisName, gridIndex / gridId / gridName, … (can be extended) } @param {Array|number} value
        if (e.containPixel('grid', point)) {
          const clickObj = e.convertFromPixel({ seriesIndex: 0 }, point);
          const xIndex = Number(clickObj[0]);
          const seriesObj = e.getOption();
          // console.info(seriesObj)
          const targetData = seriesObj.series[0].data[xIndex] || {};
          const { name } = targetData;
          if (!name) {
            message.warn('无效点击');
            return;
          }
          setTimeObj({ beginTime: `${name} 00:00:00`, endTime: `${name} 23:59:59` })
          handleVisibleChange(true)
        }
      }
    })
  }

// 'click'、 'dblclick'、 'mousedown'、 'mousemove'、 'mouseup'、 'mouseover'、 'mouseout'、 'globalout'、 'contextmenu' 
  const onEvents = {
    click: onChartClick,
  };

// onChartReady: when the chart is ready, will callback the function with the echarts object as it's paramter.
// onEvents:图形点击事件

<ReactEcharts
            onChartReady={zrClick}
            onEvents={onEvents}
            option={getOptions(findChartType(chartType))}
            style={{ width: '100%', flex: 1, marginTop: 12 }}
          />
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39