快速上手
获取 Apache ECharts
Apache ECharts 支持多种下载方式,我们将在下一篇教程下载和安装中详细介绍。这里我们以从 jsDelivr CDN 获取为例,讲解如何快速安装。
在 https://www.jsdelivr.com/package/npm/echarts 中选择 dist/echarts.js
,点击并另存为 echarts.js
文件。
有关这些文件的更多信息,请参阅下一篇教程下载和安装。
引入 ECharts
在刚才保存 echarts.js
的目录中,新建一个 index.html
文件,内容如下:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<!-- Include the ECharts file you just downloaded -->
<script src="echarts.js"></script>
</head>
</html>
打开这个 index.html
时,你会看到一个空白的页面。但别担心,打开控制台,确保没有报错信息,就可以进行下一步了。
绘制一个简单的图表
在绘制前,我们需要为 ECharts 准备一个定义了高宽的 DOM 容器。在刚才引入的 </head>
标签后添加如下代码:
<body>
<!-- Prepare a DOM with a defined width and height for ECharts -->
<div id="main" style="width: 600px;height:400px;"></div>
</body>
然后你就可以通过 echarts.init 方法初始化一个 ECharts 实例,并通过 setOption 方法设置 ECharts 实例来生成一个简单的柱状图。以下是完整代码:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>ECharts</title>
<!-- Include the ECharts file you just downloaded -->
<script src="echarts.js"></script>
</head>
<body>
<!-- Prepare a DOM with a defined width and height for ECharts -->
<div id="main" style="width: 600px;height:400px;"></div>
<script type="text/javascript">
// Initialize the echarts instance based on the prepared dom
var myChart = echarts.init(document.getElementById('main'));
// Specify the configuration items and data for the chart
var option = {
title: {
text: 'ECharts Getting Started Example'
},
tooltip: {},
legend: {
data: ['sales']
},
xAxis: {
data: ['Shirts', 'Cardigans', 'Chiffons', 'Pants', 'Heels', 'Socks']
},
yAxis: {},
series: [
{
name: 'sales',
type: 'bar',
data: [5, 20, 36, 10, 10, 20]
}
]
};
// Display the chart using the configuration items and data just specified.
myChart.setOption(option);
</script>
</body>
</html>
这就是你用 Apache ECharts 实现的第一个图表!