ECharts图表教程文档实战案例解析如何制作专业数据图表
说实话,第一次接触数据可视化的时候,我跟我一样懵——面对一堆图表库,选哪个?怎么上手?怎么让图表看起来既专业又不那么”程序员审美”?
今天咱们就从头到尾把ECharts这件事儿掰开揉碎讲清楚。不管你是想做一个炫酷的后台大屏,还是给老板做一个简洁明了的数据报表,这篇文章都能帮到你。
到底什么是ECharts
ECharts是百度开源的一个前端可视化库,现在归Apache管理,全称是ECharts(早期叫Eric’s Charts),现在就是一个功能非常全面的图表库。它支持各种常见的图表类型,折线图、柱状图、饼图、散点图、地图、关系图、雷达图、热力图等等,应有尽有。
最重要的是它免费、文档全、例子多、社区活跃,而且有强大的数据可视化能力。如果你需要做一个数据看板或者管理后台,ECharts基本上是最优先的选择之一。
快速上手:从零开始跑起来
不用装一堆依赖,我们先用最简单的方式体验一下。新建一个index.html文件,把下面的代码复制进去:
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<title>ECharts 第一个示例</title>
<!-- 从CDN引入ECharts -->
<script src="https://cdn.jsdelivr.net/npm/echarts@5/dist/echarts.min.js"></script>
<style>
/* 给图表容器一个明确的高度,这很重要 */
#chart {
width: 100%;
height: 500px;
}
</style>
</head>
<body>
<!-- 图表容器 -->
<div id="chart"></div>
<script>
// 初始化ECharts实例
const myChart = echarts.init(document.getElementById('chart'));
// 配置项
const option = {
title: {
text: '我的第一个ECharts图表'
},
tooltip: {},
xAxis: {
type: 'category',
data: ['一月', '二月', '三月', '四月', '五月', '六月']
},
yAxis: {
type: 'value'
},
series: [{
name: '销量',
type: 'bar',
data: [120, 200, 150, 80, 70, 110],
// 让柱子好看一点
itemStyle: {
color: '#5470c6'
}
}]
};
// 把配置项应用到实例上
myChart.setOption(option);
// 响应式:窗口大小变化时图表跟着自适应
window.addEventListener('resize', () => {
myChart.resize();
});
</script>
</body>
</html>
用浏览器打开这个文件,你就能看到一个漂亮的柱状图了。这就是ECharts最简单的用法,核心就三步:初始化实例 → 设置配置项 → 渲染到页面。
常见的图表类型及实战配置
1. 折线图:展示趋势变化
折线图非常适合用来展示一段时间内的数据变化趋势。比如下面这个例子,展示某产品近半年的销量走势:
const lineOption = {
title: {
text: '2024年产品销量趋势',
left: 'center'
},
tooltip: {
trigger: 'axis',
formatter: '{b}月:{c} 万件'
},
legend: {
data: ['线上销量', '线下销量'],
top: 30
},
grid: {
left: '3%',
right: '4%',
bottom: '3%',
containLabel: true
},
xAxis: {
type: 'category',
boundaryGap: false,
data: ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月']
},
yAxis: {
type: 'value',
name: '销量(万件)',
axisLabel: {
formatter: '{value}'
}
},
series: [
{
name: '线上销量',
type: 'line',
smooth: true, // 平滑曲线
data: [320, 332, 341, 354, 390, 430, 440, 460, 480, 520, 560, 600],
itemStyle: { color: '#5470c6' },
areaStyle: { // 面积图效果
color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
{ offset: 0, color: 'rgba(84, 112, 198, 0.5)' },
{ offset: 1, color: 'rgba(84, 112, 198, 0.05)' }
])
}
},
{
name: '线下销量',
type: 'line',
smooth: true,
data: [220, 250, 280, 310, 350, 380, 400, 420, 450, 480, 500, 520],
itemStyle: { color: '#91cc75' }
}
]
};
这里面有几个值得注意的点:
smooth: true让折线变得圆润,比生硬的折线好看很多areaStyle给折线图加上渐变的填充区域,视觉层次感立刻就有了formatter可以自定义提示框的内容,让数据展示更清晰containLabel: true保证坐标轴的标签不会被裁剪
2. 柱状图:对比各类别数据
柱状图适合展示不同类别之间的对比关系。这个例子展示各部门的业绩对比:
const barOption = {
title: {
text: '各部门季度业绩对比',
left: 'center'
},
tooltip: {
trigger: 'axis',
axisPointer: { type: 'shadow' }
},
legend: {
data: ['Q1', 'Q2', 'Q3', 'Q4'],
top: 30
},
grid: {
left: '3%',
right: '4%',
bottom: '3%',
containLabel: true
},
xAxis: {
type: 'category',
data: ['销售部', '技术部', '市场部', '运营部', '人事部', '财务部']
},
yAxis: {
type: 'value',
name: '业绩(万元)'
},
series: [
{
name: 'Q1',
type: 'bar',
data: [120, 80, 90, 70, 40, 50],
itemStyle: { color: '#5470c6' }
},
{
name: 'Q2',
type: 'bar',
data: [132, 95, 101, 85, 55, 62],
itemStyle: { color: '#91cc75' }
},
{
name: 'Q3',
type: 'bar',
data: [148, 110, 115, 96, 60, 70],
itemStyle: { color: '#fac858' }
},
{
name: 'Q4',
type: 'bar',
data: [162, 125, 130, 110, 75, 88],
itemStyle: { color: '#ee6666' }
}
]
};
如果是想要横向的柱状图(适合类别名称比较长的时候),只需要把xAxis和yAxis互换一下就行,type: 'bar'改成横着的,代码改动非常小:
// 横向柱状图只需要交换xAxis和yAxis的type
xAxis: { type: 'value', name: '业绩(万元)' },
yAxis: { type: 'category', data: ['销售部', '技术部', '市场部', '运营部', '人事部', '财务部'] }
3. 饼图:展示占比关系
饼图适合展示各部分占整体的比例。下面是一个用户来源占比的例子:
const pieOption = {
title: {
text: '用户来源分布',
subtext: '2024年度统计',
left: 'center'
},
tooltip: {
trigger: 'item',
formatter: '{b}: {c} ({d}%)'
},
legend: {
orient: 'vertical',
left: 'left',
top: 'center'
},
series: [
{
name: '用户来源',
type: 'pie',
radius: ['40%', '70%'], // 环形图,比实心饼图更现代
center: ['60%', '50%'],
avoidLabelOverlap: false,
itemStyle: {
borderRadius: 10,
borderColor: '#fff',
borderWidth: 2
},
label: {
show: true,
formatter: '{b}\n{d}%',
fontSize: 12
},
emphasis: {
label: { show: true, fontSize: 16, fontWeight: 'bold' }
},
data: [
{ value: 1048, name: '搜索引擎' },
{ value: 735, name: '直接访问' },
{ value: 580, name: '邮件营销' },
{ value: 484, name: '联盟广告' },
{ value: 300, name: '视频广告' }
]
}
]
};
这里用了环形图(radius: ['40%', '70%']),环形图比传统的实心饼图在视觉上更现代,而且中心区域可以用来放一些补充信息。
4. 散点图:发现数据规律
散点图适合展示两个变量之间的关系,可以用来发现数据中的规律和异常值。比如下面这个展示广告投入与销售额关系的例子:
const scatterOption = {
title: {
text: '广告投入与销售额关系分析',
subtext: '每个点代表一次营销活动',
left: 'center'
},
tooltip: {
formatter: function(params) {
return `广告投入: ${params.value[0]}万元<br/>销售额: ${params.value[1]}万元`;
}
},
grid: {
left: '8%',
right: '10%',
bottom: '10%',
containLabel: true
},
xAxis: {
type: 'value',
name: '广告投入(万元)',
nameLocation: 'middle',
nameGap: 30
},
yAxis: {
type: 'value',
name: '销售额(万元)',
nameLocation: 'middle',
nameGap: 50
},
series: [{
type: 'scatter',
symbolSize: function(data, params) {
// 用气泡大小表示第三个维度——利润
return Math.sqrt(params.value[2]) * 3;
},
data: [
[10, 80, 20], [20, 150, 35], [30, 220, 50], [40, 300, 60],
[50, 380, 80], [60, 450, 90], [70, 520, 100], [80, 580, 110],
[90, 650, 120], [100, 700, 130], [15, 120, 25], [25, 180, 40],
[35, 260, 55], [45, 340, 70], [55, 420, 85], [65, 490, 95],
[75, 560, 105], [85, 620, 115], [95, 680, 125], [110, 780, 140]
],
itemStyle: {
color: function(params) {
// 根据利润值设置颜色,利润越高颜色越暖
const profit = params.value[2];
if (profit > 100) return '#ee6666';
if (profit > 70) return '#fac858';
return '#5470c6';
},
opacity: 0.7
}
}]
};
这个例子有一个巧思——散点图的大小(symbolSize)根据第三个维度(利润)来动态计算,这样就变成了气泡图,一个图表里同时展示了三个维度的信息。
5. 地图:地域数据可视化
如果你需要展示地域相关的分布数据,ECharts的地图功能非常强大。以中国地图为例:
// 首先注册地图
echarts.registerMap('china', chinaMapData);
const geoOption = {
title: {
text: '全国各省销售额分布',
left: 'center'
},
tooltip: {
trigger: 'item',
formatter: '{b}<br/>销售额: {c} 万元'
},
visualMap: {
min: 0,
max: 500,
left: 'left',
top: 'bottom',
text: ['高', '低'],
calculable: true,
inRange: {
color: [' #f0f9e8', '#bae4bc', '#7bccc4', '#43a2ca', '#0868ac']
}
},
series: [
{
name: '销售额',
type: 'map',
map: 'china',
roam: true, // 支持缩放和平移
zoom: 1.2,
label: {
show: true,
fontSize: 10
},
emphasis: {
label: { fontSize: 12 },
itemStyle: { areaColor: '#f4a460' }
},
data: [
{ name: '广东', value: 480 },
{ name: '江苏', value: 420 },
{ name: '浙江', value: 390 },
{ name: '山东', value: 350 },
{ name: '河南', value: 280 },
{ name: '四川', value: 250 },
{ name: '湖北', value: 220 },
{ name: '湖南', value: 200 },
{ name: '福建', value: 190 },
{ name: '安徽', value: 170 },
{ name: '河北', value: 160 },
{ name: '辽宁', value: 140 },
{ name: '陕西', value: 130 },
{ name: '江西', value: 120 },
{ name: '云南', value: 100 }
]
}
]
};
visualMap 是地图配色的关键配置,它可以根据数据值自动给不同区域上色,形成热力图的视觉效果。roam: true 让用户可以自由缩放和平移地图,交互体验更好。
主题和配色:让图表看起来专业
很多初学者做的图表不好看,问题往往不是数据不对,而是配色太丑。ECharts支持主题定制,你可以自己定义一套配色方案。
比如,创建一个深色主题的配置:
// 自定义深色主题
const darkTheme = {
backgroundColor: '#1a1a2e',
textStyle: { color: '#eee' },
title: { textStyle: { color: '#eee' } },
legend: { textStyle: { color: '#aaa' } },
tooltip: {
backgroundColor: 'rgba(30,30,50,0.9)',
borderColor: '#444',
textStyle: { color: '#eee' }
},
axisPointer: { lineStyle: { color: '#555' } },
line: {
itemStyle: { borderWidth: 2 },
lineStyle: { borderWidth: 2 },
symbol: 'circle',
symbolSize: 6
},
bar: {
itemStyle: {
// 柱状图用渐变色
color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
{ offset: 0, color: '#4facfe' },
{ offset: 1, color: '#00f2fe' }
])
}
},
pie: {
itemStyle: { borderWidth: 2, borderColor: '#1a1a2e' }
},
visualMap: {
textStyle: { color: '#aaa' }
},
toolbox: {
iconStyle: { borderColor: '#666' }
},
dataZoom: {
textStyle: { color: '#aaa' }
}
};
// 使用主题
const chart = echarts.init(dom, darkTheme);
一个专业的深色主题能让大屏数据看板看起来档次提升不少。常见的优秀配色方案可以参考这几个:
| 场景 | 推荐配色风格 |
|---|---|
| 后台管理仪表盘 | 清爽明亮,蓝白色调为主 |
| 数据大屏 | 深色背景 + 高亮荧光色 |
| 汇报演示 | 简约专业,低饱和度 |
| 移动端 | 鲜明对比,大字号 |
数据交互:让图表”活”起来
专业的数据图表不只是静态展示,还需要有丰富的交互能力。ECharts提供了多种交互方式:
点击事件:让数据可以下钻
myChart.on('click', function(params) {
// 点击了某个柱状图柱子时的回调
console.log('点击了:', params.name);
console.log('数据:', params.value);
// 可以做一个弹窗或者跳转到详情页面
alert(`你点击了 ${params.name},数据为 ${params.value}`);
});
// 也可以监听数据范围变化的事件
myChart.on('datazoom', function(params) {
// 用户缩放或拖动数据范围时触发
console.log('数据范围变化了');
});
动态更新数据
实际开发中,数据往往是动态变化的,下面这个例子展示了如何定时更新图表数据:
// 模拟实时数据更新
function updateChart() {
const now = new Date();
const timeLabel = now.getHours() + ':' + now.getMinutes() + ':' + now.getSeconds();
const newData = Math.floor(Math.random() * 100) + 50;
myChart.setOption({
xAxis: {
data: [...option.xAxis.data.slice(1), timeLabel] // 移除第一个,添加新的
},
series: [{
data: [...option.series[0].data.slice(1), newData] // 同上
}]
}, false); // false表示不合并,直接替换
// 保持最多20个点
if (option.xAxis.data.length > 20) {
option.xAxis.data.shift();
option.series[0].data.shift();
}
}
// 每秒更新一次
setInterval(updateChart, 1000);
工具栏功能
ECharts内置了丰富的工具箱,一键导出图片、数据视图、动态数据切换、数据区域缩放、还原:
const option = {
// ...其他配置
toolbox: {
feature: {
saveAsImage: { show: true, title: '保存图片' },
dataView: { show: true, title: '数据视图', readOnly: false },
dataZoom: { show: true, title: { zoom: '区域缩放', back: '还原缩放' } },
magicType: {
show: true,
title: { line: '切换折线图', bar: '切换柱状图' },
type: ['line', 'bar']
},
restore: { show: true, title: '还原' }
}
}
};
完整实战:做一个销售数据大屏
光说不练假把式,我们来做一套完整的东西——一个销售数据监控看板:
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>销售数据监控大屏</title>
<script src="https://cdn.jsdelivr.net/npm/echarts@5/dist/echarts.min.js"></script>
<style>
* { margin: 0; padding: 0; box-sizing: border-box; }
body {
background: #0f1923;
color: #fff;
font-family: 'Microsoft YaHei', sans-serif;
min-height: 100vh;
padding: 20px;
}
.header {
text-align: center;
padding: 20px 0;
border-bottom: 2px solid #1e3a5f;
margin-bottom: 20px;
}
.header h1 {
font-size: 28px;
letter-spacing: 4px;
color: #00d4ff;
text-shadow: 0 0 20px rgba(0, 212, 255, 0.5);
}
.header p { color: #668899; font-size: 14px; margin-top: 8px; }
.dashboard {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 20px;
}
.card {
background: #152232;
border-radius: 8px;
padding: 16px;
border: 1px solid #1e3a5f;
box-shadow: 0 4px 20px rgba(0, 0, 0, 0.3);
}
.card.large {
grid-column: span 2;
}
.card-title {
font-size: 14px;
color: #88aacc;
margin-bottom: 12px;
display: flex;
align-items: center;
gap: 8px;
}
.card-title::before {
content: '';
width: 4px;
height: 14px;
background: #00d4ff;
border-radius: 2px;
}
.chart { width: 100%; height: 260px; }
.chart.big { height: 320px; }
.kpi-cards {
display: flex;
gap: 15px;
margin-bottom: 20px;
}
.kpi {
flex: 1;
background: #152232;
border-radius: 8px;
padding: 20px;
text-align: center;
border: 1px solid #1e3a5f;
}
.kpi .number {
font-size: 32px;
font-weight: bold;
color: #00d4ff;
margin: 8px 0;
}
.kpi .label { font-size: 13px; color: #668899; }
.kpi .change { font-size: 12px; margin-top: 6px; }
.kpi .change.up { color: #4caf50; }
.kpi .change.down { color: #f44336; }
</style>
</head>
<body>
<div class="header">
<h1>📊 销售数据监控大屏</h1>
<p id="currentTime">数据更新时间:--</p>
</div>
<div class="kpi-cards">
<div class="kpi">
<div class="label">今日销售额</div>
<div class="number">¥ 1,284,560</div>
<div class="change up">↑ 12.5% 较昨日</div>
</div>
<div class="kpi">
<div class="label">今日订单量</div>
<div class="number">8,432</div>
<div class="change up">↑ 8.3% 较昨日</div>
</div>
<div class="kpi">
<div class="label">活跃用户</div>
<div class="number">23,156</div>
<div class="change down">↓ 2.1% 较昨日</div>
</div>
<div class="kpi">
<div class="label">转化率</div>
<div class="number">4.8%</div>
<div class="change up">↑ 0.5% 较昨日</div>
</div>
</div>
<div class="dashboard">
<div class="card large">
<div class="card-title">销售趋势(近30天)</div>
<div id="trendChart" class="chart big"></div>
</div>
<div class="card">
<div class="card-title">品类分布</div>
<div id="pieChart" class="chart"></div>
</div>
<div class="card">
<div class="card-title">区域销售排名</div>
<div id="barChart" class="chart"></div>
</div>
<div class="card large">
<div class="card-title">全国销售热力分布</div>
<div id="mapChart" class="chart big"></div>
</div>
</div>
<script>
// 更新时间显示
function updateTime() {
const now = new Date();
document.getElementById('currentTime').textContent =
`数据更新时间:${now.toLocaleString('zh-CN')}`;
}
updateTime();
setInterval(updateTime, 60000);
// 通用深色主题配置
const commonTheme = {
backgroundColor: 'transparent',
textStyle: { color: '#ccc' },
title: { textStyle: { color: '#eee' } },
legend: { textStyle: { color: '#88aacc' } },
tooltip: {
backgroundColor: 'rgba(21, 34, 50, 0.95)',
borderColor: '#1e3a5f',
textStyle: { color: '#eee' }
},
axisPointer: { lineStyle: { color: '#334455' } },
dataZoom: {
backgroundColor: '#152232',
fillerColor: 'rgba(0, 212, 255, 0.2)',
handleStyle: { color: '#00d4ff' }
}
};
// 1. 销售趋势图
const trendChart = echarts.init(document.getElementById('trendChart'));
const trendOption = {
...commonTheme,
grid: { left: '3%', right: '4%', bottom: '8%', containLabel: true },
legend: { data: ['销售额', '订单量'], top: 10 },
xAxis: {
type: 'category',
data: Array.from({ length: 30 }, (_, i) => `${i + 1}日`),
axisLine: { lineStyle: { color: '#334455' } },
axisLabel: { color: '#88aacc' }
},
yAxis: [
{
type: 'value',
name: '销售额',
axisLine: { lineStyle: { color: '#334455' } },
axisLabel: { color: '#88aacc', formatter: '{value}' },
splitLine: { lineStyle: { color: '#1e3a5f' } }
},
{
type: 'value',
name: '订单量',
axisLine: { lineStyle: { color: '#334455' } },
axisLabel: { color: '#88aacc' },
splitLine: { show: false }
}
],
series: [
{
name: '销售额',
type: 'line',
smooth: true,
data: [42, 45, 43, 48, 52, 55, 53, 58, 62, 60, 55, 58, 62, 68, 72, 70, 65, 68, 72, 78, 82, 80, 75, 78, 82, 88, 92, 90, 85, 88],
itemStyle: { color: '#00d4ff' },
areaStyle: {
color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
{ offset: 0, color: 'rgba(0, 212, 255, 0.3)' },
{ offset: 1, color: 'rgba(0, 212, 255, 0.02)' }
])
}
},
{
name: '订单量',
type: 'bar',
yAxisIndex: 1,
data: [2800, 3100, 2900, 3200, 3500, 3800, 3600, 3900, 4200, 4000, 3700, 3900, 4100, 4500, 4800, 4600, 4300, 4500, 4800, 5200, 5500, 5300, 5000, 5200, 5500, 5800, 6100, 5900, 5600, 5800],
itemStyle: {
color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
{ offset: 0, color: '#4caf50' },
{ offset: 1, color: 'rgba(76, 175, 80, 0.3)' }
])
}
}
]
};
trendChart.setOption(trendOption);
// 2. 品类分布饼图
const pieChart = echarts.init(document.getElementById('pieChart'));
const pieOption = {
...commonTheme,
tooltip: { trigger: 'item', formatter: '{b}: {c} ({d}%)' },
legend: { orient: 'vertical', left: 'left', top: 'center', textStyle: { color: '#88aacc', fontSize: 11 } },
series: [{
type: 'pie',
radius: ['35%', '65%'],
center: ['60%', '50%'],
avoidLabelOverlap: false,
itemStyle: { borderRadius: 6, borderColor: '#152232', borderWidth: 2 },
label: { show: false },
emphasis: { label: { show: true, fontSize: 13, fontWeight: 'bold', color: '#fff' } },
data: [
{ value: 35, name: '电子产品' },
{ value: 25, name: '服装鞋帽' },
{ value: 18, name: '食品饮料' },
{ value: 12, name: '家居用品' },
{ value: 10, name: '其他' }
]
}]
};
pieChart.setOption(pieOption);
// 3. 区域销售排名柱状图
const barChart = echarts.init(document.getElementById('barChart'));
const barOption = {
...commonTheme,
grid: { left: '3%', right: '8%', bottom: '3%', containLabel: true },
xAxis: { type: 'value', axisLine: { lineStyle: { color: '#334455' } }, axisLabel: { color: '#88aacc' }, splitLine: { lineStyle: { color: '#1e3a5f' } } },
yAxis: { type: 'category', data: ['东北', '西北', '西南', '华北', '华中', '华东', '华南'], axisLine: { lineStyle: { color: '#334455' } }, axisLabel: { color: '#88aacc' } },
series: [{
type: 'bar',
data: [120, 180, 250, 380, 450, 620, 780],
itemStyle: {
borderRadius: [0, 4, 4, 0],
color: function(params) {
const colors = ['#ff6b6b', '#ffa502', '#ffd32a', '#7bed9f', '#70a1ff', '#5352ed', '#00d4ff'];
return colors[params.dataIndex];
}
},
label: { show: true, position: 'right', color: '#aaa', formatter: '{c}万' }
}]
};
barChart.setOption(barOption);
// 4. 地图(简化版,用散点模拟)
const mapChart = echarts.init(document.getElementById('mapChart'));
const mapOption = {
...commonTheme,
grid: { left: '5%', right: '5%', bottom: '5%', top: '10%', containLabel: true },
xAxis: { show: false, min: 70, max: 140 },
yAxis: { show: false, min: 15, max: 55 },
series: [{
type: 'effectScatter',
symbolSize: function(data) { return Math.sqrt(data[2]) * 2; },
data: [
[121.5, 31.2, 780], // 上海
[116.4, 39.9, 620], // 北京
[113.3, 23.1, 580], // 广州
[113.3, 23.1, 450], // 深圳
[120.2, 30.3, 380], // 杭州
[104.1, 30.7, 350], // 成都
[118.8, 32.1, 320], // 南京
[108.9, 34.3, 280], // 武汉
[106.5, 29.5, 250], // 重庆
[114.5, 38.0, 220], // 天津
[120.4, 36.1, 200], // 青岛
[117.2, 39.1, 180], // 石家庄
[118.8, 32.1, 170], // 苏州
[102.7, 25.0, 150], // 昆明
[109.1, 34.3, 140], // 西安
],
itemStyle: {
color: '#00d4ff',
shadowBlur: 10,
shadowColor: '#00d4ff'
},
label: {
show: true,
formatter: function(params) {
return params.data[0].toFixed(1) + '万';
},
position: 'right',
color: '#aaa',
fontSize: 10
},
tooltip: {
formatter: function(params) {
return `${params.data[3] || '城市'}<br/>销售额: ${params.value[2]}万`;
}
}
}]
};
mapChart.setOption(mapOption);
// 响应式适配
window.addEventListener('resize', () => {
trendChart.resize();
pieChart.resize();
barChart.resize();
mapChart.resize();
});
</script>
</body>
</html>
这段代码可以直接保存为HTML文件在浏览器中打开,你会得到一个完整的、风格统一的数据监控大屏。包含了KPI指标卡、趋势折线图、品类饼图、排名柱状图和散点分布图,五个图表各司其职,组合在一起形成了一套完整的数据展示体系。
几个常见问题的解决办法
图表显示不出来?
最常见的原因是容器没有明确的高度。ECharts需要知道容器多大才能正确渲染,所以一定要给图表的父容器设置height,或者直接用CSS指定。
#chart { width: 100%; height: 400px; }
数据太多了图表很卡?
如果数据量超过几千条,可以考虑:
- 使用
sampling: 'lttb'对数据进行采样 - 改用 WebGL 渲染(
renderer: 'canvas'换成 WebGL 引擎) - 增加分页或数据聚合
series: [{
type: 'line',
sampling: 'lttb', // 使用LTTB采样算法,减少点数但保持视觉形状
data: largeDataset
}]
想导出成图片给老板看?
ECharts内置了导出功能,只需一行代码:
// 导出PNG图片
const url = chart.getInstance().getDataURL({
type: 'png',
pixelRatio: 2, // 2倍分辨率,更清晰
backgroundColor: '#fff'
});
const a = document.createElement('a');
a.href = url;
a.download = '图表.png';
a.click();
总结一下
做专业的数据图表其实没有你想象的那么难。核心就是三个要点:
第一,选对图表类型。 趋势用折线,对比用柱状,占比用饼图,分布用散点,关系用关系图,地域用地图。这个思路搞清楚了,就成功了一半。
第二,做好配色和布局。 别贪多,颜色别超过5种,留白要多,重点数据要突出。一个好的图表应该是”一眼就能看出什么意思”的。
第三,不要忽略交互。 工具栏、提示框、点击事件这些交互功能虽然代码量不大,但能让你的图表从”展示”变成”探索”,用户体验提升非常显著。
ECharts的文档本身也写得非常详细,官方文档地址是 echarts.apache.org,里面有几百个实例可以参考。遇到不确定的配置项,直接去实例里搜索,基本都能找到答案。
现在你已经了解了ECharts的基本用法和实战技巧了,不妨动手试一试,把自己的数据放进去看看效果。数据可视化这件事,练得多了自然就会了。
