ECharts 教程
ECharts 教程
ECharts 是百度开源、Apache 顶级项目的 JavaScript 可视化图表库,基于 Canvas/SVG 渲染,提供丰富的图表类型与强大的交互能力,是中国开发者最常用的图表库之一。
核心特性
- 图表丰富:折线、柱状、饼图、散点、地图、雷达、仪表盘、旭日图等 30+ 类型
- 交互强大:缩放、拖拽、联动、数据区域选择
- 大数据量:Canvas 渲染,万级数据流畅
- 高度定制:主题、动画、组件自由配置
- 中文文档:官方文档完善,社区活跃
引入方式
<!-- CDN --> <script src="https://cdn.jsdelivr.net/npm/echarts@5/dist/echarts.min.js"></script> # npm npm install echarts
第一个图表
<div id="main" style="width: 600px; height: 400px;"></div>
<script>
// 初始化
var chart = echarts.init(document.getElementById("main"));
// 配置项
var option = {
title: { text: "销售趋势" },
xAxis: { data: ["周一", "周二", "周三"] },
yAxis: {},
series: [{
type: "line", // 折线图
data: [120, 150, 130]
}]
};
// 渲染
chart.setOption(option);
</script>
学习路线
- 安装与配置语法
- 各图表类型与样式
- 数据加载与数据集
- 交互组件、响应式、视觉映射
- 事件处理与旭日图
ECharts 安装
ECharts 安装
1. CDN 引入
<!-- 最新版 --> <script src="https://cdn.jsdelivr.net/npm/echarts@5/dist/echarts.min.js"></script> <!-- 指定版本 --> <script src="https://cdn.jsdelivr.net/npm/echarts@5.5.0/dist/echarts.min.js"></script> <!-- 国内镜像 --> <script src="https://cdn.bootcdn.net/ajax/libs/echarts/5.5.0/echarts.min.js"></script>
2. npm 安装
# 安装
npm install echarts
# ES Module 引入
import * as echarts from "echarts";
# 按需引入(减小体积)
import * as echarts from "echarts/core";
import { BarChart } from "echarts/charts";
import { TitleComponent, TooltipComponent } from "echarts/components";
import { CanvasRenderer } from "echarts/renderers";
echarts.use([
BarChart, TitleComponent,
TooltipComponent, CanvasRenderer
]);
3. Vue 集成
# vue-echarts 封装
npm install echarts vue-echarts
import { use } from "echarts/core";
import { CanvasRenderer } from "echarts/renderers";
import { LineChart } from "echarts/charts";
import VChart from "vue-echarts";
use([CanvasRenderer, LineChart]);
// 模板中使用
<v-chart :option="option" autoresize />
4. React 集成
# echarts-for-react
npm install echarts echarts-for-react
import ReactECharts from "echarts-for-react";
const option = { xAxis: {}, yAxis: {}, series: [...] };
<ReactECharts option={option} style={{height: 400}} />
5. 验证安装
<div id="demo" style="width:400px;height:300px;"></div>
<script>
var chart = echarts.init(document.getElementById("demo"));
chart.setOption({
series: [{ type: "pie", data: [{value: 1}, {value: 2}] }]
});
</script>
ECharts 配置语法
ECharts 配置语法
1. 配置项结构
var option = {
// 标题
title: {
text: "主标题",
subtext: "副标题",
left: "center"
},
// 提示框
tooltip: {
trigger: "axis" // axis/item
},
// 图例
legend: {
data: ["系列名"]
},
// X 轴
xAxis: {
type: "category", // category/value/time/log
data: ["A", "B", "C"]
},
// Y 轴
yAxis: {
type: "value"
},
// 系列(核心)
series: [{
name: "系列名",
type: "line", // 图表类型
data: [10, 20, 30]
}],
// 工具栏
toolbox: {
feature: {
saveAsImage: {} // 导出图片
}
}
};
2. 图表类型
line 折线图 bar 柱状图 pie 饼图 scatter 散点图 effectScatter 涟漪散点 radar 雷达图 treemap 矩形树图 heatmap 热力图 graph 关系图 map 地图 boxplot 箱线图 sunburst 旭日图 gauge 仪表盘 sankey 桑基图 funnel 漏斗图
3. 坐标系
// 直角坐标(cartesian): xAxis + yAxis
// 极坐标(polar): radiusAxis + angleAxis
// 地理坐标(geo): 地图
// 雷达坐标(radar)
// 单轴(singleAxis): 桑基/热力
xAxis: { type: "category", data: [...] },
yAxis: { type: "value" }
4. 数据格式
// 简单数组
data: [10, 20, 30]
// 键值对象
data: [{name: "A", value: 10}, {name: "B", value: 20}]
// 二维数组(散点)
data: [[10, 20], [30, 40]]
// 多系列
series: [
{ name: "2025", type: "line", data: [1, 2, 3] },
{ name: "2026", type: "line", data: [2, 3, 4] }
]
5. 主题与动画
// 内置主题
echarts.init(el, "dark") // 深色主题
// 全局配置
option = {
color: ["#5470c6", "#91cc75", "#fac858"],
animation: {
duration: 1000,
easing: "cubicOut"
},
backgroundColor: "#fff"
};
ECharts 饼图
ECharts 饼图
1. 基本饼图
<div id="pie" style="width:500px;height:400px;"></div>
<script>
var chart = echarts.init(document.getElementById("pie"));
chart.setOption({
title: { text: "市场份额" },
tooltip: { trigger: "item" },
legend: { bottom: "0%" },
series: [{
type: "pie",
radius: "60%", // 半径
data: [
{ name: "Chrome", value: 65 },
{ name: "Edge", value: 12 },
{ name: "Firefox", value: 8 },
{ name: "Safari", value: 10 },
{ name: "其他", value: 5 }
],
label: {
formatter: "{b}: {d}%" // 名称: 百分比
}
}]
});
</script>
2. 环形图
series: [{
type: "pie",
radius: ["40%", "65%"], // 内径 外径 → 环形
data: [...]
}]
// 中心文字
title: {
text: "总计",
subtext: "100%",
left: "center",
top: "40%"
}
3. 南丁格尔玫瑰图
series: [{
type: "pie",
roseType: "radius", // 玫瑰图模式
radius: ["20%", "70%"],
data: [
{ name: "A", value: 30 },
{ name: "B", value: 50 },
{ name: "C", value: 20 }
]
}]
4. 圆环与间距
series: [{
type: "pie",
radius: ["45%", "65%"],
itemStyle: {
borderRadius: 8, // 扇区圆角
borderColor: "#fff",
borderWidth: 2
},
label: { show: true, formatter: "{b}: {d}%" },
emphasis: {
scale: true, // 悬停放大
scaleSize: 10
}
}]
5. 多层级饼图
// 多个 series 叠加
series: [
{
type: "pie",
radius: ["0%", "40%"],
data: [{name: "总", value: 100}]
},
{
type: "pie",
radius: ["50%", "70%"],
data: [
{name: "A", value: 60},
{name: "B", value: 40}
]
}
]
ECharts 样式设置
ECharts 样式设置
1. 颜色设置
// 全局调色板
option = {
color: ["#5470c6", "#91cc75", "#fac858",
"#ee6666", "#73c0de", "#3ba272"]
};
// 单系列颜色
series: [{
type: "bar",
itemStyle: { color: "#5470c6" }
}]
// 渐变(线性)
itemStyle: {
color: {
type: "linear",
x: 0, y: 0, x2: 0, y2: 1, // 从上到下
colorStops: [
{ offset: 0, color: "#5470c6" },
{ offset: 1, color: "#91cc75" }
]
}
}
// 径向渐变
color: {
type: "radial",
x: 0.5, y: 0.5, r: 0.5,
colorStops: [
{ offset: 0, color: "#fff" },
{ offset: 1, color: "#5470c6" }
]
}
2. 文字样式
title: {
text: "标题",
textStyle: {
color: "#333",
fontSize: 18,
fontWeight: "bold",
fontFamily: "PingFang SC"
}
},
label: {
color: "#666",
fontSize: 12
},
axisLabel: {
color: "#999",
fontSize: 12
}
3. 线条与区域
series: [{
type: "line",
lineStyle: {
color: "#5470c6",
width: 3,
type: "solid" // solid/dashed/dotted
},
itemStyle: { color: "#5470c6" },
areaStyle: { // 面积填充
color: "rgba(84,112,198,0.2)"
},
symbol: "circle", // 标记形状
symbolSize: 8
}]
4. 网格与背景
option = {
backgroundColor: "#f8f9fa",
grid: {
left: "3%",
right: "4%",
bottom: "3%",
containLabel: true
},
xAxis: {
axisLine: { lineStyle: { color: "#999" } },
splitLine: { show: false }
},
yAxis: {
splitLine: {
lineStyle: { color: "#eee", type: "dashed" }
}
}
};
5. 主题定制
// 注册自定义主题
var theme = {
color: ["#ff6b6b", "#4ecdc4", "#45b7d1"],
backgroundColor: "#fff"
};
echarts.registerTheme("myTheme", theme);
var chart = echarts.init(el, "myTheme");
// 官方主题下载
// https://echarts.apache.org/zh/theme-builder.html
ECharts 异步加载数据
ECharts 异步加载数据
1. 异步 setOption
var chart = echarts.init(document.getElementById("main"));
// 先显示加载动画
chart.showLoading({
text: "数据加载中..."
});
// 异步请求数据
fetch("/api/chart-data")
.then(res => res.json())
.then(data => {
chart.hideLoading();
chart.setOption({
xAxis: { data: data.labels },
series: [{ type: "bar", data: data.values }]
});
});
2. 时间轴动态加载
// 按日期切换加载
option = {
timeline: {
data: ["2026-01", "2026-02", "2026-03"],
onChange: function(index) {
loadMonthData(index);
}
},
baseOption: { ... },
options: [] // 各时间点配置
};
3. 定时刷新
// 实时数据
setInterval(function() {
fetch("/api/live")
.then(r => r.json())
.then(data => {
chart.setOption({
series: [{ data: data }]
});
});
}, 5000);
// 增量添加数据
setInterval(function() {
chart.setOption({
xAxis: { data: newLabels },
series: [{ data: newValues }]
});
}, 1000);
4. 加载状态控制
// 显示加载
chart.showLoading({
color: "#5470c6",
text: "努力加载中...",
textColor: "#666",
maskColor: "rgba(255,255,255,0.8)"
});
// 隐藏加载
chart.hideLoading();
// 错误处理
fetch(...).catch(err => {
chart.hideLoading();
chart.clear();
alert("数据加载失败: " + err);
});
ECharts 数据集(dataset)
ECharts 数据集(dataset)
1. 什么是 dataset
dataset 组件用于管理数据,实现数据与图表的解耦,数据可以是表格(二维)或对象形式。
2. 表格数据
option = {
dataset: {
source: [
["产品", "销量", "利润"],
["A", 120, 30],
["B", 150, 40],
["C", 130, 35]
]
},
xAxis: { type: "category" },
yAxis: {},
series: [
{ type: "bar", seriesLayoutBy: "column" }, // 按列
{ type: "bar", seriesLayoutBy: "column" }
]
};
3. 对象数据
dataset: {
dimensions: ["name", "sales", "profit"],
source: [
{ name: "A", sales: 120, profit: 30 },
{ name: "B", sales: 150, profit: 40 }
]
},
series: [
{ type: "bar", encode: { x: "name", y: "sales" } },
{ type: "bar", encode: { x: "name", y: "profit" } }
]
4. 行列转换
// 行布局(每个 series 一行)
series: [
{ type: "bar", seriesLayoutBy: "row" },
{ type: "bar", seriesLayoutBy: "row" }
]
// 与 grid 配合多图
grid: [
{ left: "5%", right: "55%", top: "10%" },
{ right: "5%", top: "10%" }
]
5. 数据转换(transform)
// 数据过滤
dataset: [{
source: [...]
}, {
transform: {
type: "filter",
config: { dimension: "sales", ">": 100 }
}
}]
// 数据排序
transform: {
type: "sort",
config: { dimension: "sales", order: "desc" }
}
ECharts 交互组件
ECharts 交互组件
1. toolbox 工具栏
option = {
toolbox: {
feature: {
saveAsImage: { title: "保存图片" },
restore: { title: "还原" },
dataView: { title: "数据视图" },
dataZoom: { title: "缩放" },
magicType: {
title: { line: "折线", bar: "柱状" },
type: ["line", "bar"]
}
}
}
};
2. dataZoom 缩放
option = {
// 内置缩放条(底部)
dataZoom: [{
type: "inside", // 滚轮缩放
start: 0,
end: 40
}, {
type: "slider", // 滑块
height: 20,
bottom: 10
}]
};
3. dataZoom 联动
// 两个图联动缩放
grid: [{ bottom: "25%" }, { top: "70%" }],
xAxis: [{ gridIndex: 0 }, { gridIndex: 1 }],
yAxis: [{ gridIndex: 0 }, { gridIndex: 1 }],
dataZoom: [{
type: "slider",
xAxisIndex: [0, 1], // 同时作用于两个 x 轴
start: 0,
end: 50
}]
4. 视觉组件
// 图例选择
legend: {
data: ["系列1", "系列2"],
selected: { "系列1": true }
},
// visualMap 视觉映射
visualMap: {
min: 0,
max: 100,
calculable: true, // 可拖拽
inRange: { color: ["#50a3ba", "#eac736", "#d94e5d"] }
}
5. 提示框联动
tooltip: {
trigger: "axis",
axisPointer: {
type: "cross" // cross/shadow/line
}
},
// 多个图联动 tooltip
// axisPointer.link 连接
axisPointer: {
link: [{ xAxisIndex: "all" }]
}
ECharts 响应式
ECharts 响应式
1. 容器自适应
// 监听窗口变化
var chart = echarts.init(document.getElementById("main"));
window.addEventListener("resize", function() {
chart.resize();
});
// 或使用 resize 观察器
new ResizeObserver(() => chart.resize())
.observe(document.getElementById("main"));
2. 响应式配置
// 根据宽度调整配置
function getOption(width) {
return {
grid: {
left: width < 600 ? "10%" : "5%"
},
legend: {
position: width < 600 ? "bottom" : "top"
}
};
}
window.addEventListener("resize", () => {
chart.setOption(getOption(window.innerWidth));
chart.resize();
});
3. 移动端适配
option = {
// 小屏隐藏部分组件
legend: {
show: window.innerWidth > 600,
top: 0
},
// 数据点标签小屏隐藏
label: {
show: window.innerWidth > 768
},
grid: {
left: window.innerWidth > 600 ? "3%" : "10%"
}
};
4. 初始尺寸
// 容器必须有宽度
// 隐藏容器初始化问题
// 方案:容器显示后再 init
function initChart() {
if (container.offsetWidth > 0) {
chart = echarts.init(container);
chart.setOption(option);
} else {
setTimeout(initChart, 200); // 延迟重试
}
}
ECharts 数据的视觉映射
ECharts 数据的视觉映射
1. visualMap 组件
// 连续型视觉映射
option = {
visualMap: {
type: "continuous", // continuous/piecewise
min: 0,
max: 100,
dimension: 0, // 映射数据维度
calculable: true, // 可拖拽手柄
inRange: {
color: ["#50a3ba", "#eac736", "#d94e5d"]
},
text: ["高", "低"]
},
series: [{
type: "scatter",
data: [[10, 20], [50, 60], [90, 80]]
}]
};
2. 分段型视觉映射
visualMap: {
type: "piecewise",
pieces: [
{ min: 80, label: "优秀" },
{ min: 60, max: 79, label: "良好" },
{ min: 40, max: 59, label: "及格" },
{ max: 39, label: "不及格" }
],
inRange: {
color: ["#2ecc71", "#f1c40f", "#e67e22", "#e74c3c"]
}
}
3. 映射到多种视觉通道
visualMap: {
inRange: {
color: ["#5470c6", "#fac858"], // 颜色
symbolSize: [10, 50] // 大小
}
}
// 热力图使用
series: [{
type: "heatmap",
data: [[0, 0, 10], [1, 0, 30], [2, 0, 80]],
visualMap: {
min: 0, max: 100,
inRange: { color: ["#313695", "#f7fbff"] }
}
}]
ECharts 事件处理
ECharts 事件处理
1. 图表事件
var chart = echarts.init(document.getElementById("main"));
// 点击事件
chart.on("click", function(params) {
console.log("点击了:", params.name);
console.log("值:", params.value);
console.log("系列:", params.seriesName);
});
// 鼠标移入
chart.on("mouseover", function(params) {
console.log("悬停:", params.name);
});
// 图例切换
chart.on("legendselectchanged", function(params) {
console.log("图例状态:", params.selected);
});
// 数据缩放
chart.on("datazoom", function(params) {
console.log("缩放范围:", params.start, "-", params.end);
});
2. 事件参数
chart.on("click", function(params) {
// params 包含
params.name // 数据名
params.value // 数据值
params.seriesName // 系列名
params.seriesIndex // 系列索引
params.dataIndex // 数据索引
params.data // 原始数据
params.event // 原生事件
params.type // 事件类型
});
3. 组件事件
// tooltip 显示
chart.on("showTip", function(params) {
console.log("显示提示:", params.name);
});
// 点击图例
chart.on("legendselectchanged", ...);
// 点击工具栏
chart.on("saveAsImage", ...);
// 坐标轴区域选择
chart.on("brushEnd", function(params) {
console.log("框选区域:", params.areas);
});
4. 事件联动
// 点击图表联动其他图表
var chart1 = echarts.init(el1);
var chart2 = echarts.init(el2);
chart1.on("click", function(params) {
// 根据点击更新 chart2
chart2.setOption({
series: [{ data: getDetail(params.name) }]
});
});
5. 动态添加/移除事件
// 移除事件
chart.off("click");
chart.off("click", handler); // 移除指定处理器
// 触发自定义事件
chart.trigger("click");
ECharts 旭日图
ECharts 旭日图
1. 什么是旭日图
旭日图(sunburst)用于展示层级数据的占比,从内到外逐层细分,是饼图的层级扩展。
2. 基本旭日图
<div id="sunburst" style="width:600px;height:450px;"></div>
<script>
var chart = echarts.init(document.getElementById("sunburst"));
chart.setOption({
title: { text: "销售结构" },
series: [{
type: "sunburst",
data: [
{
name: "电子产品",
children: [
{ name: "手机", value: 50 },
{ name: "电脑", value: 30 },
{ name: "耳机", value: 20 }
]
},
{
name: "家居",
children: [
{ name: "家具", value: 40 },
{ name: "厨具", value: 20 }
]
},
{ name: "服饰", value: 40 }
],
radius: [0, "90%"],
label: { rotate: "radial" }
}]
});
</script>
3. 旭日图样式
series: [{
type: "sunburst",
radius: ["20%", "90%"], // 内径 外径
center: ["50%", "50%"],
sort: "desc", // 排序
itemStyle: {
borderRadius: 4,
borderColor: "#fff",
borderWidth: 2
},
label: {
show: true,
formatter: "{b}\n{d}%",
fontSize: 12
},
emphasis: {
focus: "ancestor" // 聚焦祖先
}
}]
4. 点击交互
chart.on("click", function(params) {
console.log("层级:", params.treePathInfo);
console.log("名称:", params.name);
console.log("值:", params.value);
// 树路径
var path = params.treePathInfo
.map(p => p.name).join(" / ");
alert("路径: " + path);
});
5. 旭日图应用
- 销售结构分析
- 流量来源层级
- 文件空间占用
- 组织架构数据
第 1 / 12 节