ECharts 基础使用

本文代码中令myChart为一个echarts实例(echartsInstance)

基本原理为先设置好装图表的容器,然后再在option中指定图表的配置项和数据

最后通过 myChart.setOption(option)显示图表

图表容器及大小

初始化

先在html中定义一个有宽度,高度的div节点,通过下列代码初始化一个echarts实例

1
var myChart = echarts.init(document.getElementById('xxx'));

也可以为不存在宽度高度的容器指定宽度,高度

1
2
3
4
var myChart = echarts.init(document.getElementById('main'), null, {
width: 600,
height: 400
});

响应容器大小

让图表大小实时根据容器的大小进行变化

1
2
3
4
5
6
7
var myChart = echarts.init(document.getElementById('main'));
window.onresize = function() {
myChart.resize({
width: 800,
height: 400
});
};

销毁容器节点

1
myChart.dispose()

坐标轴

x轴 y轴

xAxis, yAxis

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
option = {
xAxis: {
type: 'time',
//x轴type可选value(连续数据),category(离散数据),time(时序数据),log(对数数据)
name: '销售时间
axisLabel: {
show: true, //是否显示刻度标签
interval: 0 //隔几个标签显示一个标签,若为0,即为显示全部标签
},
data: [] //x轴数据
// ...
},
yAxis: {
type: 'value',
name: '销售数量'
// ...
}
// ...
};

轴线

利用axisLine设置轴线的样式

1
2
3
4
5
6
7
8
9
10
xAxis: {
axisLine: {
symbol: 'arrow',
length: 6 //调整刻度
lineStyle: {
type: 'dashed'
//...
}
}
}

刻度标签

利用axisLabel配置标签

1
2
3
4
5
6
7
8
xAxis: {
axisLabel: {
formatter: '{value} kg',
align: 'center'
// ...
}
// ...
},

数据集

在系列中设置数据

将数据设置在series中:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
option = {
xAxis: {
type: 'category',
data: ['Matcha Latte', 'Milk Tea', 'Cheese Cocoa', 'Walnut Brownie']
},
yAxis: {},
series: [
{
type: 'bar',
name: '2015',
data: [89.3, 92.1, 94.4, 85.4]
},
{
type: 'bar',
name: '2016',
data: [95.8, 89.4, 91.2, 76.9]
},
{
type: 'bar',
name: '2017',
data: [97.7, 83.1, 92.5, 78.1]
}
]
};

实际应用可参考官方文档中的示例:https://echarts.apache.org/handbook/zh/get-started